tags:

views:

148

answers:

2

Hi,

Can anyone tell me how to convert a PDF document from an HTML code using C#? I'm using itextsharp 5.0.2 dll. I have come across this forum. I didnt find any solution so far. And some of them mentioned iTextSharp.HtmlParser but i cannot find such kind of class in my version of dll. In which version should i need to use to achieve my task.

I have tried with this code...i dont know what wrong did i do? Im not getting the PDF file.

Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;filename=TestResult.pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCache);

StringBuilder htmlText =
            new StringBuilder("<table style='color:red;' border='1'>");
htmlText.Append("<tr><th>Karunagara Pandi</th><tr><td> Software Engineer</td></tr></table>");

StringReader stringReader = new StringReader(htmlText.ToString());
Document doc = new Document(PageSize.A4);
List<iTextSharp.text.IElement> elements = 
        iTextSharp.text.html.simpleparser.HTMLWorker.ParseToList(stringReader, null);
doc.Open();
foreach (object item in elements)
{
    doc.Add((IElement)item);
}

// Response Output
PdfWriter.GetInstance(doc, Response.OutputStream);
doc.Open();

//doc.Close();

Response.Write("PDF is created");

This code also taken from this site only....I need to your proper solution. I'll also try to get.....

Thanks.

+1  A: 

You have two doc.Open statements without an intervening doc.Close(). The second one will effectively overwrite the contents you've just added.

doc.Open();  // ONE
foreach (object item in elements)
{
    doc.Add((IElement)item);
}

// Response Output
PdfWriter.GetInstance(doc, Response.OutputStream);
doc.Open();  // TWO
ChrisF
A: 

To whom it may respond to, I am trying to run the code provided by Karanugara Pandi, I have corrected the code as ChrisF had pointed out two open docs, I get this error : System.Exception was unhandled by user code Message=The document is not open. Source=itextsharp StackTrace: at iTextSharp.text.pdf.PdfWriter.get_DirectContent() at iTextSharp.text.pdf.PdfDocument.get_PageEmpty() at iTextSharp.text.pdf.PdfDocument.NewPage() at iTextSharp.text.pdf.PdfDocument.Close() at iTextSharp.text.Document.Close() at PdfWriterWeb.WebForm3.Page_Load(Object sender, EventArgs e) in D:\HOME\Projects\PdfWriterWeb\PdfWriterWeb\nodb.aspx.cs:line 31 at System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) at System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) at System.Web.UI.Control.OnLoad(EventArgs e) at System.Web.UI.Control.LoadRecursive() at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) InnerException:

....

How can I resolve this problem ? Thank you ,

Kayhan YÜKSEL

kayhan yüksel