Problem with empty page when using Apache PDFBox to add image to PDF

痴心易碎 提交于 2019-12-02 00:55:58

Please also have a look at the JavaDocs and sources of the library you try to work with. You create a PDPageContentStream:

PDPageContentStream contents = new PDPageContentStream(doc, page);

This conductor is documented to overwrite all existing content streams of this page:

/**
 * Create a new PDPage content stream. This constructor overwrites all existing content streams
 * of this page.
 *
 * @param document The document the page is part of.
 * @param sourcePage The page to write the contents to.
 * @throws IOException If there is an error writing to the page contents.
 */
public PDPageContentStream(PDDocument document, PDPage sourcePage) throws IOException

Thus, you have to use a different constructor which keeps the current page contents, e.g.

/**
 * 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, appended or prepended.
 * @param compress Tell if the content stream should compress the page contents.
 * @param resetContext Tell if the graphic context should be reset. This is only relevant when
 * the appendContent parameter is set to {@link AppendMode#APPEND}. You should use this when
 * appending to an existing stream, because the existing stream may have changed graphic
 * properties (e.g. scaling, rotation).
 * @throws IOException If there is an error writing to the page contents.
 */
public PDPageContentStream(PDDocument document, PDPage sourcePage, AppendMode appendContent,
                           boolean compress, boolean resetContext) throws IOException

Thus

PDPageContentStream contents = new PDPageContentStream(doc, page, AppendMode.APPEND, true, true);

should make your code work as desired.

Alternatively, if you want the image in the background, try

PDPageContentStream contents = new PDPageContentStream(doc, page, AppendMode.PREPEND, true, true);

Beware, though, in certain cases the image won't be visible in the background, e.g. if the existing content starts with an instruction to fill the whole page area in white. In such a case watermarks must be applied with some kind of transparency atop existing content.

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