XMLWorker异常:未将对象引用设置为对象的实例

时间:2012-08-07 07:40:01

标签: c# asp.net exception html-parsing export-to-pdf

我想将html导出为pdf

 var document = new Document();
 PdfWriter pdfWriter = PdfWriter.GetInstance(document, 
                                   new FileStream("/my.pdf", FileMode.Create)); 
  pdfWriter.SetFullCompression();
  pdfWriter.StrictImageSequence = true;
  pdfWriter.SetLinearPageMode();

 var sr = new StringReader(htmlcode);
document.Open();

var k = XMLWorkerHelper.GetInstance();
k.ParseXHtml(pdfWriter, document, sr);
//here it gave me an exception: Object reference not set to an instance of 
                                                                  an object


  sr.Close();
   document.Close();

Response.ContentType = "Application/pdf";
Response.AppendHeader("Content-Disposition", "attachment; filename="my.pdf");
Response.TransmitFile(@"c:\test\my.pdf");
Response.Flush();
Response.End();
Response.Close();

所有例外:

 System.NullReferenceException: Object reference not set to an 
instance of an object.
       at iTextSharp.tool.xml.pipeline.html.HtmlPipeline.Close
                          (IWorkerContext context, Tag t, ProcessObject po)
       at iTextSharp.tool.xml.XMLWorker.EndElement(String tag, String ns)
       at iTextSharp.tool.xml.parser.XMLParser.EndElement()
    at iTextSharp.tool.xml.parser.state.ClosingTagState.Process(Char character)
       at iTextSharp.tool.xml.parser.XMLParser.ParseWithReader(TextReader reader)
       at iTextSharp.tool.xml.XMLWorkerHelper.ParseXHtml(PdfWriter writer,
                                                    Document doc, TextReader inp)

1 个答案:

答案 0 :(得分:1)

此行中的错误

var k = XMLWorkerHelper.GetInstance();
k.ParseXHtml(pdfWriter, document, sr);

//这里它给了我一个例外:对象引用未设置为的实例                                                                   一个对象

由于任何一个输入参数的值指向NULL 我们可以在传递之前检查它(变量将通过)是否为null或值。

以下代码足以获取HTML内容并将其写入PDF文件

Document pdfDoc = new Document(PageSize.A4, 10, 10, 10, 10);  
PdfWriter writer = PdfWriter.GetInstance(pdfDoc, new FileStream(@"D:\Syed\New PDF\PDF.pdf", FileMode.Create));// Output PDF File Path
Response.Write("File Created Successfully");
pdfDoc.Open();
XMLWorkerHelper.GetInstance().ParseXHtml(writer, pdfDoc, new StreamReader(@"D:\Syed\test.html"));//This is input HTML file path
pdfDoc.Close();

它将从HTML文件中读取并将其写入创建的PDF文件