Пожалуйста, ознакомьтесь с JavaDocs и источниками библиотеки, с которой вы пытаетесь работать. Вы создаете PDPageContentStream
:
PDPageContentStream contents = new PDPageContentStream(doc, 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
Таким образом, вы должны использовать другой конструктор, который хранит содержимое текущей страницы, например,
/**
* 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
Таким образом
PDPageContentStream contents = new PDPageContentStream(doc, page, AppendMode.APPEND, true, true);
должен заставить ваш код работать так, как вам нужно.
В качестве альтернативы, если вы хотите изображение в фоновом режиме, попробуйте
PDPageContentStream contents = new PDPageContentStream(doc, page, AppendMode.PREPEND, true, true);
Осторожно, однако, в некоторых случаях изображение не будет видно на заднем плане, например если существующий контент начинается с инструкции, чтобы заполнить всю область страницы белым цветом. В таком случае водяные знаки должны применяться с некоторой прозрачностью поверх существующего контента.