Pregunta

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.

¿Fue útil?

Solución

You use

PDPageContentStream contentStream = new PDPageContentStream(document, page);

This constructor is implemented like this:

public PDPageContentStream(PDDocument document, PDPage sourcePage) throws IOException
{
    this(document, sourcePage, false, true);
}

which in turn calls this

/**
 * Create a new PDPage content stream.
 *
 * @param document The document the page is part of.
 * @param sourcePage The page to write the contents to.
 * @param appendContent Indicates whether content will be overwritten. If false all previous content is deleted.
 * @param compress Tell if the content stream should compress the page contents.
 * @throws IOException If there is an error writing to the page contents.
 */
public PDPageContentStream(PDDocument document, PDPage sourcePage, boolean appendContent, boolean compress) throws IOException

So that two-parameter constructor always uses appendContent = false which causes all previous content to be deleted.

Thus, you should instead use

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

to append to the current content.

Otros consejos

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:

public PDPageContentStream(PDDocument document, PDPage sourcePage, boolean appendContent, boolean compress)

So changing to this constructor and using appendContent=true, I got the above sample working. Time for an upgrade...

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top