可以使用 iText 将 pdf 连接/合并在一起的功能 - 导致一些问题 [英] function that can use iText to concatenate / merge pdfs together - causing some issues
问题描述
我正在使用以下代码使用 iText 将 PDF 合并在一起:
I'm using the following code to merge PDFs together using iText:
public static void concatenatePdfs(List<File> listOfPdfFiles, File outputFile) throws DocumentException, IOException {
Document document = new Document();
FileOutputStream outputStream = new FileOutputStream(outputFile);
PdfWriter writer = PdfWriter.getInstance(document, outputStream);
document.open();
PdfContentByte cb = writer.getDirectContent();
for (File inFile : listOfPdfFiles) {
PdfReader reader = new PdfReader(inFile.getAbsolutePath());
for (int i = 1; i <= reader.getNumberOfPages(); i++) {
document.newPage();
PdfImportedPage page = writer.getImportedPage(reader, i);
cb.addTemplate(page, 0, 0);
}
}
outputStream.flush();
document.close();
outputStream.close();
}
这通常很好用!但有时,它会将某些页面旋转 90 度?有人遇到过这种情况吗?
This usually works great! But once and a while, it's rotating some of the pages by 90 degrees? Anyone ever have this happen?
我正在查看 PDF 本身,以了解被翻转的 PDF 有何特别之处.
I am looking into the PDFs themselves to see what is special about the ones that are being flipped.
推荐答案
偶尔会出现错误,因为您使用了错误的方法来连接文档.请阅读我的书的第 6 章,您会注意到使用 PdfWriter
连接(或合并)PDF 文档错误:
There are errors once in a while because you are using the wrong method to concatenate documents. Please read chapter 6 of my book and you'll notice that using PdfWriter
to concatenate (or merge) PDF documents is wrong:
- 您完全忽略了原始文档中页面的页面大小(假设它们都是 A4 大小),
- 您忽略页面边界,例如裁剪框(如果存在),
- 您忽略存储在页面字典中的旋转值,
- 您丢弃了原始文档中存在的所有交互性,依此类推.
连接 PDF 使用 PdfCopy
完成,例如参见 FillFlattenMerge2 示例:
Concatenating PDFs is done using PdfCopy
, see for instance the FillFlattenMerge2 example:
Document document = new Document();
PdfCopy copy = new PdfSmartCopy(document, new FileOutputStream(dest));
document.open();
PdfReader reader;
String line = br.readLine();
// loop over readers
// add the PDF to PdfCopy
reader = new PdfReader(baos.toByteArray());
copy.addDocument(reader);
reader.close();
// end loop
document.close();
这篇关于可以使用 iText 将 pdf 连接/合并在一起的功能 - 导致一些问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!