使用PDFBox addPage合并PDF插入固定页后生成全空白页面问题
问题排查与解决方案
问题根源
- 页面资源未同步:PDFBox中
PDPage的内容依赖所属原文档的资源(字体、图像、内容流等),直接调用addPage()将原文档页面添加到新文档时,资源不会自动复制,导致新文档无法渲染页面内容,显示空白。 - 临时文档未关闭:循环中打开的文档
doc和固定页文档doccgv未关闭,会引发资源泄漏,甚至影响页面内容的正常读取。 - 固定页复用错误:直接复用原文档的
cgvpage对象,同样存在资源未同步到新文档的问题。
修正后的代码
// Create final PDF Document PDDocument document = new PDDocument(); // List all pdf files in input folder String[] filenames; File f = new File(context.repertoire_output_docone); filenames = f.list(); // Import the fixed CGV page into the final document first File cgvFile = new File(context.repertoire_advendio + "conf/CGV.pdf"); try (PDDocument cgvDoc = Loader.loadPDF(cgvFile)) { // Import the page to get a copy belonging to the final document PDPage importedCgvPage = document.importPage(cgvDoc.getPage(0)); // Process each PDF file if (filenames != null) { for (String filename : filenames) { // Skip files that don't match the naming pattern if (!filename.startsWith("fact_") && !filename.startsWith("agence_fact_")) { continue; } File targetFile = new File(context.repertoire_output_docone + filename); // Use try-with-resources to auto-close the document try (PDDocument sourceDoc = Loader.loadPDF(targetFile)) { for (PDPage sourcePage : sourceDoc.getPages()) { // Import the source page into the final document document.importPage(sourcePage); // Add the pre-imported CGV page document.addPage(importedCgvPage); } } } } // Save final document String outputPath = context.repertoire_output_docone + "output/docone_" + context.id_legal_entity + "_" + context.input_invoice_date.replace("-", "") + ".pdf"; document.save(outputPath); } finally { // Close the final document document.close(); }
关键修正点
- 用
importPage()替代addPage():该方法会将页面的所有关联资源复制到目标文档,确保内容能正常渲染。 - 使用
try-with-resources自动关闭临时文档:避免资源泄漏,同时保证文档资源正确释放。 - 提前导入固定页:将固定页先导入到最终文档,后续直接复用该导入后的页面对象,确保资源属于最终文档。
内容的提问来源于stack exchange,提问作者RomAZE
相关产品推荐
相关产品推荐

