Opening a content stream blanks saved content?

て烟熏妆下的殇ゞ 提交于 2019-12-24 19:05:57

问题


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.


回答1:


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.




回答2:


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...



来源:https://stackoverflow.com/questions/21939267/opening-a-content-stream-blanks-saved-content

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!