2

我在网上查看了一些示例,并想出了使用 iTextSharp 合并 pdf 的代码。但我收到一个错误:.

{“文档没有页面。”}

它在Page = writer.GetImportedPage(reader, X);处失败

这是堆栈跟踪:

 at iTextSharp.text.pdf.PdfPages.WritePageTree()
 at iTextSharp.text.pdf.PdfWriter.Close()
 at iTextSharp.text.pdf.PdfCopy.Close()
 at iTextSharp.text.Document.Close()

当我调试它时,它有 3 页。这里有什么问题??

这是我的代码

public static MemoryStream MergePdfs(List<MemoryStream> pdfStreams)
       {
        //Create output stream
           MemoryStream OutStream = new MemoryStream();
           Document Document = null;

           try
           {
                //Create Main reader
                PdfReader Reader = new PdfReader(pdfStreams.ElementAt(0));
                //Create Main Doc
                Document = new Document(Reader.GetPageSizeWithRotation(1));
                //Create main writer
                PdfCopy Writer = new PdfCopy(Document, OutStream);
                //Open document for writing
                Document.Open();
                //Add pages
                AddPages(Reader.NumberOfPages, Reader, ref Writer);

                //For each additional pdf after first combine them into main document
                foreach (MemoryStream PdfStream in pdfStreams.Skip(1))
                {
                    PdfReader Reader2 = new PdfReader(PdfStream);
                    // Add content
                    AddPages(Reader2.NumberOfPages, Reader2, ref Writer);
                }
             }
             finally
             {
                 // Step 5: Close the document
                 if (Document != null)
                     Document.Close();

                foreach (var Strm in pdfStreams)
                {
                    try { if (null != Strm) Strm.Dispose(); } catch { }
                }
             }

             return OutStream;
         }

        private static void AddPages(int Pages, PdfReader reader, ref PdfCopy writer)
        {
            PdfImportedPage Page = null;

            for (int X = 0; X < Pages; X++)
            {
                 Page = writer.GetImportedPage(reader, X);
                 writer.AddPage(Page);
            }

            if (reader.AcroForm != null)
                writer.CopyAcroForm(reader);
        }
4

1 回答 1

6

GetImportedPage 的页码从 1 开始。因此:

for (int X = 1; X < Pages + 1; X++)
{
    Page = writer.GetImportedPage(reader, X);
    writer.AddPage(Page);
}
于 2012-11-02T15:59:45.487 回答