Click here to Skip to main content
14,970,162 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am having a prblem in converting html to pdf

The code which i used for conversion is as follows

using iTextSharp.text;
using iTextSharp.text.html.simpleparser;
using iTextSharp.text.pdf;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.IO;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

protected void ConvertToPDFNow()
  StringWriter sw = new StringWriter();
        HtmlTextWriter w = new HtmlTextWriter(sw);
        string htmWrite = sw.GetStringBuilder().ToString();

Response.ContentType = "application/pdf";
        Response.AddHeader("content-disposition", "attachment;filename=FileName.pdf");

        htmWrite = Regex.Replace(htmWrite, "</?(a|A).*?>", "");
        htmWrite = htmWrite.Replace("\r\n", "");
        StringReader reader = new StringReader(htmWrite);

        Document doc = new Document(PageSize.A4);
        HTMLWorker parser = new HTMLWorker(doc);
        PdfWriter.GetInstance(doc, Response.OutputStream);
        catch (Exception ex)
        {                   }

I am passing an html text which has image, table, inline-styles, id.
While converting i am getting an error "Object referenced not set to an instance" at
What to do?

1 solution

I believe the parser instance that you are creating from HTMLWorker is not getting properly initiated, and as a result any call made upon the parser object reference is throwing a null reference exception. Make a debugging and most importantly go though the stack trace.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900