PRODUCTS   DOWNLOAD PURCHASE SUPPORT BLOG  COMPANY  
 
Key Features
DOCX to PDF
RTF to PDF
>>HTML to PDF
Text to PDF
Split and merge PDF
Download trial
Purchase
Online-demo
Documentation
What's New

"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 PDF Metamorphosis .Net Online Demo


Have a Question?

You have a question, need a support or a code example: ask our support team at support@sautinsoft.com. We will help you quickly and with pleasure.

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: border-top-style: border-color: font-size: margin-bottom:
background: border-right-style: border-top-color: font-family: margin-left:
border-collapse: border-bottom-style: border-right-color: font-weight: padding:
border: border-left-style: border-bottom-color: font-style: padding-top:
border-top: border-width: border-left-color: height: padding-right:
border-right: border-top-width: color: list-style-type: padding-bottom:
border-bottom: border-right-width: display: margin: padding-left:
border-left: border-bottom-width: direction: margin-top: page-break-after:
border-style: border-left-width: font: margin-right: page-break-before:
         
page-break-inside: text-indent: vertical-align:    
text-align: text-transform: width:    
text-decoration: visibility: 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.2 -1.6, PDF/A. If you are looking for .Net class (C#) to convert PDF to other formats, see our PDF Focus .Net.


What PDF Metamorphosis .Net can give me:

  1. Save a time and cost of developing of my application. You will need to only add the reference to "PdfMetamorphosis.dll" and write 3-4 C# lines to get ability create PDF from HTML, RTF, Text or PDF from DOCX.

  2. The one product provides me by set of API to convert from Text, RTF, HTML to PDF at once, split and merge PDF documents.

  3. Because of this is absolutely standalone PDF library, I don't need to worry about the availability of Adobe Acrobat, MS Word, OpenOffice or other software on the my client's computers.

  4. My software will have the one of the fastest API to convert into PDF documents and therefore my clients will not have any delays during creating PDF documents.

  5. I don't need to worry about accuracy of source HTML and RTF documents. PDF Metamorphosis .Net can "eat" any types, versions and produce for me a valid PDF document.

  6. The one time price. I pay a one time and can use «PDF Metamorphosis .Net» for a whole life without any additional fees. My license will never expires.

  7. As bonus, I get unlimited technical support during a whole life for free and independently of the date of my purchasing.

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" %>





    Untitled Page


    
If anyone needs a code sample in C#, VB.Net, ASP.Net etc "How to convert HTML to PDF", email us at support@sautinsoft.com or ask at Online Chat (right-bottom corner of this page). We'll help you certainly!


Requrements and Technical Information

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



Reasonable prices

     The library offers developers high quality conversion at reasonably prices. The main point of interest is that PDF Metamorphosis .Net is less expensive than all of its more or less popular counterparts. For example, a single license cost $339 with no additional fees or royalties!


Download

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

 
 
Products Downloads Support Company
Buy now
Follow us on Google Plus SautinSoft on Facebook SautinSoft on Twitter SautinSoft on Youtube Our Blog
Copyright © 2002 - 2017 SautinSoft (started from sautin.com). All rights reserved.