Export HTML to PDF in asp.net

Description:-

In this article we will export html elements to pdf it could be html tag, hyper links, style tags etc. here I have created demo example to create pdf file from html.
here i have create class for converting html to pdf and attached as pdf file. here is the source code to convert HTML to PDF in dot net.

Default.aspx:-
<div id="dvHtml" runat="server" style="margin: 0 0 0 0;">
  <div>
    <b>ASPCODDER CODE</b><br/>
    <br/>Dear candidate,<br/>
    <br/>
    <b>Visit this website:</b><a href="https://aspcodder.blogspot.in/"target="_blank" style="color: #292929; text-decoration: none;"> https://aspcodder.blogspot.in/ </a> <br/>
    <br/>You can get the different solutions with demo example source code from <a href="https://aspcodder.blogspot.in/"  target="_blank"style="color: #292929; text-decoration: none;"><b>ASPCODDER</b></a>. We will always with you, so share your problem with us and we will give you best solutions as soon as possible.<br/>
    <br/>
    <b>Material with the download links are listed below.</b><br/>
    <b>ASP.NET :</b><a href="https://aspcodder.blogspot.in/search/label/Asp.Net" target="_blank" style="color: #292929; text-decoration: none;"> https://aspcodder.blogspot.in/search/label/Asp.Net</a><br/>
    <br/>
    <b>SQL Server :</b><a href="https://aspcodder.blogspot.in/search/label/SQL" target="_blank"style="color: #292929; text-decoration: none;">https://aspcodder.blogspot.in/search/label/SQL</a><br/>
    <br/>
    <b>Dynamics Ax :</b><a href="https://aspcodder.blogspot.in/search/label/Dynamics%20AX" target="_blank"style="color: #292929; text-decoration: none;">https://aspcodder.blogspot.in/search/label/Dynamics%20AX</a><br/>
    <br/>
    <b>Thanks,<br/> Code Scratcher Team</b>
  </div>
</div>
<br/>
<br/>
<center>
<asp:Button ID="btnClick"runat="server" OnClick="btnClick_Click" style="Height:30px"Text="HTML Download as PDF"/>
</center>

Default.aspx.cs:-
protected void btnClick_Click(object sender, EventArgs e)
{
  DownloadAsPDF();
}

public void DownloadAsPDF()
{
  try
  {
    string strHtml = string.Empty;
    string pdfFileName = Request.PhysicalApplicationPath + "\\files\\" + "GenerateHTMLTOPDF.pdf";

    StringWriter sw = new StringWriter();
    HtmlTextWriter hw = new HtmlTextWriter(sw);
    dvHtml.RenderControl(hw);
    StringReader sr = new StringReader(sw.ToString());
    strHtml = sr.ReadToEnd();
    sr.Close();

    CreatePDFFromHTMLFile(strHtml, pdfFileName);

    Response.ContentType = "application/x-download";
    Response.AddHeader("Content-Disposition", string.Format("attachment; filename=\"{0}\"", "GenerateHTMLTOPDF.pdf"));
    Response.WriteFile(pdfFileName);
    Response.Flush();
    Response.End();
  }
  catch (Exception ex)
  {
    Response.Write(ex.Message);
  }
}

