How to write a function to convert HTML to PDF in C# for 15 minutes?

How to write a function to convert HTML to PDF in C# for 15 minutes?

PDF Metamorphosis .Net

.Net assembly which gives API to convert RTF, Text, HTML, DOCX to PDF in .Net and C#.
How to write a function to convert HTML to PDF in C# for 15 minutes?

PDF Metamorphosis .Net

How to write a function to convert HTML to PDF in C# for 15 minutes?
How to write a function to convert HTML to PDF in C# for 15 minutes?

Introduction

Imagine, that in 15 minutes after reading this text you will be able to provide API for your application which converts any HTML document to PDF, using C# or VB.Net.


            SautinSoft.PdfMetamorphosis p = new SautinSoft.PdfMetamorphosis();

if (p != null)
{
    // Specify page options.
    p.PageSettings.Size.A4();

    string htmlPath = @"c:\Fathers and Sons.html";
    string pdfPath = @"c:\Fathers and Sons.pdf";

    int result = p.HtmlToPdfConvertFile(htmlPath, pdfPath);
}
          

Download

To see this functionality firsthand, download the freshest «PDF Metamorphosis .Net» with code examples, 39.6 Mb.

Limitations

PDF Metamorphosis .Net The limitations of the free version are: The trial notice "Created by unlicensed version of PDF Metamorphosis .Net" and the random addition of the word "TRIAL".


Input HTML documents

The component can read and parse all types of HTML: 3.2, HTML 4.01, HTML 5 with CSS and XHTML. Our component doesn't require any special version of HTML format it will work with any version. The component has own HTML parser.

Scripting languages (like a JQuery, JavaScript) are not supported. If you want to convert HTML (saturated with JavaScript and complex CSS) to PDF, use another our component - PDF Vision .Net.

These CSS are now supported by the current version of PDF Metamorphosis .Net:

background-color:
background:
border-collapse:
border:
border-top:
border-right:
border-bottom:
border-left:
border-style:
border-top-style:
border-right-style:
border-bottom-style:
border-left-style:
border-width:
border-top-width:
border-right-width:
border-bottom-width:
border-left-width:
border-color:
border-top-color:
border-right-color:
border-bottom-color:
border-left-color:
color:
display:
direction:
font:
font-size:
font-family:
font-weight:
font-style:
height:
list-style-type:
margin:
margin-top:
margin-right:
margin-bottom:
margin-left:
padding:
padding-top:
padding-right:
padding-bottom:
padding-left:
page-break-after:
page-break-before:
page-break-inside:
text-align:
text-decoration:
text-indent:
text-transform:
visibility:
vertical-align:
width:
white-space:

Output PDF documents

