我正在尝试使用apache PDFBOX将图像保存到现有的pdf中,但是当我将图像放在pdf顶部时,我的内容将被删除,并且会得到空白文档,是否可以解决此问题? / p>
我的代码看起来像这样。
public class TestPdfImage {
public static void main(String args[]) throws Exception {
//Loading an existing document
File file = new File("...../mydoc.pdf");
PDDocument doc = PDDocument.load(file);
//Retrieving the page
PDPage page = doc.getPage(0);
//Creating PDImageXObject object
PDImageXObject pdImage = PDImageXObject.createFromFile("...../sample.png",doc);
//creating the PDPageContentStream object
PDPageContentStream contents = new PDPageContentStream(doc, page);
//Drawing the image in the PDF document
contents.drawImage(pdImage, 70, 250);
System.out.println("Image inserted");
//Closing the PDPageContentStream object
contents.close();
//Saving the document
doc.save(".../sample.pdf");
//Closing the document
doc.close();
}
}
答案 0 :(得分:0)
尝试使用附加模式
//creating the PDPageContentStream object
PDPageContentStream contents = new PDPageContentStream(doc, page, AppendMode.APPEND, true);
编辑
提尔曼·豪瑟(TilmanHausherr)提到
new PDPageContentStream(doc, page, AppendMode.APPEND, true, true);