返回顶部

收藏

java使用itext按页码拆分pdf文件

更多

java使用itext按页码拆分pdf文件,代码实现如下:

/**
 * @author viralpatel.net
 * 
 * @param inputStream Input PDF file
 * @param outputStream Output PDF file
 * @param fromPage start page from input PDF file
 * @param toPage end page from input PDF file
 */
public static void splitPDF(InputStream inputStream,
        OutputStream outputStream, int fromPage, int toPage) {
    Document document = new Document();
    try {
        PdfReader inputPDF = new PdfReader(inputStream);

        int totalPages = inputPDF.getNumberOfPages();

        //make fromPage equals to toPage if it is greater
        if(fromPage > toPage ) {
            fromPage = toPage;
        }
        if(toPage > totalPages) {
            toPage = totalPages;
        }

        // Create a writer for the outputstream
        PdfWriter writer = PdfWriter.getInstance(document, outputStream);

        document.open();
        PdfContentByte cb = writer.getDirectContent(); // Holds the PDF data
        PdfImportedPage page;

        while(fromPage <= toPage) {
            document.newPage();
            page = writer.getImportedPage(inputPDF, fromPage);
            cb.addTemplate(page, 0, 0);
            fromPage++;
        }
        outputStream.flush();
        document.close();
        outputStream.close();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (document.isOpen())
            document.close();
        try {
            if (outputStream != null)
                outputStream.close();
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }
}

使用示例如下,将一个20页的pdf文件拆分成1-12和13-20页两个pdf文件:

public static void main(String[] args) {
    try {
        MergePDF.splitPDF(new FileInputStream("C:\\input.pdf"), 
                    new FileOutputStream("C:\\output1.pdf"), 1, 12);
        MergePDF.splitPDF(new FileInputStream("C:\\input.pdf"), 
                    new FileOutputStream("C:\\output2.pdf"), 13, 20);

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

标签:java

收藏

0人收藏

支持

0

反对

0

发表评论