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

2008041.jpg
在實際開發(fā)過程中,遇到將多個pdf文件合并成一個pdf文件方便預(yù)覽的問題,處理代碼如下(親測可用):
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) {
        //要合并文件數(shù)組
        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.
經(jīng)檢查,是pdf文件損壞引起的。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容