How to move the content inside a rectangle inside an existing PDF?

My goal is to move text in a PDF around, which is within a certain rectangular area. All content matching the area in the original PDF should be shifted somewhat in the x and y direction. I have no

My goal is to move text in a PDF around, which is within a certain rectangular area. All content matching the area in the original PDF should be shifted somewhat in the x and y direction. I have no influence on how the PDFs are created and I can accept a solution that only vaguely works.

Posted on StackOverflow on Feb 6, 2015 by tom_ink

Suppose that you have a PDF document like this:

Original PDF
Original PDF

I also have the coordinates of a rectangle: new Rectangle(100, 500, 200, 600); and an offset: move everything in that rectangle 10 points to the left and 2 points to the bottom, like this:

Manipulated PDF
Manipulated PDF

That is fairly easy to achieve. Take a look at the CutAndPaste example:

public void manipulatePdf(String src, String dest)
    throws IOException, DocumentException {
    // Creating a reader
    PdfReader reader = new PdfReader(src);
    // step 1
    Rectangle pageSize = reader.getPageSize(1);
    Rectangle toMove = new Rectangle(100, 500, 200, 600);
    Document document = new Document(pageSize);
    // step 2
    PdfWriter writer
        = PdfWriter.getInstance(document, new FileOutputStream(dest));
    // step 3
    document.open();
    // step 4
    PdfImportedPage page = writer.getImportedPage(reader, 1);
    PdfContentByte cb = writer.getDirectContent();
    PdfTemplate template1 = cb.createTemplate(pageSize.getWidth(), pageSize.getHeight());
    template1.rectangle(0, 0, pageSize.getWidth(), pageSize.getHeight());
    template1.rectangle(toMove.getLeft(), toMove.getBottom(),
            toMove.getWidth(), toMove.getHeight());
    template1.eoClip();
    template1.newPath();
    template1.addTemplate(page, 0, 0);
    PdfTemplate template2 = cb.createTemplate(pageSize.getWidth(), pageSize.getHeight());
    template2.rectangle(toMove.getLeft(), toMove.getBottom(),
            toMove.getWidth(), toMove.getHeight());
    template2.clip();
    template2.newPath();
    template2.addTemplate(page, 0, 0);
    cb.addTemplate(template1, 0, 0);
    cb.addTemplate(template2, -20, -2);
    // step 4
    document.close();
    reader.close();
}

Share this article

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