In this tutorial, we will see Itextsharp html to pdf with css styles c# example. Here is the step by step tutorial to achieve the HTML to pdf with the help of itextsharp. Before creating the HTML to pdf we need to know some point.
$ads={1}
What is itextsharp in c#
itextsharp is a library which can be mainly used for creating the pdf reports. If you have web page this library will help you to convert this HTML page into pdf format. Later on, it depends on you how you will use the report, after converting you can download or send it to in mail attachment.
Namespace
Before using this library we need to include some namespaces, as we know that namespace is the collection of classes so if you want to use the itextsharp library classes you have to include namespaces.
using iTextSharp.text;
using iTextSharp.text.pdf;
Step to achieving HTML to pdf using itextsharp
Install-Package iTextSharp
-Version 5.5.13.2
itextsharp html to pdf |
using iTextSharp.text;
using iTextSharp.text.html.simpleparser;
using iTextSharp.text.pdf;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using iTextSharp.tool.xml;
public partial class html_to_pdf : System.Web.UI.Page
{
protected void
Page_Load(object sender, EventArgs e)
{
try
{
string strHtml = string.Empty;
string htmlFileName = Server.MapPath("~") + "\\files\\" + "ConvertHTMLToPDF.htm";
string pdfFileName = Request.PhysicalApplicationPath + "\\files\\" + "ConvertHTMLToPDF.pdf";
FileStream fsHTMLDocument = new FileStream(htmlFileName,
FileMode.Open, FileAccess.Read);
StreamReader srHTMLDocument = new StreamReader(fsHTMLDocument);
strHtml =
srHTMLDocument.ReadToEnd();
srHTMLDocument.Close();
strHtml = strHtml.Replace("\r\n", "");
strHtml = strHtml.Replace("\0", "");
using (Stream fs = new FileStream(Request.PhysicalApplicationPath + "\\files\\" + "ConvertHTMLToPDF.pdf",
FileMode.Create))
{
using (Document doc = new Document(PageSize.A4))
{
PdfWriter writer =
PdfWriter.GetInstance(doc, fs);
doc.Open();
using (StringReader sr = new StringReader(strHtml))
{
XMLWorkerHelper.GetInstance().ParseXHtml(writer, doc, sr);
}
doc.Close();
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;filename=sample.pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Write(doc);
}
}
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
}
}
Also Read
Post a Comment