为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

冉冉说 2022-09-28 10:09:57
我正在使用PDFBOX v2,我正在尝试克隆PD文档的第一个PD页面,以将其保留为新PD页面的模板。第一页,有一些我需要填写的杂技字段。我尝试了一些方法,但任何人都让我想要实现。1)复制第一页内容,并在我需要新页面时将其添加到文档中。复制页面,但accroform字段与其他页面字段链接,如果我从第一页修改字段值,则会显示在其他页面中。//Save in variable first page contentCOSDictionary pageContent = (COSDictionary)doc.getPage(0).getCOSObject();...//when i need insert new pagedoc.addPage(new PDPage(pageContent));2)克隆第一页内容,然后像第一种方法一样添加到文档中。复制页面但没有复制任何字段:/PDFCloneUtility cloner = new PDFCloneUtility(doc);COSDictionary pageContent = (COSDictionary)cloner.cloneForNewDocument(doc.getPage(0).getCOSObject());...//when i need insert new pagedoc.addPage(new PDPage(pageContent));那么,制作PDPage的深度副本的正确方法是什么,使accroform字段独立于第一页?谢谢!
查看完整描述

1 回答

?
慕慕森

TA贡献1856条经验 获得超17个赞

我得到了解决方案!


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 ...


它可能不是最优化的代码,但它可以工作。


查看完整回答
反对 回复 2022-09-28
  • 1 回答
  • 0 关注
  • 229 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号