打开内容流会空白保存的内容?

时间:2014-02-21 16:03:41

标签: pdfbox

我正在尝试通过向每个页面的标题添加一些文本来修改现有PDF。但即使是我在下面的简单示例代码最终也会生成一个空白PDF作为输出:

  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();

(相同的结果是否执行了评论块)。

那么如何简单地打开内容流并关闭它以空白保存的文档?我是否需要进行一些其他API调用才能将内容删除?

令人惊讶的是,我无法找到此类更改的PDFBox配方。

2 个答案:

答案 0 :(得分:3)

您使用

PDPageContentStream contentStream = new PDPageContentStream(document, page);

这个构造函数的实现如下:

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

反过来调用此

/**
 * 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

因此,双参数构造函数始终使用appendContent = false,这会导致所有以前的内容删除

因此,您应该使用

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

附加到当前内容。

答案 1 :(得分:0)

呃,显然我们在项目中使用的PDFBox版本需要升级。我刚才注意到最新的API有我需要的构造函数:

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

所以改为这个构造函数并使用appendContent = true,我得到了上面的示例。 升级的时间......