extracting one page from pdf file using iText

2019-02-15 19:47发布

问题:

I want to return one page from pdf files from java servlet (to reduce file size download), using itext library. using this code

     try {
        PdfReader reader = new PdfReader(input);
        Document document = new Document(reader.getPageSizeWithRotation(page_number) );


        PdfSmartCopy copy1 = new PdfSmartCopy(document, response.getOutputStream());
        copy1.setFullCompression();
        document.open();

        copy1.addPage(copy1.getImportedPage(reader, page_i) );
        copy1.freeReader(reader);
        reader.close();

        document.close();

    } catch (DocumentException e) {
        e.printStackTrace();
    }

this code returns the page, but the file size is large and some times equals the original file size, even it is just a one page.

回答1:

I have downloaded a single file from your repository: Abdomen.pdf

I have then used the following code to "burst" that PDF:

public static void main(String[] args) throws DocumentException, IOException {
    PdfReader reader = new PdfReader("resources/Abdomen.pdf");
    int n = reader.getNumberOfPages();
    reader.close();
    String path;
    PdfStamper stamper;
    for (int i = 1; i <= n; i++) {
        reader = new PdfReader("resources/abdomen.pdf");
        reader.selectPages(String.valueOf(i));
        path = String.format("results/abdomen/p-%s.pdf", i);
        stamper = new PdfStamper(reader,new FileOutputStream(path));
        stamper.close();
        reader.close();
    }
}

To "burst" means to split in separate pages. While the original file Abdomen.pdf is 72,570 KB (about 70.8 MB), the separate pages are much smaller:

I can not reproduce the problem you describe.



回答2:

A bit more updated and a lot cleaner (5.5.6 and up) :

/**
 * Manipulates a PDF file src with the file dest as result
 * @param src the original PDF
 * @param dest the resulting PDF
 * @throws IOException
 * @throws DocumentException
 */
public void manipulatePdf(String src, String dest)
    throws IOException, DocumentException {
    PdfReader reader = new PdfReader(src);
    SmartPdfSplitter splitter = new SmartPdfSplitter(reader);
    int part = 1;
    while (splitter.hasMorePages()) {
        splitter.split(new FileOutputStream("results/merge/part_" + part + ".pdf"), 200000);
        part++;
    }
    reader.close();
}