PDF Metamorphosis .Net can render PDF documents using own PDF class. You may select the version for output PDF: 1.3 -1.7, PDF/A. If you are looking for .NET class (C#) to convert PDF to other formats, see our PDF Focus .Net.

Some examples to convert HTML to PDF in C# and VB.Net

1. Convert HTML string to PDF bytes in C#:

            SautinSoft.PdfMetamorphosis p = new SautinSoft.PdfMetamorphosis();

            if (p != null)
            {
                string htmlPath = @"c:\Doctor Zhivago.htm";
                string pdfPath = Path.ChangeExtension(htmlPath, ".pdf");
                string htmlString = "";

                // 1. Get HTML content.
                htmlString = ReadFromFile(htmlPath);

                // 2. Converting HTML to PDF
                // Specify BaseUrl to help converter find a full path for relative images, CSS.
                p.HtmlSettings.BaseUrl = Path.GetDirectoryName(Path.GetFullPath(htmlPath));
                byte[] pdfBytes = p.HtmlToPdfConvertStringToByte(htmlString);

                if (pdfBytes != null)
                {
                    // 3. Save the PDF document to a file for a viewing purpose.
                    File.WriteAllBytes(pdfPath, pdfBytes);
                    System.Diagnostics.Process.Start(pdfPath);
                }
            }
      
2. Convert URL to PDF using C#:
            SautinSoft.PdfMetamorphosis p = new SautinSoft.PdfMetamorphosis();

            if (p != null)
            {
                string htmlPath = @"http://www.w3.org/";
                string pdfPath = @"c:\w3.pdf";

                //Converting HTML to PDF
                int result = p.HtmlToPdfConvertFile(htmlPath, pdfPath);
            }

      
3. Convert HTML file to PDF file in VB.Net:
            Dim p As New SautinSoft.PdfMetamorphosis()

            ' Set page options.
            p.PageSettings.Size.A4()
            p.PageSettings.Numbering.Text = "Page {page} of {numpages}"

            Dim htmlPath As String = "d:\One Day in the Life of Ivan Denisovich.htm"
            Dim pdfPath As String = "d:\One Day in the Life of Ivan Denisovich.pdf"

            Dim result As Integer = p.HtmlToPdfConvertFile(htmlPath, pdfPath)
      
4. Convert ASPX page to PDF - C#, ASP.Net application:
Default.aspx.cs:
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Net;
using System.Text;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        //Create a simple ASP.Net page with table inside

        if (!Page.IsPostBack)
        {
            //Create a simple ASP.Net table
            Table table = new Table();
            TableRow row = null;
            TableCell cell = null;

            int rows = 5;
            int cells = 5;
            for (int x = 0; x < rows; x++)
            {
                row = new TableRow();
                for (int y = 0; y < cells; y++)
                {
                    cell = new TableCell();
                    cell.Width = Unit.Pixel(80);
                    cell.BorderColor = System.Drawing.ColorTranslator.FromHtml("darkgreen");
                    cell.BorderWidth = Unit.Pixel(2);
                    cell.Font.Name = "Helvetica";
                    cell.Font.Size = FontUnit.Point(10);
                    cell.HorizontalAlign = HorizontalAlign.Center;

                    cell.Text = "Row " + ((int)(x + 1)).ToString() + ", Cell " + ((int)(y + 1)).ToString();
                    row.Cells.Add(cell);
                }
                table.Rows.Add(row);
            }

            //Add table to page
            Panel1.Controls.Add(table);
        }
    }

    //Get HTML from ASPX
    protected override void Render(HtmlTextWriter writer)
    {
        // setup a TextWriter to capture the markup
        TextWriter tw = new StringWriter();
        HtmlTextWriter htw = new HtmlTextWriter(tw);

        // render the markup into our surrogate TextWriter
        base.Render(htw);

        // get the captured markup as a string
        string currentPage = tw.ToString();

        //Save HTML code to tempory file
        if (!Page.IsPostBack)
            File.WriteAllText(Path.Combine(Server.MapPath("Temp"), "temp.htm"), currentPage, Encoding.UTF8);

        // render the markup into the output stream verbatim
        writer.Write(currentPage);
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        //Get HTML from temporary file which we've created in the overriden method Render()
        string html = File.ReadAllText(Path.Combine(Server.MapPath("Temp"), "temp.htm"), Encoding.UTF8);

        string url = System.Web.HttpContext.Current.Request.Url.AbsoluteUri;

        if (html.Length > 0)
        {
            SautinSoft.PdfMetamorphosis p = new SautinSoft.PdfMetamorphosis();
		    //After purchasing the license, please insert your serial number here to activate the component
            //p.Serial = "XXXXXXXXXXX";

            p.HtmlSettings.BaseUrl = url;

            byte[] pdf = p.HtmlToPdfConvertStringToByte(html);

            //show PDF
            if (pdf != null)
            {
                Response.Buffer = true;
                Response.Clear();
                Response.ContentType = "application/PDF";
                Response.AddHeader("content-disposition:", "attachment; filename=Result.pdf");
                Response.BinaryWrite(pdf);
                Response.Flush();
                Response.End();
            }

        }
    }
}
      
Default.aspx:
<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!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>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Panel ID="Panel1" runat="server">
        </asp:Panel>
        <asp:Button ID="Button1" runat="server" Text="Convert" OnClick="Button1_Click"/>
   </div>
    </form>
</body>
</html>

Requirements and Technical Information

Requires .NET Framework 4.0 or higher. Our product is compatible with all .NET languages and supports all Operating Systems where .NET Framework and .NET Core can be used. Note that PDF Metamorphosis .Net is entirely written in managed C#, which makes it absolutely standalone and an independent library.

.Net Framework 4.0 and higher and .Net Core 2.0 and higher

.NET Framework 4.0, 4.5, 4.6.1 and higher.

.NET Standard 2.0

.NET Core 2.0 and higher.


Multi-platform component, runs on:


Our component has proven itself on cloud platforms and services:

  • Microsoft Azure
  • Amazon Web Services (AWS)
  • Google Cloud Platform
  • SharePoint
  • Docker
  • etc.

If you need a new code example or have a question: email us at support@sautinsoft.com or ask at Online Chat (right-bottom corner of this page) or use the Form below: