title: Function that I can use to remove a single page from a PDF using iText
body: <p>Similar: <a href="https://stackoverflow.com/questions/2464166/how-can-i-remove-blank-page-from-pdf-in-itext">How can I remove blank page from PDF in iText</a></p>
  
  <p>I'm trying to make a generic function that can delete a page from a PDF using iText 5.5.x.</p>
  
  <p>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.</p>
  
  <p>Any ideas what is wrong with my code to make it flakey?</p>
  
  <pre><code>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 &lt;= 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();
      }
  </code></pre>