我正在使用PDFBOX v2,我试图克隆PDDocument的第一个PDPage,以便将它作为新PDPages的模板。第一页,有一些顶体字段,我需要填充。
我尝试过一些方法,但每个人都让我想要实现。
1)复制第一页内容,并在需要新页时将其添加到文档中。该复制页,但顶体字段与其他页面字段相链接,如果我从第一页修改字段值,则显示在其他页面中。
//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的顶体字段呢?
谢谢!
发布于 2019-04-10 00:00:28
我找到解决办法了!
1)从一个空的pdf模板开始,只有1页。打开模板文档,填充常用数据,并作为byte[]保存在内存中。
PDDocument templatedoc = PDDocument.load(new File(path));
PDDocumentCatalog catalog = templatedoc.getDocumentCatalog();
PDAcroFrom acroForm = catalog.getAcroForm());
... fill acroForm common data of all pages ...
ByteArrayOutputStream basicTemplate = new ByteArrayOutputStream();
templatedoc.save(basicTemplate);
byte[] filledBasicTemplate = basicTemplate.toByteArray();
2)为每个需要的页面生成新文档。
List<PDDocument> documents = new ArrayList<PDDocument>();
PDDocument activeDoc;
for(int i = 0; i < 5; i++) {
activeDoc = PDDocument.load(filledBasicTemplate);
documents.add(activeDoc);
... fill acroform or you need in each page ...
}
( 3)将所有新文件第一页输入最终文件,并保存最后文件。
PDDocument finalDoc = new PDDocument();
for(PDDocument currentDoc : documents) {
... fill common things like page numbers ...
finalDoc.importPage(currentDoc.getPage(0));
}
finalDoc.save(new File(path));
... close all documents after save the final document ...
它可能不是最优化的代码,但它能工作。
https://stackoverflow.com/questions/55571857
复制