【发布时间】:2019-04-16 20:10:53
【问题描述】:
我正在使用此代码:https://www.tutorialspoint.com/pdfbox/pdfbox_inserting_image.htm
帮助我将图像添加到现有 PDF。问题是它创建的文件是一个空白页,上面只有图像。
这是我的代码:
public void signPDF(PdfDTO pdfDTO) throws IOException{
//Loading an existing document
File file = new File(getAbsolutePdfPath(pdfDTO));
PDDocument doc = PDDocument.load(file);
//Retrieving the page
PDPage page = doc.getPage(0);
//a test to ensure the doc is loading correctly
PDDocument testDoc = new PDDocument();
testDoc.addPage(page);
testDoc.save("C:" + File.separator + "Users" + File.separator + "kdotson" + File.separator + "Documents" + File.separator + "test.pdf");
testDoc.close(); //this file is good so I know the doc is loading correctly
//Creating PDImageXObject object
PDImageXObject pdImage = PDImageXObject.createFromFile("C://test_images/signature.pdf", doc);
//creating the PDPageContentStream object
PDPageContentStream contents = new PDPageContentStream(doc, page);
//Drawing the image in the PDF document
contents.drawImage(pdImage, 0, 0);
//Closing the PDPageContentStream object
contents.close();
//Saving the document
doc.save(new File(getSignedPdfLocation(pdfDTO))); //the created file has the image on it, so I know the image is loading correctly
//Closing the document
doc.close();
}
据我所知,我正在做的事情应该可以工作,而且我没有收到任何错误,那是什么?
【问题讨论】:
-
可能与 stackoverflow.com/questions/27919436 重复。请先尝试,如果不起作用,请链接到您的 PDF。
-
@TilmanHausherr 不是重复的,而是密切相关的。这里的问题是由于使用
new PDPageContentStream(doc, page)而导致的失败,解决方案是使用至少具有第三个(附加)参数的构造函数。您链接到的问题中的问题是无法使用new PDPageContentStream(doc, page, true, true),解决方案是使用带有第五个(resetContext)参数的构造函数。人们可能会考虑为所有关于使用哪个PDPageContentStream构造函数的问题创建一个规范的答案。