可以使用iText连接/合并pdf的函数 - 导致一些问题 [英] function that can use iText to concatenate / merge pdfs together - causing some issues

查看:140
本文介绍了可以使用iText连接/合并pdf的函数 - 导致一些问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下代码使用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本身,看看正在翻转的内容有什么特别之处。

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),

  • 您忽略页面边界,例如裁剪框(如果存在),

  • 您忽略存储在页面字典中的旋转值

  • 您将丢弃原始文档中存在的所有交互性,依此类推。

  • You completely ignore the page size of the pages in the original document (you assume they are all of size A4),
  • You ignore page boundaries such as the crop box (if present),
  • You ignore the rotation value stored in the page dictionary,
  • You throw away all interactivity that is present in the original document, and so on.

使用 PdfCopy 连接PDF,例如参见 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