2011-06-28 85 views
1

我已經嘗試了幾個不同的代碼樣本中,他們都拋出同樣的異常:試圖合併使用iTextSharp的V4 PDF文件拋出異常

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) 

本例使用PdfCopy。我也嘗試過使用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; 
    } 

有了這段代碼,AddPage會發生異常。在一個PdfWriter,它發生在文檔關閉。我真的不知道該iTextSharp的內部那麼好......

+0

我懷疑你有一個壞的PDF那裏。我們可以看看嗎? –

回答