Similar: How can I remove blank page from PDF in iText
I'm trying to make a generic function that can delete a page from a PDF using iText 5.5.x.
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();
}