利用iText 合并PDF与分解PDF的例子

很久前记录过一篇创建PDF 的文章,可以参考这里 java 利用 itext 创建pdf .  一般只是创建pdf, 但有些特殊情况还需要合并pdf 与拆分pdf, 这些功能对一iText 来说,不过是小菜一碟。创建pdf 的方法还是参考以前的文章吧,毕竟里面给出的函数齐全一些。今天用iText 5.0 测试了PDF 的合并与拆分,效果还是很好的,而且性能也不错。

java itext 合并PDF
1. 首先准备要合并的pdf,将内容放在一个 InputStream  list 中,准备好目标文件目录
2. 调用 合并 pdf 的方法: concatPDFs, 传入输入流list, 输出文件流,是否处理分页参数.
3. 在 concatPDFs 方法中循环处理 将输入流转换成 PdfReader,并处理页码.
4. 利用 Document class和 PdfWriter.getInstance() 方法生成目标文件
5. 在循环中将所有输入的  PDF 合并到输出文件中.
代码如下 :
程序代码 程序代码

package com.yihaomen.pdf;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import com.itextpdf.text.Document;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfImportedPage;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfWriter;

public class MergePDF {

    public static void main(String[] args) {
        try {
            List<InputStream> pdfs = new ArrayList<InputStream>();
            for(int i=0;i<10;i++){
                pdfs.add(new FileInputStream("d:\\pdf\\" + i +".pdf"));
            }
            OutputStream output = new FileOutputStream("d:\\pdf\\merge.pdf");
            MergePDF.concatPDFs(pdfs, output, true);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void concatPDFs(List<InputStream> streamOfPDFFiles,
            OutputStream outputStream, boolean paginate) {

        Document document = new Document();
        try {
            List<InputStream> pdfs = streamOfPDFFiles;
            List<PdfReader> readers = new ArrayList<PdfReader>();
            int totalPages = 0;
            Iterator<InputStream> iteratorPDFs = pdfs.iterator();

            // Create Readers for the pdfs.
            while (iteratorPDFs.hasNext()) {
                InputStream pdf = iteratorPDFs.next();
                PdfReader pdfReader = new PdfReader(pdf);
                readers.add(pdfReader);
                totalPages += pdfReader.getNumberOfPages();
            }
            // Create a writer for the outputstream
            PdfWriter writer = PdfWriter.getInstance(document, outputStream);

            document.open();
            BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA,
                    BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
            PdfContentByte cb = writer.getDirectContent(); // Holds the PDF
            // data

            PdfImportedPage page;
            int currentPageNumber = 0;
            int pageOfCurrentReaderPDF = 0;
            Iterator<PdfReader> iteratorPDFReader = readers.iterator();

            // Loop through the PDF files and add to the output.
            while (iteratorPDFReader.hasNext()) {
                PdfReader pdfReader = iteratorPDFReader.next();
                // Create a new page in the target for each source page.
                while (pageOfCurrentReaderPDF < pdfReader.getNumberOfPages()) {
                    document.newPage();
                    pageOfCurrentReaderPDF++;
                    currentPageNumber++;
                    page = writer.getImportedPage(pdfReader,
                            pageOfCurrentReaderPDF);
                    cb.addTemplate(page, 0, 0);

                    // Code for pagination.
                    if (paginate) {
                        cb.beginText();
                        cb.setFontAndSize(bf, 9);
                        cb.showTextAligned(PdfContentByte.ALIGN_CENTER, ""
                                + currentPageNumber + " of " + totalPages, 520,
                                5, 0);
                        cb.endText();
                    }
                }
                pageOfCurrentReaderPDF = 0;
            }
            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();
            }
        }
    }
}




java itext 根据页码拆分 pdf 文档
目前简单实现根据页码拆分pdf 文档,代码如下:
程序代码 程序代码

package com.yihaomen.pdf;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import com.itextpdf.text.Document;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfImportedPage;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfWriter;

public class SplitPDF {
    
    public static void main(String[] args) {
        try {
            splitPDF(new FileInputStream("d:\\pdf\\merge.pdf"),
                        new FileOutputStream("d:\\pdf\\output1.pdf"), 1, 5);
            splitPDF(new FileInputStream("d:\\pdf\\merge.pdf"),
                        new FileOutputStream("d:\\pdf\\output2.pdf"), 6, 10);
            
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

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



如果需要整个源代码的,可以在这里下载:

下载文件 点击下载此文件


除非申明,文章均为一号门原创,转载请注明本文地址,谢谢!
文章来自: 本站原创
引用通告: 查看所有引用 | 我要引用此文章
Tags: itext pdf
相关日志:
评论: 1 | 引用: 0 | 查看次数: -
回复回复鸢尾[2015-03-27 11:31 AM | del]
既然发源码公开了 为什么不注释...
发表评论
昵 称:
密 码: 游客发言不需要密码.
内 容:
验证码: 验证码
选 项:
虽然发表评论不用注册,但是为了保护您的发言权,建议您注册帐号.