Docx4j在AWS Lambda运行报错,本地正常问题求助
Docx4j转PDF在AWS Lambda中只读文件系统异常解决
问题说明
本地运行Docx4j实现的docx转PDF功能正常,部署到AWS Lambda时触发以下异常:
Caused by: java.lang.ExceptionInInitializerError: Exception java.lang.RuntimeException: org.docx4j.fonts.fop.apps.FOPException: java.io.FileNotFoundException: .docx4j (Read-only file system)
已尝试配置临时目录为Lambda可写的/tmp,但问题未解决,原有代码如下:
Docx4jProperties.setProperty("docx4j.openpackaging.parts.TempDir", "/tmp"); System.setProperty("java.io.tmpdir", "/tmp"); String convertedFileName = "/tmp/templFile.pdf"; File file = new File(convertedFileName); WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.load(contents); FileOutputStream fout = new FileOutputStream(convertedFileName); FOSettings foSettings = Docx4J.createFOSettings(); foSettings.setApacheFopMime(MimeConstants.MIME_PDF); foSettings.setWmlPackage(wordMLPackage); Docx4J.toFO(foSettings, fout, Docx4J.FLAG_EXPORT_PREFER_XSL); FileInputStream fin = new FileInputStream(convertedFileName); content = fin.readAllBytes(); fin.close(); file.delete();
问题根源
Docx4j处理字体时会默认在当前工作目录创建.docx4j缓存目录,但AWS Lambda的当前工作目录是只读的,因此触发文件写入权限异常。之前的配置仅覆盖了文档处理的临时目录,未指定字体缓存的存储路径。
解决方案
添加字体缓存目录的配置,将其指向Lambda可写的/tmp路径,并确保目录存在:
修改后的完整代码
// 配置文档处理临时目录 Docx4jProperties.setProperty("docx4j.openpackaging.parts.TempDir", "/tmp"); System.setProperty("java.io.tmpdir", "/tmp"); // 关键配置:指定字体缓存目录到/tmp下的可写路径 Docx4jProperties.setProperty("docx4j.fonts.cacheDir", "/tmp/.docx4j"); // 确保缓存目录存在,避免创建失败 new File("/tmp/.docx4j").mkdirs(); String convertedFileName = "/tmp/templFile.pdf"; WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.load(contents); // 使用try-with-resources自动关闭流,避免资源泄漏 try (FileOutputStream fout = new FileOutputStream(convertedFileName); FileInputStream fin = new FileInputStream(convertedFileName)) { FOSettings foSettings = Docx4J.createFOSettings(); foSettings.setApacheFopMime(MimeConstants.MIME_PDF); foSettings.setWmlPackage(wordMLPackage); Docx4J.toFO(foSettings, fout, Docx4J.FLAG_EXPORT_PREFER_XSL); content = fin.readAllBytes(); } finally { // 清理生成的临时PDF文件 new File(convertedFileName).delete(); }
额外注意事项
- AWS Lambda的
/tmp目录最大存储空间为512MB,若处理大量带特殊字体的docx文件,需定期清理缓存目录或设置缓存过期策略。 - 确保Lambda执行角色拥有
/tmp目录的读写权限(默认已具备)。
内容的提问来源于stack exchange,提问作者Akhildas Mp
相关产品推荐
相关产品推荐

