0

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();
    }
Community
  • 1
  • 1
Nicholas DiPiazza
  • 10,029
  • 11
  • 83
  • 152
  • You copy the original file page by page dropping all interactive and document level content. Consider using a `PdfStamper` and selecting the pages you want to keep. – mkl Apr 17 '14 at 22:23

1 Answers1

3

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();
Bruno Lowagie
  • 75,994
  • 9
  • 109
  • 165