簡體   English   中英

Apache PDFbox Java出現錯誤,無法讀取輸入文件

[英]Apache PDFbox Java getting error Cant read input file

我正在嘗試使用PDFBox 2.0.1版將徽標添加到我的PDF文件中。 我有以下代碼:

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);

希望能幫助到你。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM