多个pdf文件合并成一个pdf文件

2008041.jpg
在实际开发过程中,遇到将多个pdf文件合并成一个pdf文件方便预览的问题,处理代码如下(亲测可用):
import com.itextpdf.text.Document;
import com.itextpdf.text.pdf.PdfCopy;
import com.itextpdf.text.pdf.PdfImportedPage;
import com.itextpdf.text.pdf.PdfReader;

import java.io.FileOutputStream;


public class PDFSplitTest {
    public static void main(String[] args) {
        //要合并文件数组
        String[] files = { "C:\\Users\\Administrator\\Desktop\\testPdf\\test1.pdf","C:\\Users\\Administrator\\Desktop\\testPdf\\test2.pdf" };
        //合并到文件
        String savepath = "C:\\Users\\Administrator\\Desktop\\testPdf\\merge.pdf";
        mergePdfFiles(files, savepath);
    }

    public static boolean mergePdfFiles(String[] files, String newfile) {
        boolean retValue = false;
        Document document = null;
        try {
            document = new Document(new PdfReader(files[0]).getPageSize(1));
            PdfCopy copy = new PdfCopy(document, new FileOutputStream(newfile));
            document.open();
            for (int i = 0; i < files.length; i++) {
                PdfReader reader = new PdfReader(files[i]);
                int n = reader.getNumberOfPages();
                for (int j = 1; j <= n; j++) {
                    document.newPage();
                    PdfImportedPage page = copy.getImportedPage(reader, j);
                    copy.addPage(page);
                }
            }
            retValue = true;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            document.close();
        }
        return retValue;
    }

}

使用过程中,遇到问题:
com.itextpdf.text.exceptions.InvalidPdfException: PDF header signature not found.
经检查,是pdf文件损坏引起的。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容