I have a document processing pipeline in which I need to add pages to from a donor document. All examples I have found to clone the donor page do not continue to work after the donor document has been closed. I need to open a donor, pull a page from it, insert it into the document in the pipeline, and then close the donor (or it closes itself when it goes out of scope). I am using PDFBox 2.0.27
My bestapproximation of the solution from StackOverflow 20084117
URL donorUrl = this.class.classLoader.getResource("files/DonorDocument.pdf")
File donorFile = new File(donorUrl.toURI());
PDDocument donorDocument = PDDocument.load(donorFile);
PDPage donorPage = donorDocument.getPage(0);
// trying to clone the page per SO 20084117
COSDictionary donorDictionary = donorPage.getCOSObject(); // they said getCOSDictionary but that is 404
COSDictionary newPageDictionary = new COSDictionary(donorDictionary);
newPageDictionary.removeItem(COSName.ANNOTS);
PDPage newPage = new PDPage(newPageDictionary);
targetDocument.addPage(newPage);
donorDocument.close();
// the following line will return a page which has been closed
targetDocument.getPage(document.numberOfPages - 1);
I aslso tried a number of variations using PDFCloneUtility
PDFCloneUtility cloner = new PDFCloneUtility(donorDocument);
COSBase clonedDOcument = cloner.cloneForNewDocument(donorPage.getCOSObject());
COSDictionary clonedDictionary = clonedDOcument as COSDictionary;
COSDictionary newPageDict = new COSDictionary(clonedDictionary);
PDPage newPage = new PDPage(newPageDict);
targetDocument.addPage(clonePage);
donorDocument.close();
// the following line will return a page which has been closed
targetDocument.getPage(document.numberOfPages - 1);
and
PDFCloneUtility cloner = new PDFCloneUtility(donorDocument);
PDPage clonePage = new PDPage();
cloner.cloneMerge(donorPage, clonePage);
targetDocument.addPage(clonePage);
donorDocument.close();
// the following line will return a page which has been closed
targetDocument.getPage(document.numberOfPages - 1);
edit: this method is one stop in an application pipeline. A donor is selected, opened, added, and then the method exits. If I don’t close the donor document in this method then it closes itself when it goes out of scope.
5