加入收藏 | 设为首页 | 会员中心 | 我要投稿 安卓应用网 (https://www.0791zz.com/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

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

发布时间:2020-05-24 15:44:02 所属栏目:Java 来源:互联网
导读:java使用itext按页码拆分pdf文件

下面是脚本之家 jb51.cc 通过网络收集整理的代码片段。

脚本之家小编现在分享给大家,也给大家做个参考。

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

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

以上是脚本之家(jb51.cc)为你收集整理的全部代码内容,希望文章能够帮你解决所遇到的程序开发问题。

如果觉得脚本之家网站内容还不错,欢迎将脚本之家网站推荐给程序员好友。

(编辑:安卓应用网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读