Remove page from PDF

2019-01-26 09:16发布

问题:

I'm currently using iText and I'm wondering if there is a way to delete a page from a PDF file?

I have opened it up with a reader etc., and I want to remove a page before it is then saved back to a new file; how can I do that?

回答1:

The 'better' way to 'delete' pages is doing

reader.selectPages("1-5,10-12");

Which means we only select pages 1-5, 10-12 effectively 'deleting' pages 6-9.



回答2:

Get the reader of existing pdf file by

PdfReader pdfReader = new PdfReader("source pdf file path");

Now update the reader by

 reader.selectPages("1-5,15-20");

then get the pdf stamper object to write the changes into a file by

PdfStamper pdfStamper = new PdfStamper(pdfReader,
                new FileOutputStream("destination pdf file path"));

close the PdfStamper by

pdfStamper.close();

It will close the PdfReader too.

Cheers.....



回答3:

You can use a PdfStamper in combination with PdfCopy.

In this answer it is explained how to copy a whole document. If you change the criteria for the loop in the sample code you can remove the pages you don't need.



回答4:

Here is a removing function ready for real life usage. Proven to work ok with itext 2.1.7. It does not use "strigly typing" also.

/**
 * Removes given pages from a document.
 * @param reader    document
 * @param pagesToRemove pages to remove; 1-based
 */
public static void removePages(PdfReader reader, int... pagesToRemove) {
    int pagesTotal = reader.getNumberOfPages();
    List<Integer> allPages = new ArrayList<>(pagesTotal);
    for (int i = 1; i <= pagesTotal; i++) {
        allPages.add(i);
    }
    for (int page : pagesToRemove) {
        allPages.remove(new Integer(page));
    }
    reader.selectPages(allPages);
}


回答5:

For iText 7 I found this example:

    PdfReader pdfReader = new PdfReader(PATH + name + ".pdf");
    PdfDocument srcDoc = new PdfDocument(pdfReader);
    PdfDocument resultDoc = new PdfDocument(new PdfWriter(PATH + name + "_cut.pdf"));
    resultDoc.initializeOutlines();

    srcDoc.copyPagesTo(1, 2, resultDoc);

    resultDoc.close();
    srcDoc.close();

See also here: clone-reordering-pages and here: clone-splitting-pdf-file



标签: java pdf itext