如何使用 iText 7 重新排序 pdf 文档

How to reorder a pdf document with iText 7

我正在学习 iText 7 库,我希望它有两个主要功能:重新排序页面和旋转页面。后者在快速入门指南中很容易理解。前者我遇到了一些麻烦,因为我能找到的所有例子要么是旧的,要么是 java(或两者)。

我目前正在尝试设置一个将第一页移到第二页之后的示例:

PdfReader reader = new PdfReader(FILE_READ_LOCATION);
PdfWriter writer = new PdfWriter(FILE_WRITE_LOCATION);
PdfDocument document = new PdfDocument(reader, writer);

PdfPage pageToMove = document.GetPage(1);

document.AddPage(3, pageToMove);
document.RemovePage(pageToMove);

document.Close();

出于某种原因,document.Close(); 抛出 NullReferenceException(但我没有看到任何 null)。有什么建议吗?

这是我为 copyToCopyPagesTo 方法所做的尝试(dest.Close(); 抛出一个异常说 Document has no pages):

PdfReader reader = new PdfReader(FILE_READ_LOCATION);
PdfWriter writer = new PdfWriter(FILE_WRITE_LOCATION);

PdfDocument src = new PdfDocument(reader);
PdfDocument dest = new PdfDocument(writer);

src.GetPage(1).CopyTo(dest);
src.CopyPagesTo(new List<int>(1), dest);

src.Close();
dest.Close();

您应该阅读常见问题条目How to reorder pages in an existing PDF file?

首先您需要创建一个 List 整数。例如:

List<int> pages = new List<int>();
pages.Add(2);
pages.Add(1);
for (int i = 3; i <= total; i++) {
    pages.Add(i);
}

然后您可以使用此页面顺序将一个 PDF 的页面复制到另一个 PDF:

srcDoc.CopyPagesTo(pages, resultDoc);

其中 srcDoc 是使用 PdfReader 对象创建的 PdfDocumentresultDoc 是使用 PdfWriter 对象创建的 PdfDocument .

正如@Bruno 指出的那样,使用 PdfDocument 方法 CopyPagesTo.

的重载,可以轻松地使用 iText 7 重新排序 pdf 文档

关于您的尝试

  • src.GetPage(1).CopyTo(dest);

    CopyTo(dest) 将页面 data 从源复制到目标,只是 not 但将其添加到目的地 页面树 。这就是为什么 CopyTo returns 可以使用 dest.AddPage(...) 重载的页面对象;这尤其允许您在所需的任何位置插入页面。

  • src.CopyPagesTo(new List<int>(1), dest);

    new List<int>(1) 创建一个空列表容量为 1。您可能想要执行 new List<int> { 1 } (带花括号),它创建一个包含一个条目的列表,一个 1.