How to give an image rounded corners?
I'm using iTextSharp to export images into a PDF. Now I want to get the image width and height (while getting the image from disk) and make the edges of image curved (rounded corners). I get and add the image like this:
pdfDoc.Open(); //pdfDoc.Add(new iTextSharp.text.Paragraph("Welcome to dotnetfox")); iTextSharp.text.Image gif = iTextSharp.text.Image.GetInstance(@"C:\images\logoall.bmp"); // gif.ScaleToFit(500, 100); pdfDoc.Add(gif);
Question 1: What is the size of an image?
You have an Image
instance gif
. In iText 7 this is done in the following way:
Image gif = new Image(ImageDataFactory.create("C:\images\logoall.bmp"));
The width and height of this image are gif.getImageScaledWidth() and
gif.getImageScaledHeight()` respectively. There are other ways to get the width and the height, but this way always gives you the size in user units that will be used in the PDF.
If you do not scale the image, above methods will give you the original size of the image in pixels. Pixels will be treated as user units by iText. In PDF, a user unit corresponds with a point by default (and 72 points correspond with 1 inch).
Question 2: How do you display the image with rounded corners?
Some image formats (such as PNG) allow transparency. You could create an image in such a way that the effect of rounded corners is mimicked by making the corners transparent.
If this is not an option, you should apply a clipping path. This is demonstrated in the ClippingPath example in chapter 10 of my book.
public void createPdf(String imgSrc, String dest) throws IOException {
PdfDocument pdfDoc = new PdfDocument(new PdfWriter(dest));
Document doc = new Document(pdfDoc);
ImageData img = ImageDataFactory.create(imgSrc);
Image imgModel = new Image(img);
float w = imgModel.getImageScaledWidth();
float h = imgModel.getImageScaledHeight();
PdfFormXObject xObject = new PdfFormXObject(new Rectangle(850, 600));
PdfCanvas xObjectCanvas = new PdfCanvas(xObject, pdfDoc);
xObjectCanvas.ellipse(0, 0, 850, 600);
xObjectCanvas.clip();
xObjectCanvas.newPath();
xObjectCanvas.addImage(img, w, 0, 0, h, 0, -600);
com.itextpdf.layout.element.Image clipped = new com.itextpdf.layout.element.Image(xObject);
clipped.scale(0.5f, 0.5f);
doc.add(clipped);
doc.close();
}
Of course: this clips the image into an ellipse. You need to replace the ellipse()
method from the example with the roundRectangle()
method, where the last parameter is the expected radius:
xObjectCanvas.roundRectangle(0, 0, 850, 600, 5);
Click How to give an image rounded corners? if you want to see how to answer this question in iText 5.