Edit pdf page using pdfbox

Monssef picture Monssef · Jul 16, 2013 · Viewed 20.2k times · Source

How can i edit a pdf page with java and pdfbox by writing in a specific position that i know already in pixels ?

I tried this but it overwrites :

PDDocument document = null;
try {
    document = PDDocument.load(new File("/x/x/x/mypdf.pdf"));
    PDPage page = (PDPage) document.getDocumentCatalog().getAllPages().get(0);
    PDFont font = PDType1Font.HELVETICA_BOLD;
    PDPageContentStream contentStream = new PDPageContentStream(document, page);
    page.getContents().getStream();
    contentStream.beginText();
    contentStream.setFont(font, 12);
    contentStream.moveTextPositionByAmount(100, 100);
    contentStream.drawString("Hello");
    contentStream.endText();
    contentStream.close();
    document.save("/x/x/x/mypdf.pdf");
    document.close();
} catch (IOException e) {
    e.printStackTrace();
} catch (COSVisitorException e) {
    e.printStackTrace();
}

Thank you.

Answer

Anita Kulkarni picture Anita Kulkarni · Oct 18, 2013

You could have used PDFBox, all you are missing is appending to the page. Just change this line:

PDPageContentStream contentStream = new PDPageContentStream(document, page);

to:

PDPageContentStream contentStream = new PDPageContentStream(document, page, true, true);

Starting from PDFBox 2.0, the boolean appendContent has been replaced by the AppendMode APPEND such that the equivalent of the previous code is now:

PDPageContentStream contentStream = new PDPageContentStream(
    document, page, PDPageContentStream.AppendMode.APPEND, true
);