How to draw lines on an image?

I am trying to draw lines on image that needs to be added to a document, just like we draw graphics on paint event of any control. How is this done?

Posted on StackOverflow on Apr 10, 2015 by Harsh Kumar Singhi

Please take a look at the WatermarkedImages4 example. It is based on the WatermarkedImages1 example. The only difference between the two examples is that we add text in the example written in answer to "How to add text to an image?" whereas we add lines in the example written in answer to your question.

We add images like this:

doc.add(getWatermarkedImage(pdfDoc, new Image(ImageDataFactory.create(imgSrc))));

The getWatermarkedImage() method looks like this:

public Image getWatermarkedImage(PdfDocument pdfDocument, Image img) {
    float width = img.getImageScaledWidth();
    float height = img.getImageScaledHeight();
    PdfFormXObject template = new PdfFormXObject(new Rectangle(width, height));
    new Canvas(template, pdfDocument).add(img);
    new PdfCanvas(template, pdfDocument)
        .saveState()
        .setStrokeColor(Color.GREEN)
        .setLineWidth(3)
        .moveTo(width * .25f, height * .25f)
        .lineTo(width * .75f, height * .75f)
        .moveTo(width * .25f, height * .75f)
        .lineTo(width * .25f, height * .25f)
        .stroke()
        .setStrokeColor(Color.WHITE)
        .ellipse(0, 0, width, height)
        .stroke()
        .restoreState();
    return new Image(template);
}

As you can see, I add two green lines using moveTo(), lineTo() and stroke(). I also add a white ellipse using the ellipse() and stroke() method.

This results in a PDF that looks like this:

Screen shots showing lines added to images in a PDF file

Screen shots showing lines added to images in a PDF file

As you can see, the shape of the ellipse and the position of the lines are different for the different images because I defined my coordinates based on the width and the height of the image.

Click this link if you want to see how to answer this question in iText 5.



Ready to use iText?

Try our iText 7 Library and add-ons FREE for 30 days. Test your proof of concept, and see if our solution is right for you.

Get my FREE trial
Contact

Still have questions? 

We're happy to answer your questions. Reach out to us and we'll get back to you shortly.

Contact us
Stay updated

Join 11,000+ subscribers and become an iText PDF expert by staying up to date with our new products, updates, tips, technical solutions and happenings.

Subscribe Now