我可以使用iText从PDF中删除单个页面的功能 [英] Function that I can use to remove a single page from a PDF using iText
问题描述
我正在尝试制作一个可以使用iText 5.5.x从PDF中删除页面的通用功能。
I'm trying to make a generic function that can delete a page from a PDF using iText 5.5.x.
我写了一个函数,它通常可以正常工作。但是我得到了用户的抱怨,这个函数曾经有一段时间完全破坏PDF。
I wrote a function and it usually works ok. But I've gotten complaints from users that once and a while the function botches the PDF completely.
我的代码有什么问题让它变得多么糟糕?
Any ideas what is wrong with my code to make it flakey?
public static void removePageFromPDF(File thePDFFile, int pageIndexNotZeroBased) throws InterruptedException, Exception {
PdfReader reader = new PdfReader(thePDFFile.getAbsolutePath());
File tmpNewFile = File.createTempFile("pdfRemoveFile", "pdfouttemp.pdf");
FileOutputStream fos = new FileOutputStream(tmpNewFile);
com.itextpdf.text.Document d = new com.itextpdf.text.Document();
PdfCopy copy = new PdfCopy(d, fos);
d.open();
for (int i = 1; i <= reader.getNumberOfPages(); ++i) {
if (i != pageIndexNotZeroBased) {
copy.addPage(copy.getImportedPage(reader, i));
}
}
copy.freeReader(reader);
reader.close();
d.close();
fos.close();
FileUtils.copyFile(tmpNewFile, thePDFFile);
tmpNewFile.delete();
}
推荐答案
请阅读第6章。您将看到有两种方法可以选择页面,一种使用 PdfCopy
,一种使用 PdfStamper
。使用 PdfStamper
的方法比你拥有的方法简单得多,而且它也更可靠:
Please read chapter 6 of my book. You'll see that there are two method to select pages, one using PdfCopy
and one using PdfStamper
. The method using PdfStamper
is much simpler than what you have, and it's more reliable too:
PdfReader reader = new PdfReader(src);
reader.selectPages("!2");
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));
stamper.close();
这篇关于我可以使用iText从PDF中删除单个页面的功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!