在实际开发过程中,遇到将多个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文件损坏引起的。
网友评论