可以使用iText将pdf连接/合并在一起的函数 - 导致一些问题

Nic*_*zza 6 java pdf itext

我正在使用以下代码使用iText将PDF合并在一起:

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();
    }
Run Code Online (Sandbox Code Playgroud)

这通常很棒!但有一段时间,它会将部分页面旋转90度?有人发生过这种事吗?

我正在研究PDF本身,看看正在被翻转的内容有什么特别之处.

Bru*_*gie 16

偶尔会出现错误,因为您使用错误的方法来连接文档.请阅读我的书的第6章,您会注意到使用PdfWriter连接(或合并)PDF文档是错误的:

  • 您完全忽略原始文档中页面的页面大小(假设它们都是A4大小),
  • 您忽略页面边界,例如裁剪框(如果存在),
  • 您忽略存储在页面字典中的旋转值,
  • 您丢弃了原始文档中存在的所有交互性,依此类推.

连接PDF是使用完成的PdfCopy,参见例如FillFlattenMerge2示例:

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();
Run Code Online (Sandbox Code Playgroud)

还有其他的例子.

  • 是的,我是Lowagie ;-) (7认同)
  • 我从 itext 命名空间中认出了你的名字。您是 itext 库的创始人吗? (2认同)

Nic*_*zza 11

如果有人正在寻找它,使用上面的Bruno Lowagie的正确答案,这里的功能版本似乎没有我上面描述的页面翻转问题:

public static void concatenatePdfs(List<File> listOfPdfFiles, File outputFile) throws DocumentException, IOException {
        Document document = new Document();
        FileOutputStream outputStream = new FileOutputStream(outputFile);
        PdfCopy copy = new PdfSmartCopy(document, outputStream);
        document.open();
        for (File inFile : listOfPdfFiles) {
            PdfReader reader = new PdfReader(inFile.getAbsolutePath());
            copy.addDocument(reader);
            reader.close();
        }
        document.close();
}
Run Code Online (Sandbox Code Playgroud)