使用iText从pdf文件中提取一页

时间:2015-02-07 12:48:29

标签: java google-app-engine pdf itext

我想使用itext库从java servlet中返回pdf文件中的一页(以减少文件大小下载)。 使用此代码

     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();
    }

此代码返回页面,但文件大小很大,有时等于原始文件大小,即使它只是一页。

2 个答案:

答案 0 :(得分:7)

我从您的存储库下载了一个文件:Abdomen.pdf

然后我使用以下代码“破解”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();
    }
}

“爆发”表示在单独的页面中分割。虽然原始文件Abdomen.pdf为72,570 KB(约70.8 MB),但单独的页面要小得多:

enter image description here

我无法重现您描述的问题。

答案 1 :(得分:0)

更新了一些,更整洁了(5.5.6及更高版本):

/**
 * 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();
}