PDFBox 3.0.4处理带表单PDF文件时出现内容丢失问题
使用PDFBox处理带表单PDF时丢失页面的问题
问题说明
用PDFBox处理一份带表单的PDF文件,仅执行打开文件并另存为新文件的操作,原文档就会丢失3页内容。
复现代码
public static void main(String[] args) { File pdfFile = new File("C:\\Users\\Test\\Documents\\testForms.pdf"); try (PDDocument document = Loader.loadPDF(pdfFile)) { document.save("C:\\Users\\Test\\Documents\\testForms_mod.pdf"); } catch (IOException ex) { Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex); } }
原因分析与解决办法
- 核心原因:该PDF大概率使用了动态XFA表单(XML Forms Architecture),PDFBox对XFA表单的原生支持有限,默认加载逻辑不会处理XFA关联的页面内容,导致保存时丢失对应页面。
- 解决办法1:开启XFA加载支持
加载PDF时设置加载选项,明确启用XFA内容的处理:public static void main(String[] args) { File pdfFile = new File("C:\\Users\\Test\\Documents\\testForms.pdf"); PDFLoadOptions loadOptions = new PDFLoadOptions(); loadOptions.setXfaContent(true); try (PDDocument document = Loader.loadPDF(pdfFile, loadOptions)) { document.save("C:\\Users\\Test\\Documents\\testForms_mod.pdf"); } catch (IOException ex) { Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex); } } - 解决办法2:转换为AcroForm表单
如果不需要保留XFA动态表单特性,可以先用Adobe Acrobat等工具将PDF转换为静态AcroForm表单,再用PDFBox处理,避免页面丢失。 - 解决办法3:升级PDFBox版本
旧版本PDFBox对XFA的支持存在较多缺陷,更换为最新稳定版可解决部分兼容性问题。
内容的提问来源于stack exchange,提问作者rampunseng
相关产品推荐
相关产品推荐

