Skip to main content
 首页 » 编程设计

c#之使用 itextsharp 重新排序 pdf 文件中的页面

2024年02月20日12del

我正在尝试重新排列 PDF 文件中的多个页面。我在博客中找到了一些代码,但无法让它工作。我有一个两页的 pdf,我想让最后一页显示在第一页。我总是得到一个异常(exception),说页码必须与订单相匹配。当我检查文档对象时,它显示 0 页。但是传入的 PDF 有两页。

public void reOrder(string inputFile) 
{  
    Document document = new Document(); 
    FileStream fs = new FileStream(inputFile, FileMode.Open); 
    PdfWriter writer = PdfWriter.GetInstance(document, fs); 
    document.AddDocListener(writer);                 
    writer.SetLinearPageMode(); 
    int[] order = {2,1}; 
    writer.ReorderPages(order); 
} 

请您参考如下方法:

每当您使用 iTextSharp 编写创建新文档所需的内容时,它永远不会写入现有文档。在您的情况下,页面重新排序需要书写,因此您需要创建一个新文档,将页面移过来,然后重新排序。 (当然,您也可以在导入时重新排序。)

        var inputFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Test.pdf"); 
        var output = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Output.pdf"); 
 
        //Bind a reader to our input file 
        var reader = new PdfReader(inputFile); 
 
        //Create our output file, nothing special here 
        using (FileStream fs = new FileStream(output, FileMode.Create, FileAccess.Write, FileShare.None)) { 
            using (Document doc = new Document(reader.GetPageSizeWithRotation(1))) { 
                //Use a PdfCopy to duplicate each page 
                using (PdfCopy copy = new PdfCopy(doc, fs)) { 
                    doc.Open(); 
                    copy.SetLinearPageMode(); 
                    for (int i = 1; i <= reader.NumberOfPages; i++) { 
                        copy.AddPage(copy.GetImportedPage(reader, i)); 
                    } 
                    //Reorder pages 
                    copy.ReorderPages(new int[] { 2, 1 }); 
                    doc.Close(); 
                } 
            } 
        }