MaiK
MaiK

Reputation: 101

What is the correct way to deep clone PDPage?

I am working with PDFBOX v2, I'm trying to clone the first PDPage of a PDDocument for keep it as template for new PDPages. That first page, has some acroform fields that I need fill.

I tried some methods but anyone makes I want to achieve.

1) Copy the first page content and add it to the document when I need a new page. That copy the page but the acroform field are linked with other pages fields, and if I modify field value from the first page, that shows in the other pages.

//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) Clone the first page content and then add to the document like the first method. That copy the page but no field is copied :/

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));

Then, what is the correct way to make a deep copy of a PDPage getting acroform fields independent from the first page?

Thanks!

Upvotes: 0

Views: 1225

Answers (1)

MaiK
MaiK

Reputation: 101

I got the solution!

1) Start with an empty pdf template, only has 1 page. Open template document, fill common data and save as byte[] in memory.


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) Generate new document for each needed page.


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) Import all new document first pages into final document and save final document.


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

It maybe not be the most optimized code, but it works.

Upvotes: 0

Related Questions