I am trying to modify an existing PDF by adding some text to the header of each page. But even the simple sample code I have below ends up generating me a blank PDF as output:
document = PDDocument.load(new File("c:/tmp/pdfbox_test_in.pdf"));
PDPage page = (PDPage) document.getDocumentCatalog().getAllPages().get(0);
PDPageContentStream contentStream = new PDPageContentStream(document, page);
/*
contentStream.beginText();
contentStream.setFont(font, 12);
contentStream.moveTextPositionByAmount(100, 100);
contentStream.drawString("Hello");
contentStream.endText();
*/
contentStream.close();
document.save("c:/tmp/pdfbox_test_out.pdf");
document.close();
(same result whether the commented block is executed or not).
So how is simply opening the content stream and closing it enough to blank the saved document? Is there some other API calls I need to be making in order to not have the content be stripped out?
Surprisingly, I couldn't find a PDFBox recipe for this type of change.
You use
This constructor is implemented like this:
which in turn calls this
So that two-parameter constructor always uses
appendContent = false
which causes all previous content to be deleted.Thus, you should instead use
to append to the current content.
Ugh, apparently the version of PDFBox we are using in our project needs to be upgraded. I just noticed that the latest API has the constructor I need:
So changing to this constructor and using appendContent=true, I got the above sample working. Time for an upgrade...