How to move the content inside a rectangle inside an existing PDF?
Posted on StackOverflow on Feb 6, 2015 by tom_ink
Suppose that you have a PDF document like this:
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
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();
}