深度克隆 PDPage 的正确方法是什么?

我正在使用PDFBOX v2,我正在尝试克隆PD文档的第一个PD页面,以将其保留为新PD页面的模板。第一页,有一些我需要填写的杂技字段。


我尝试了一些方法,但任何人都让我想要实现。


1)复制第一页内容,并在我需要新页面时将其添加到文档中。复制页面,但accroform字段与其他页面字段链接,如果我从第一页修改字段值,则会显示在其他页面中。


//Save in variable first page content

COSDictionary pageContent = (COSDictionary)doc.getPage(0).getCOSObject();

...


//when i need insert new page

doc.addPage(new PDPage(pageContent));


2)克隆第一页内容,然后像第一种方法一样添加到文档中。复制页面但没有复制任何字段:/


PDFCloneUtility cloner = new PDFCloneUtility(doc);

COSDictionary pageContent = (COSDictionary)cloner.cloneForNewDocument(doc.getPage(0).getCOSObject());


...


//when i need insert new page

doc.addPage(new PDPage(pageContent));


那么,制作PDPage的深度副本的正确方法是什么,使accroform字段独立于第一页?


谢谢!


冉冉说
浏览 232回答 1
1回答

慕慕森

我得到了解决方案!1)从一个空的pdf模板开始,只有1页。打开模板文档,填充常用数据并另存为内存中的byte[]。PDDocument templatedoc = PDDocument.load(new File(path));&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;PDDocumentCatalog catalog = templatedoc.getDocumentCatalog();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;PDAcroFrom acroForm = catalog.getAcroForm());... fill acroForm common data of all pages ...ByteArrayOutputStream basicTemplate = new ByteArrayOutputStream();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;templatedoc.save(basicTemplate);byte[] filledBasicTemplate = basicTemplate.toByteArray();2)为每个需要的页面生成新文档。List<PDDocument> documents = new ArrayList<PDDocument>();PDDocument activeDoc;for(int i = 0; i < 5; i++) {&nbsp; activeDoc = PDDocument.load(filledBasicTemplate);&nbsp; documents.add(activeDoc);&nbsp; ... fill acroform or you need in each page ...}3)将所有新文档的首页导入最终文档并保存最终文档。PDDocument finalDoc = new PDDocument();for(PDDocument currentDoc : documents) {&nbsp; &nbsp;... fill common things like page numbers ...&nbsp; &nbsp;finalDoc.importPage(currentDoc.getPage(0));}finalDoc.save(new File(path));... close all documents after save the final document ...它可能不是最优化的代码,但它可以工作。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java