简体   繁体   中英

Attempting to merge PDFs using iTextSharp v4 throws an exception

I have tried a couple of different code samples and they all throw the same exception:

System.InvalidCastException was unhandled by user code
  Message=Unable to cast object of type 'iTextSharp.text.pdf.PdfArray' to type 'iTextSharp.text.pdf.PRIndirectReference'.
  Source=itextsharp
  StackTrace:
       at iTextSharp.text.pdf.PdfCopy.CopyObject(PdfObject inp)
       at iTextSharp.text.pdf.PdfCopy.CopyDictionary(PdfDictionary inp)
       at iTextSharp.text.pdf.PdfCopy.AddPage(PdfImportedPage iPage)

This example uses PdfCopy. I have also tried it with PdfWriter:

    public MemoryStream Merge(MemoryStream outputStream,List<PdfReader> documents)
    {
        if (outputStream == null || !outputStream.CanWrite)
            throw new Exception("OutputStream is null or you can't write to it.");

        Document newDocument = null;
        try
        {
            newDocument = new Document(documents[0].GetPageSizeWithRotation(1));
            PdfCopy pdfWriter = new PdfCopy(newDocument, outputStream);

            newDocument.Open();
            //PdfContentByte pdfContentByte = pdfWriter.DirectContent;

            foreach (PdfReader pdfReader in documents)
            {
                for (int page = 1; page <= pdfReader.NumberOfPages; page++)
                {
                    //newDocument.NewPage();
                    PdfImportedPage importedPage = pdfWriter.GetImportedPage(pdfReader, page);
                    pdfWriter.AddPage(importedPage);
                }
            }
        }
        finally
        {
            outputStream.Flush();
            if (newDocument != null)
                newDocument.Close();
            outputStream.Close();
        }
        return outputStream;
    }

With this code, the exception happens at AddPage. On a PdfWriter, it happens at document close. I really don't know the iTextSharp internals all that well...

I use this: my code

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM