//Read string contents using stream reader and convert html to parsed conent
var parsedHtmlElements = HTMLWorker.ParseToList(new StringReader(contents), null);
//Get each array values from parsed elements and add to the PDF document
foreach (var htmlElement in parsedHtmlElements)
pdfDoc.Add(htmlElement as IElement);
//Close your PDF
pdfDoc.Close();
Response.ContentType = "application/pdf";
//Set default file Name as current datetime
Response.AddHeader("content-disposition", "attachment; filename=" + DateTime.Now.ToString("yyyyMMdd") + ".pdf");
System.Web.HttpContext.Current.Response.Write(pdfDoc);
Response.Flush();
Response.End();
}
catch (Exception ex)
{
Response.Write(ex.ToString());
}
}
// Below code is read content from HTML file and convert to PDF
protected void Button1_Click(object sender, EventArgs e)
{
//Set page size as A4
Document pdfDoc = new Document(PageSize.A4, 10, 10, 10, 10);
try
{
PdfWriter.GetInstance(pdfDoc, System.Web.HttpContext.Current.Response.OutputStream);
//Open PDF Document to write data
pdfDoc.Open();
//Assign Html content in a string to write in PDF
string contents = "";
StreamReader sr;
try
{
//Read file from server path
sr = File.OpenText(Server.MapPath("sample.html"));
//store content in the variable
contents = sr.ReadToEnd();
sr.Close();
}
catch (Exception ex)
{
}
var parsedHtmlElements = HTMLWorker.ParseToList(new StringReader(contents), null);
// ArrayList parsedHtmlElements = HTMLWorker.ParseToList(new StringReader(contents), null);
//Get each array values from parsed elements and add to the PDF document
foreach (var htmlElement in parsedHtmlElements)
pdfDoc.Add(htmlElement as IElement);
//Close your PDF
pdfDoc.Close();
Response.ContentType = "application/pdf";
//Set default file Name as current datetime
Response.AddHeader("content-disposition", "attachment; filename=" + DateTime.Now.ToString("yyyyMMdd") + ".pdf");
System.Web.HttpContext.Current.Response.Write(pdfDoc);
Response.Flush();
Response.End();
}
catch (Exception ex)
{
Response.Write(ex.ToString());
}
}
}
It works fine for
following sample.html
Collapse | Copy Code
<html> <head> <title></title> </head> <body> <h5>EXPORT HTML CONTENT TO PDF</h5><br /><br /><br /> <b>This content is convert from html file to PDF file</b><br /><br /><br /> <font color="red">Samples from Ravi!!!</font> </body> </html>
but gives error in following line for following html file contents
var parsedHtmlElements = HTMLWorker.ParseToList(new StringReader(contents), null);
error: Input string was not in a correct format.
contents in html file giving error