【发布时间】:2016-06-28 03:20:11
【问题描述】:
我已经阅读了 How to split a PDF using Apache PDFBox? 和 How to merge two PDF files into one in Java? 的帖子,但是,它只演示了如何在每个页面上将其拆分或分成相等的卡盘,并且 addSource() 的合并 api 似乎只有 File em>、String 和 InputStream 和 not PDDocument。
我想将一个单页 pdf 文件插入到指定页码的较大 pdf 文件(例如 100 页)的 3 个位置,例如第 3、7 和 10 页。因此,我需要在第 3、7、10 页拆分较大的文档,然后插入一页 pdf 文档,然后将所有拆分部分合并到一个新的 pdf 文件中。
我尝试过如下操作:
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();
我哪里出错了或者有更好的方法吗?
【问题讨论】:
-
我的回答有帮助还是您还有问题?