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
. The witdh of this image is gif.ScaledWidth
and jpg.ScaledHeight
. 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, ScaledWidth
and ScaledHeight
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.
Ported to C#, the example would be something like this:
Image img = Image.GetInstance(some_path_to_an_image);
float w = img.ScaledWidth;
float h = img.ScaledHeight;
PdfTemplate t = writer.DirectContent.CreateTemplate(w, h);
t.Ellipse(0, 0, w, h);
t.Clip();
t.NewPath();
t.AddImage(img, w, 0, 0, h, 0, -600);
Image clipped = Image.GetInstance(t);
Of course: this clips the image into an ellipse. You need to replace the Ellipse()
method from the example with the RoundRectangle()
method.