簡體   English   中英

如何使用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方法嘗試的CopyPagesTodest.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();

正如@Bruno指出的那樣,可以使用PdfDocument方法CopyPagesTo的重載輕松地使用iText 7重新排序pdf文檔。

關於你的嘗試

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

    CopyTo(dest)可從源到目的地的頁面數據 ,它只是還沒有把它添加到目標頁面樹 這就是為什么CopyTo返回一個頁面對象,你可以使用dest.AddPage(...)重載; 這尤其允許您將頁面插入所需的任何位置。

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

    new List<int>(1)創建一個容量為1空列表 您可能想要創建一個new List<int> { 1 } (帶花括號),它創建一個包含一個條目的列表,即1

您應該閱讀FAQ條目如何重新排序現有PDF文件中的頁面?

首先,您需要創建一個整數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);

srcDocPdfDocument使用創建PdfReader對象, resultDocPdfDocument使用創建PdfWriter對象。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM