Skip to main content
Skip table of contents

How to give an image rounded corners?

I want to get the image width and height and make the edges of the image curved.

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.Add(new iTextSharp.text.Paragraph("Welcome to dotnetfox"));
iTextSharp.text.Image gif =
// gif.ScaleToFit(500, 100);
Posted on StackOverflow on Sep 20, 2014 by Annadate Piyush

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() andgif.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.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);

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.

JavaScript errors detected

Please note, these errors can depend on your browser setup.

If this problem persists, please contact our support.