public void CreatePDFFromHTMLFile(stringHtmlStream, stringFileName)
{
  try
  {
    objectTargetFile = FileName;
    string ModifiedFileName = string.Empty;
    string FinalFileName = string.Empty;


    GeneratePDF.HtmlToPdfBuilder builder = new GeneratePDF.HtmlToPdfBuilder(iTextSharp.text.PageSize.A4);
    GeneratePDF.HtmlPdfPage first = builder.AddPage();
    first.AppendHtml(HtmlStream);
    byte[] file = builder.RenderPdf();
    File.WriteAllBytes(TargetFile.ToString(), file);

    iTextSharp.text.pdf.PdfReader reader = newiTextSharp.text.pdf.PdfReader(TargetFile.ToString());
    ModifiedFileName = TargetFile.ToString();
    ModifiedFileName = ModifiedFileName.Insert(ModifiedFileName.Length - 4, "1");

    iTextSharp.text.pdf.PdfEncryptor.Encrypt(reader, newFileStream(ModifiedFileName, FileMode.Append),     iTextSharp.text.pdf.PdfWriter.STRENGTH128BITS, "", "", iTextSharp.text.pdf.PdfWriter.AllowPrinting);
    reader.Close();
    if (File.Exists(TargetFile.ToString()))
    File.Delete(TargetFile.ToString());
    FinalFileName = ModifiedFileName.Remove(ModifiedFileName.Length - 5, 1);
    File.Copy(ModifiedFileName, FinalFileName);
    if (File.Exists(ModifiedFileName))
    File.Delete(ModifiedFileName);
  }
  catch (Exception ex)
  {
    throw ex;
  }
}

ConvertPdf.cs:-
#regionHtmlToPdfBuilder Class
public class HtmlToPdfBuilder
{
  #region Constants
  private conststring STYLE_DEFAULT_TYPE = "style";
  private conststring DOCUMENT_HTML_START = "<html><head></head><body>";
  private conststring DOCUMENT_HTML_END = "</body></html>";
  private conststring REGEX_GROUP_SELECTOR = "selector";
  private conststring REGEX_GROUP_STYLE = "style";

  //amazing regular expression magic
  private conststring REGEX_GET_STYLES = @"(?<selector>[^\{\s]+\w+(\s\[^\{\s]+)?)\s?\{(?<style>[^\}]*)\}";
  #endregion

  #region Constructors
  ///<summary>
  ///Creates a new PDF document template. Use PageSizes.{DocumentSize}
  ///</summary>
  public HtmlToPdfBuilder(Rectangle size)
  {
    this.PageSize = size;
    this._Pages = newList<HtmlPdfPage>();
    this._Styles = newStyleSheet();
  }
  #endregion

  #region Delegates
  ///<summary>
  /// Method to override to have additional control over the document
  ///</summary>
  public event RenderEvent BeforeRender;

  ///<summary>
  /// Method to override to have additional control over the document
  ///</summary>
  public event RenderEvent AfterRender;
  #endregion

  #region Properties
  ///<summary>
  ///The page size to make this document
  ///</summary>
  public Rectangle PageSize { get; set; }

  ///<summary>
  /// Returns the page at the specified index
  ///</summary>
  public HtmlPdfPage this[int index]
  {
    get{ returnthis._Pages[index]; }
  }

  ///<summary>
  /// Returns a list of the pages available
  ///</summary>
  public HtmlPdfPage[] Pages
  {
    get
    {
      return this._Pages.ToArray(); //http://aspnettutorialonline.blogspot.com/
    }
  }
  #endregion

  #region Members
  private List<HtmlPdfPage> _Pages;
  private StyleSheet _Styles;
  #endregion

  #region Working With The Document
  ///<summary>
  ///Appends and returns a new page for this document http://aspnettutorialonline.blogspot.com/
  ///</summary>
  public HtmlPdfPage AddPage()
  {
    HtmlPdfPage page = new HtmlPdfPage();
    this._Pages.Add(page);
    return page;
  }

  ///<summary>
  ///Removes the page from the document http://aspnettutorialonline.blogspot.com/
  ///</summary>
  public void RemovePage(HtmlPdfPage page)
  {
    this._Pages.Remove(page);
  }

  ///<summary>
  ///Appends a style for this sheet http://aspnettutorialonline.blogspot.com/
  ///</summary>
  public void AddStyle(string selector, string styles)
  {
    this._Styles.LoadTagStyle(selector, HtmlToPdfBuilder.STYLE_DEFAULT_TYPE, styles);
  }

