ITEXT PDF文件的拆分与合并

x33g5p2x  于2021-12-28 转载在 其他  
字(1.9k)|赞(0)|评价(0)|浏览(344)

问题场景

用itext写PDF,在加目录(可以参考我的文章)的过程当中遇到PDF的拆分与合并,记录下。

CODE

需要导入的包:itext-pdfa-5.5.6.jar、itext-xtra-5.5.6.jar、itext-5.5.6.jar、itext-asian.jar

package itext.contents;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.PdfCopy;
import com.itextpdf.text.pdf.PdfImportedPage;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;

import java.io.FileOutputStream;
import java.io.IOException;

/** * Created on 2017/8/23 * Author: youxingyang. */
public class TestSplitAndMergePdf {

    /** * 复制pdf文档 * @param sourceFile 源文件 * @param targetFile 目标文件 * @param ranges 复制规则 "1-7"表示复制1到7页、"8-"表示复制从第八页之后到文档末尾 */
    public static void copyPdf(String sourceFile ,String targetFile, String ranges)throws Exception{
        PdfReader pdfReader = new PdfReader(sourceFile);
        PdfStamper pdfStamper = new PdfStamper(pdfReader , new FileOutputStream(targetFile));
        pdfReader.selectPages(ranges);
        pdfStamper.close();
    }

    /** * 多个PDF合并功能 * @param files 多个PDF的路径 * @param savePath 生成的新PDF绝对路径 */
    public static void mergePdfFiles(String[] files, String savePath)  {
        if (files.length > 0) {
            try {
                Document document = new Document(new PdfReader(files[0]).getPageSize(1));
                PdfCopy copy = new PdfCopy(document, new FileOutputStream(savePath));
                document.open();
                for (String file : files) {
                    PdfReader reader = new PdfReader(file);
                    int n = reader.getNumberOfPages();
                    for (int j = 1; j <= n; j++) {
                        document.newPage();
                        PdfImportedPage page = copy.getImportedPage(reader, j);
                        copy.addPage(page);
                    }
                }
                document.close();
            } catch (IOException | DocumentException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) throws Exception {

        String sourceFile = "E://TESTPDF/2016-08-24.pdf";
        String targetFile = "E://TESTPDF/2016-08-24-part1.pdf";
        String targetFile1 = "E://TESTPDF/2016-08-24-part2.pdf";

        copyPdf(sourceFile, targetFile, "1-10");
        copyPdf(sourceFile, targetFile1, "11-");

        String[] files = {targetFile, "E://TESTPDF/contents.pdf", targetFile1};
        mergePdfFiles(files, "E://TESTPDF/2016-08-24-Add.pdf");

    }
}

相关文章