iText5 合并多个 pdf 文件
核心代码
public static void mergePdf(OutputStream os, List<byte[]> files) {
Document document = null;
try {
document = new Document(new PdfReader(files.get(0)).getPageSize(1));
final PdfCopy copy = new PdfCopy(document, os);
document.open();
for (byte[] file : files) {
final PdfReader reader = new PdfReader(file);
final int numberOfPages = reader.getNumberOfPages();
for (int i = 1; i <= numberOfPages; i++) {
document.newPage();
final PdfImportedPage page = copy.getImportedPage(reader, i);
copy.addPage(page);
}
}
} catch (IOException | DocumentException e) {
throw new RuntimeException(e);
} finally {
if (document != null) {
document.close();
}
}
}
完整的类代码
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.PdfCopy;
import com.itextpdf.text.pdf.PdfImportedPage;
import com.itextpdf.text.pdf.PdfReader;
import java.io.