  ///<summary>
  /// Imports a stylesheet into the document
  ///</summary>
  public void ImportStylesheet(string path)
  {

  //load the file
  string content = File.ReadAllText(path);

  //use a little regular expression magic
  foreach (MatchmatchinRegex.Matches(content, HtmlToPdfBuilder.REGEX_GET_STYLES))
  {
    string selector = match.Groups[HtmlToPdfBuilder.REGEX_GROUP_SELECTOR].Value;
    string style = match.Groups[HtmlToPdfBuilder.REGEX_GROUP_STYLE].Value;
    this.AddStyle(selector, style);
  }
}
#endregion

#region Document Navigation
  ///<summary>
  /// Moves a page before another
  ///</summary>
  public void InsertBefore(HtmlPdfPage page, HtmlPdfPage before)
  {
    this._Pages.Remove(page);
    this._Pages.Insert(
    Math.Max(this._Pages.IndexOf(before), 0),page);
  }

  ///<summary>
  /// Moves a page after another
  ///</summary>
  public void InsertAfter(HtmlPdfPage page, HtmlPdfPage after)
  {
    this._Pages.Remove(page);
    this._Pages.Insert(
    Math.Min(this._Pages.IndexOf(after) + 1, this._Pages.Count),page);
  }
#endregion

#region Rendering The Document
///<summary>
///Renders the PDF to an array of bytes
///</summary>
public byte[] RenderPdf()
{

  //Document is inbuilt class, available in iTextSharp
  MemoryStream file = new MemoryStream();
  Documentdocument = new Document(this.PageSize);
  PdfWriter writer = PdfWriter.GetInstance(document, file);

  //allow modifications of the document
  if (this.BeforeRenderisRenderEvent)
  {
    this.BeforeRender(writer, document);
  }

  //header
  document.Add(newHeader(Markup.HTML_ATTR_STYLESHEET, string.Empty));
  document.Open();

  //render each page that has been added
  foreach (HtmlPdfPage page inthis._Pages)
  {
    document.NewPage();

    //generate this page of text
    MemoryStream output = new MemoryStream();
    StreamWriter html = new StreamWriter(output, Encoding.UTF8);

    //get the page output
    html.Write(string.Concat(HtmlToPdfBuilder.DOCUMENT_HTML_START, page._Html.ToString(), HtmlToPdfBuilder.DOCUMENT_HTML_END));
    html.Close();
    html.Dispose();

    //read the created stream
    MemoryStream generate = new MemoryStream(output.ToArray());
    StreamReader reader = new StreamReader(generate);
    foreach (object item inHTMLWorker.ParseToList(reader, this._Styles))
    {
      document.Add((IElement)item);
    }

    //cleanup these streams
    html.Dispose();
    reader.Dispose();
    output.Dispose();
    generate.Dispose();    
  }

  //after rendering
  if (this.AfterRenderisRenderEvent)
  {
    this.AfterRender(writer, document);
  }

  //return the rendered PDF
  document.Close();
  returnfile.ToArray();
  }
  #endregion
}
#endregion

#regionHtmlPdfPage Class
///<summary>
///A page to insert into a HtmlToPdfBuilder Class
///</summary>
public class HtmlPdfPage
{
  #region Constructors
  ///<summary>
  ///The default information for this page
  ///</summary>
  public HtmlPdfPage()
  {
    this._Html = newStringBuilder();
  }
  #endregion

  #region Fields
  //parts for generating the page
  internalStringBuilder _Html;
  #endregion

  #region Working With The Html
  ///<summary>
  ///Appends the formatted HTML onto a page
  ///</summary>
  public virtual void AppendHtml(string content, paramsobject[] values)
  {
    this._Html.AppendFormat(content, values);
  }
  #endregion
}
#endregion

#region Rendering Delegate
///<summary>
/// Delegate for rendering events
///</summary>
public delegate void RenderEvent(PdfWriter writer, Document document);
#endregion

Related Posts

Previous
Next Post »

Thanks for comments.....