
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文件損壞引起的。