Remove page from PDF

前端 未结 5 630
日久生厌
日久生厌 2020-12-19 00:40

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

相关标签:
5条回答
  • 2020-12-19 01:10

    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);
    }
    
    0 讨论(0)
  • 2020-12-19 01:14

    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

    0 讨论(0)
  • 2020-12-19 01:15

    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.

    0 讨论(0)
  • 2020-12-19 01:24

    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.

    0 讨论(0)
  • 2020-12-19 01:29

    Get the reader of existing pdf file by

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

    Now update the reader by

     pdfReader.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.....

    0 讨论(0)
提交回复
热议问题