Do this with each page, i.e. from 0 to doc.getNumberOfPages():
PDPage pdPage = doc.getPage(page);
InputStream oldContentStream = pdPage.getContents();
byte[] ba = IOUtils.toByteArray(oldContentStream);
oldContentStream.close();
// brings a warning because a content stream already exists
PDPageContentStream newContentStream = new PDPageContentStream(doc, pdPage, false, true);
// createFromFile is the easiest way with an image file
// if you already have the image in a BufferedImage,
// call LosslessFactory.createFromImage() instead
PDImageXObject pdImage = PDImageXObject.createFromFile(imagePath, doc);
newContentStream.saveGraphicsState();
newContentStream.drawImage(pdImage, 0, 0);
newContentStream.restoreGraphicsState();
newContentStream.close();
// append the saved existing content stream
PDPageContentStream newContentStream2 = new PDPageContentStream(doc, pdPage, true, true);
newContentStream2.appendRawCommands(ba); // deprecated... needs to be rediscussed among devs
newContentStream2.close();
There is another way to do it which is more painful IMHO, getting a iterator of PDStream objects from the page with getContentStreams(), build a List, and insert the new stream at the beginning, and reassign this PDStream list to the page with setContents(). I can add this as an alternative solution if needed.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…