7

我正在尝试使用以下内容使用 iTextSharp 5.3.4 创建一个 pdf 文档

Document document = new Document();
FileStream stm = new FileStream(filename, FileMode.Create);
PdfWriter writer = PdfWriter.GetInstance(document, stm);

我得到一个带有以下堆栈跟踪的 System.NullReferenceException:

System.NullReferenceException occurred
HResult=-2147467261
Message=La référence d'objet n'est pas définie à une instance d'un objet.
Source=itextsharp
StackTrace:
   à iTextSharp.text.Version.GetInstance()
InnerException: 

我已经验证文档和 stm 都不是空的,如果我在 VS12 中选择“继续”,则会创建文档 - 但是总是抛出异常。我更新到 iTextSharp 5.4.0 并且它仍在发生。我在任何地方都找不到有关此的任何信息-有人有任何想法吗?

4

2 回答 2

24

确保您没有捕获所有异常。这NullReferenceException很可能是已经在 iTextSharp 中捕获和处理的问题,因此您不必关心它。
你可以继续的事实支持了这个理论。

更改以下设置以验证:

Debug -> Exceptions -> 去掉“Common Language Runtime Exceptions”的“Thrown”列中的复选框。

于 2013-04-05T11:55:12.273 回答
-1

经过长时间的调试,我找到了一个可行的奇怪解决方案。它基于一个发现:PdtWriter 实例好像创建时间长,然后延迟解决问题。在这里我提出我的解决方案:一个返回 PdfWriter 实例的函数。

static  public iTextSharp.text.pdf.PdfWriter   PdfWriter_GetInstance(iTextSharp.text.Document document , System.IO.FileStream FS )
{
  iTextSharp.text.pdf.PdfWriter writer = null;
           
  for (int Times = 0; Times < 6; Times++)
  {
    try
    {
      writer = iTextSharp.text.pdf.PdfWriter.GetInstance(document, FS); // sometime rise exception on first call
      break; //created, then exit loop
    }
    catch
    {
      System.Threading.Thread.Sleep(250); // wait for a while...
    }
  }
  if (writer == null) // check if instantiated
  {
    throw new Exception("iTextSharp PdfWriter is null");
  }
            
  return writer;
}
于 2020-11-08T17:57:32.800 回答