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

Tags: PdfStamperclippingiText 5

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;
    // 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.addTemplate(page, 0, 0);
    PdfTemplate template2 = cb.createTemplate(pageSize.getWidth(), pageSize.getHeight());
    template2.rectangle(toMove.getLeft(), toMove.getBottom(),
            toMove.getWidth(), toMove.getHeight());
    template2.addTemplate(page, 0, 0);
    cb.addTemplate(template1, 0, 0);
    cb.addTemplate(template2, -20, -2);
    // step 4