Java使用iText PDF合并PDF(将多个PDF合并成一个PDF)

1 配置pom文件

我用的是5.4.3的版本


	com.itextpdf
	itextpdf
	5.4.3

2 合并PDF代码

/**
 * @author Reverse_XML
 * 将多个PDF合并成一个PDF
 * @param files 源PDF路径
 * @param outputPath 合并后输出的PDF路径
 * @param outputFileName 合并后输出的PDF文件名
 */
public static void mergePDF(String[] files, String outputPath, String outputFileName) {
        String sep = java.io.File.separator;
        Document document = null;
        PdfCopy copy = null;
        PdfReader reader = null;
        try {
            document = new Document(new PdfReader(files[0]).getPageSize(1));
            copy = new PdfCopy(document, new FileOutputStream(outputPath + sep +outputFileName));
            document.open();
            for (int i = 0; i < files.length; i++) {
                reader = new PdfReader(files[i]);
                int numberOfPages = reader.getNumberOfPages();
                for (int j = 1; j <= numberOfPages; j++) {
                    document.newPage();
                    PdfImportedPage page = copy.getImportedPage(reader, j);
                    copy.addPage(page);
                }
            }
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        } catch (DocumentException e) {
            log.error(e.getMessage(), e);
        } finally {
            if (document != null)
                document.close();
            if (reader != null)
                reader.close();
            if (copy != null)
                copy.close();
        }
    }

3 调用示例

将test1.pdf 和 test2.pdf 合并成一个merge.pdf

public static void main(String[] args) {
	String[] files = {"D:\\inputPath\\test1.pdf", "D:\\inputPath\\test2.pdf"};
    String outputPath= "D:\\outputPath";
    String outputFileName ="merge.pdf";
    
    try {
        PDFUtils.mergePDF(files,outputPath,outputFileName);
    } catch (Exception e) {
        log.error(e.getMessage(), e);
    }
}

4 官网

https://itextpdf.com

你可能感兴趣的:(Java,java,itext)