我正在尝试使用 PDFBox 2.0.1 版向我的 PDF 文件添加 Logo 。我有以下代码:
public class PDFService {
public void createPdf() {
// Create a document and add a page to it
PDDocument document = new PDDocument();
PDPage page = new PDPage();
document.addPage(page);
// Create a new font object selecting one of the PDF base fonts
PDFont font = PDType1Font.HELVETICA_BOLD;
ServletContext servletContext = (ServletContext) FacesContext
.getCurrentInstance().getExternalContext().getContext();
try {
PDImageXObject pdImage = PDImageXObject.createFromFile(
servletContext.getRealPath("/resources/images/logo.png"),
document);
PDPageContentStream contentStream = new PDPageContentStream(
document, page);
contentStream.drawImage(pdImage, 20, 20);
contentStream.beginText();
contentStream.setFont(font, 12);
contentStream.endText();
// Make sure that the content stream is closed:
contentStream.close();
// Save the results and ensure that the document is properly closed:
document.save("Hello World.pdf");
document.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
我收到错误 javax.imageio.IIOException:无法读取输入文件!在行中
PDImageXObject pdImage = PDImageXObject.createFromFile(
servletContext.getRealPath("/resources/images/logo.png"),
document);
servletContext.getRealPath返回的路径是C:\Users\erickpezoa\Desktop\Multivision\Materials\apps\eclipse Kepler\eclipse\Projects\.metadata\.plugins\org.eclipse.core.resources\Servicios_Exequiales\build\weboutput\resources\images\logo.png
我在这里做错了什么?
最佳答案
如果您使用 Maven 并且您的 images 文件夹位于 Eclipse 中的 src/main/resources 下,您可以尝试:
PDImageXObject pdImage = PDImageXObject.createFromFile(
PDFService.class.getResource("/images/logo.png").getPath(),
document);
仅当 src/main/resources
下有另一个名为 resources
的文件夹时,才需要 /resources/images/logo.png
作为路径。或者不使用 Maven,并且您的输出文件夹包含:/resources/images。在这种情况下:
PDImageXObject pdImage = PDImageXObject.createFromFile(
PDFService.class.getResource("/resources/images/logo.png").getPath(),
document);
希望有帮助。
关于java - Apache PDFbox Java 出现错误无法读取输入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37362525/