I've read the posts How to split a PDF using Apache PDFBox? and How to merge two PDF files into one in Java? However, it only demonstrates how to split it at every page or into equal chucks and the merger apis for addSource() seem to only have File, String and InputStream and not PDDocument.
I would like to insert a one page pdf file into 3 places of a larger pdf file (say 100 pages) at specified pages numbers, e.g. pages 3, 7 and 10. So, I need to split the larger document at page 3, 7, 10, then insert the one page pdf doc, and then merge all the splits parts together in a new pdf file.
I have attempted to do as follows:
PDDocument doc;
PDDocument onePage;
Splitter splitDoc = new Splitter();
PDFMergerUtility mergedDoc = new PDFMergerUtility();
onePage = PDDocument.load("/path/onepage.pdf");
doc = PDDocument.load("/path/hundredpages.pdf");
splitDoc.setSplitAtPage(1); // inefficient
// is there a better solution for split?
List<PDDocument> splitDocs = splitDoc.split(doc);
for (int i=0; i<splitDocs.size(); i++) {
if (i==2 || i==7 || i==10) { // only to demonstrate
mergeFiles.addSource(onePage); // see comment below
} else {
// doesn't accept PDDocument
// what's the alternative without resorting to InputStream
mergeFiles.addSource(splitDocs.remove(0));
}
}
mergedDoc.setDestinationFileName("/path/mergeddoc.pdf");
mergedDoc.mergeDocuments();
Where are my going wrong or is there a better way?