You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Web应用Jar包中使用iText添加PDF附件注释遇文件找不到异常

Hey, I've run into exactly this issue before when working with iText and JAR-packaged resources—let me walk you through how to fix it.

The Root Cause

Your problem boils down to how Java handles resources inside JAR files. When you're running in your IDE, the attachment.doc and icon files are regular files on your filesystem, so getResource().getFile() returns a valid path that FileInputStream can use. But once you package everything into a JAR, those resources are no longer independent files—they're entries inside the JAR archive. The path returned by getFile() is a fake "virtual" path that doesn't exist in the real filesystem, hence the FileNotFoundException.

The Fix: Use Input Streams Instead of File Paths

iText's PdfFileSpecification has overloads that accept byte arrays or input streams directly, so you don't need to rely on filesystem paths at all. Here's how to rewrite your code:

Step 1: Update the Attachment Loading Code

Replace the part where you fetch the attachment file with code that reads the resource as an input stream, converts it to a byte array, and passes that to iText:

protected void createAttachment(PdfWriter writer, Rectangle rect, String templatePath, String fileName) throws IOException, DocumentException {
    // Load the attachment from classpath as an input stream
    try (InputStream attachmentStream = getClass().getClassLoader().getResourceAsStream(templatePath)) {
        if (attachmentStream == null) {
            throw new IOException("Could not find resource: " + templatePath);
        }
        // Convert stream to byte array (no external dependencies)
        byte[] attachmentBytes = inputStreamToByteArray(attachmentStream);
        
        // Use the byte array overload of fileEmbedded
        PdfFileSpecification fs = PdfFileSpecification.fileEmbedded(
            writer, null, fileName, attachmentBytes
        );
        
        // Rest of your annotation setup
        PdfAnnotation attachment = PdfAnnotation.createFileAttachment(writer, rect, fileName, fs);
        
        // Fix the icon loading too (same issue applies!)
        try (InputStream iconStream = getClass().getClassLoader().getResourceAsStream(WORD_ICON)) {
            if (iconStream == null) {
                throw new IOException("Could not find icon resource: " + WORD_ICON);
            }
            Image img = Image.getInstance(inputStreamToByteArray(iconStream));
            img.scaleAbsolute(200, 200);
            img.setAbsolutePosition(0, 0);
            
            PdfAppearance app = writer.getDirectContent().createAppearance(200, 200);
            app.addImage(img);
            attachment.setAppearance(PdfAnnotation.APPEARANCE_NORMAL, app);
            
            writer.addAnnotation(attachment);
        }
    }
}

// Helper method to convert input stream to byte array
private byte[] inputStreamToByteArray(InputStream is) throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    byte[] buffer = new byte[1024];
    int bytesRead;
    while ((bytesRead = is.read(buffer)) != -1) {
        baos.write(buffer, 0, bytesRead);
    }
    return baos.toByteArray();
}

Step 2: Verify Your Resource Paths

Make sure your resource paths are correct relative to the JAR's root. From your code, you're using "pdf/attachment.doc"—this means attachment.doc should be in a pdf/ directory at the root of your JAR (not inside the example.pdf package directory). Double-check your build setup (Maven/Gradle) to ensure resources are copied correctly into the JAR during packaging.

Key Takeaways

  • Never use getResource().getFile() for resources in JARs: This method only works for filesystem resources, not archive entries.
  • Use getResourceAsStream() instead: This gives you direct access to the resource's content regardless of whether it's in a JAR or on the filesystem.
  • Fix all resource loading: Don't forget your icon file—you'd hit the same FileNotFoundException there once you fix the attachment.

内容的提问来源于stack exchange,提问作者Xiaoqiang Wang

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 09:35:05