XMLWorker Exception : Object reference not set to an instance of an object
-
25-06-2021 - |
Domanda
I want to export html to 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();
All exceptions:
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)
Soluzione
Error in this line
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
due to value of any one of input arguments was pointing to NULL We can Check it(variable going to pass) whether its null or value, before passing.
This following code is just enough to get get HTML content and write it to PDF file
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();
It 'll read from HTML file and wrote them into created PDF file
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow