HTML to PDF Conversion Using Syncfusion PDF

Programming, error messages and sample code > ASP.NET

Assemblies Required

  1. Syncfusion.Compression.Base.dll
  2. Syncfusion.HtmlConverter.Base.dll
  3. Syncfusion.Pdf.Base.dll
  4. System.Windows.Forms.dll
  5. Microsoft.mshtml.dll
 
You have to put these assemblies to bin folder and make sure they are used for 32 bit.
 
 
HtmlToPDF.aspx
 
<%@ Page Language="C#" AspCompat="true" AutoEventWireup="true" CodeFile="HtmlToPDF.aspx.cs" Inherits="HtmlToPDF" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>HTMLtoPDF Demo</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <h4>HTMLtoPDF Conversion Demo</h4>
    </div>
    <div>
        <asp:Button ID="Button1" runat="server" Text="PDF" onclick="Button1_Click" />
    </div>
    </form>
</body>
</html>
 
HtmlToPDF.aspx.cs
 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using Syncfusion.Pdf;
using Syncfusion.Pdf.Graphics;
using Syncfusion.HtmlConverter;
using System.Drawing;
using System.Drawing.Imaging;

public partial class HtmlToPDF : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        StreamReader reader = new StreamReader(Server.MapPath(@"App_Data\Template.html"));
        string htmlContent = reader.ReadToEnd();
        //Create a new pdf document
        PdfDocument pdf = new PdfDocument();
        //Adds a new pdf page.
        PdfPage page = pdf.Pages.Add();
        PdfUnitConvertor converter = new PdfUnitConvertor();
        float width = converter.ConvertToPixels(page.GetClientSize().Width, PdfGraphicsUnit.Point);

        using (HtmlConverter htmlconverter = new HtmlConverter())
        {
            //Renders html from the string to image.
            PdfMetafile mf = new PdfMetafile(htmlconverter.FromString(htmlContent, Path.GetFullPath(@"..\..\Template.html"), ImageType.Metafile, (int)width, -1, AspectRatio.KeepWidth) as Metafile);
            mf.Quality = 100;

            PdfMetafileLayoutFormat format = new PdfMetafileLayoutFormat();
            format.Break = PdfLayoutBreakType.FitPage;
            format.Layout = PdfLayoutType.Paginate;
            //Draws the image.
            mf.Draw(page, new PointF(0, 0), format);
        }

        pdf.Save("DoctoPDF.pdf", Response, HttpReadType.Open);

    }
}