我正在使用 pdfbox 来操作 PDF 内容。我有一个很大的 PDF 文件(比如 500 页)。我还有其他一些仅包含单个图像的单页 PDF 文件,每个文件最大约为 8-15kb。我需要做的是将这些单页 pdf 导入到大 PDF 文件的某些页面上,就像覆盖一样。
我尝试过 pdfbox 的 LayerUtility,我取得了成功,但它创建了一个非常大的文件作为输出。处理前的源 pdf 大小约为 1MB,添加较小的 pdf 文件后,大小将达到 64MB。有时我需要将两个较小的 PDF 包含到较大的 PDF 中。
有没有更好的方法来做到这一点,或者我只是做错了?下面发布代码尝试将两个图层添加到单个页面上:
...
...
..
overlayDoc[pCounter] = PDDocument.load("data\\" + overlay + ".pdf");
outputPage[pCounter] = (PDPage) overlayDoc[pCounter].getDocumentCatalog().getAllPages().get(0);
LayerUtility lu = new LayerUtility( overlayDoc[pCounter] );
form[pCounter] = lu.importPageAsForm( bigPDFDoc, Integer.parseInt(pageNo)-1);
lu.appendFormAsLayer( outputPage[pCounter], form[pCounter], aTrans, "OVERLAY_"+pCounter );
outputDoc.addPage(outputPage[pCounter]);
mOverlayDoc[pCounter] = PDDocument.load("data\\" + overlay2 + ".pdf");
mOutputPage[pCounter] = (PDPage) mOverlayDoc[pCounter].getDocumentCatalog().getAllPages().get(0);
LayerUtility lu2 = new LayerUtility( mOverlayDoc[pCounter] );
mForm[pCounter] = lu2.importPageAsForm(outputDoc, outputDoc.getNumberOfPages()-1);
lu.appendFormAsLayer( mOutputPage[pCounter], mForm[pCounter], aTrans, "OVERLAY_2"+pCounter );
outputDoc.removePage(outputPage[pCounter]);
outputDoc.addPage(mOutputPage[pCounter]);
...
...
使用如下代码,我没有看到任何意外的大小增长:
PDDocument bigDocument = PDDocument.load(BIG_SOURCE_FILE);
LayerUtility layerUtility = new LayerUtility(bigDocument);
List bigPages = bigDocument.getDocumentCatalog().getAllPages();
// import each page to superimpose only once
PDDocument firstSuperDocument = PDDocument.load(FIRST_SUPER_FILE);
PDXObjectForm firstForm = layerUtility.importPageAsForm(firstSuperDocument, 0);
PDDocument secondSuperDocument = PDDocument.load(SECOND_SUPER_FILE);
PDXObjectForm secondForm = layerUtility.importPageAsForm(secondSuperDocument, 0);
// These things can easily be done in a loop, too
AffineTransform affineTransform = new AffineTransform(); // Identity... your requirements may differ
layerUtility.appendFormAsLayer((PDPage) bigPages.get(0), firstForm, affineTransform, "Superimposed0");
layerUtility.appendFormAsLayer((PDPage) bigPages.get(1), secondForm, affineTransform, "Superimposed1");
layerUtility.appendFormAsLayer((PDPage) bigPages.get(2), firstForm, affineTransform, "Superimposed2");
bigDocument.save(BIG_TARGET_FILE);
如你所见我叠加的第一页FIRST_SUPER_FILE
两页目标文件的但我只导入页面一次。因此,该导入页面的资源也仅被导入once.
这种方法也是开放循环的,但是不要多次导入同一页面!相反,将所有必需的模板页面作为表单导入一次,然后在后面的循环中一次又一次地引用这些表单。
(我希望这能解决您的问题。如果没有,请提供更多代码和示例 PDF 来重现您的问题。)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)