打开内容流会将保存的内容清空吗? [英] Opening a content stream blanks saved content?

查看:20
本文介绍了打开内容流会将保存的内容清空吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过向每个页面的页眉添加一些文本来修改现有的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配方。

推荐答案

您使用

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

追加到当前内容。

这篇关于打开内容流会将保存的内容清空吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