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

Spring Boot中如何将生成的PDF保存至src/main/resources目录

如何在Spring Boot项目的src/main/resources目录保存生成的PDF

嘿,我来帮你搞定把PDF存到Spring Boot的src/main/resources目录这个事儿!不过得先给你提个关键的注意事项:src/main/resources目录在项目打包成JAR/WAR后,会被打包到类路径里,这时候它就不是一个可写的文件系统目录了。所以如果是生产环境,真不建议往这儿写,最好用一个外部的可写目录(比如在配置文件里自定义一个路径)。但如果是开发阶段想存到这里测试,咱们可以这么做:

步骤1:获取src/main/resources的实际物理路径

在Spring Boot里,咱们可以用ResourceLoader来获取这个目录的实际路径,毕竟开发环境下它就是项目里的一个物理文件夹。

步骤2:修改你的PDF生成代码

我把你的PdfGenaratorUtil代码改好了,直接替换就行:

@Component 
public class PdfGenaratorUtil { 
    @Autowired 
    private TemplateEngine templateEngine;
    
    // 注入ResourceLoader来拿到resources目录的路径
    @Autowired
    private ResourceLoader resourceLoader;

    public String createPdf(String templateName, Map map) throws Exception { 
        Assert.notNull(templateName, "The templateName can not be null"); 
        Context ctx = new Context(); 
        if (map != null) { 
            Iterator<Map.Entry> itMap = map.entrySet().iterator(); 
            while (itMap.hasNext()) { 
                Map.Entry pair = itMap.next(); 
                ctx.setVariable(pair.getKey().toString(), pair.getValue()); 
            } 
        } 
        String processedHtml = templateEngine.process(templateName, ctx); 
        FileOutputStream os = null; 
        String fileName = "POLIST "; 
        try { 
            // 获取src/main/resources的实际路径
            Resource resource = resourceLoader.getResource("classpath:");
            File resourcesDir = resource.getFile();
            
            // 在resources目录下创建临时PDF文件
            final File outputFile = File.createTempFile(fileName, ".pdf", resourcesDir); 
            os = new FileOutputStream(outputFile); 
            ITextRenderer renderer = new ITextRenderer(); 
            renderer.setDocumentFromString(processedHtml); 
            renderer.layout(); 
            renderer.createPDF(os, false); 
            renderer.finishPDF(); 
            System.out.println("PDF生成成功,路径:" + outputFile.getAbsolutePath()); 
            return outputFile.toString(); 
        } catch (IOException e) {
            // 这里要处理异常,比如打包成JAR后运行的话,getResource()会报错
            System.err.println("没法写入resources目录哦,大概率是在JAR环境下运行:" + e.getMessage());
            throw e;
        } finally { 
            if (os != null) { 
                try { 
                    os.close(); 
                } catch (IOException e) { 
                    e.printStackTrace();
                } 
            } 
        } 
    } 
}

必看的注意事项

  • 开发/生产环境差异:上面的代码在IDE里跑(开发环境)完全没问题,但如果项目打包成JAR后运行,resource.getFile()会抛出异常——因为这时候resources目录是JAR内部的资源条目,不是文件系统里的文件夹。生产环境推荐这么做:
    在application.properties里加个配置:
    pdf.output.path=/opt/app/pdf-files/
    
    然后在代码里读取这个配置并创建目录:
    @Value("${pdf.output.path}")
    private String pdfOutputPath;
    
    // 先确保目录存在,不存在就创建
    File outputDir = new File(pdfOutputPath);
    if (!outputDir.exists()) {
        outputDir.mkdirs();
    }
    // 然后把PDF写到这个目录里
    final File outputFile = File.createTempFile(fileName, ".pdf", outputDir);
    
  • IDE刷新问题:就算在开发环境,刚生成的PDF可能不会立刻在IDE的src/main/resources目录里显示,你得手动刷新一下项目目录才能看到。

这样应该就能解决你的问题啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 07:29:56