How to Convert HTML into PDF in C#

Converting HTML to PDF almost relates to every individual or group as PDF is the best format for safely distribution or sharing. Then how should we convert html to PDF easily and safely becomes very important. Online html to PDF converter is truly convenient but may lead to reveal of privacy, which could be fatal, especially for cooperation, company and organization. A sound solution is that we can customize html to PDF by ourselves. This section shows a direct example for you to manage html to PDF by yourself in C# and VB.NET.

By using Spire.PDF, a professional PDF component, you can convert files of HTML to PDF format under .NET, WPF and Silverlight platforms. You can realize your requirement of converting HTML to PDF in several lines of code.

Here comes to the details:

  • Download Spire.PDF for .NET (or Spire.Office for .NET) and install it on your system.
  • Add Spire.PDF.dll as reference in the downloaded Bin folder thought the below path: "..\Spire.PDF\Bin\NET4.0\ Spire.PDF.dll".
  • Check the codes as below in C#:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using Spire.Pdf;
using System.Drawing;
using Spire.Pdf.Widget;
using Spire.Pdf.Fields;
using System.Threading;
using Spire.Pdf.HtmlConverter;


namespace PDF
{
    class Program
    {
        static void Main(string[] args)
        {

            //Create a pdf document.
            PdfDocument doc = new PdfDocument();

            PdfPageSettings setting = new PdfPageSettings();

            setting.Size = new SizeF(1000,1000);
            setting.Margins = new Spire.Pdf.Graphics.PdfMargins(20);

            PdfHtmlLayoutFormat htmlLayoutFormat = new PdfHtmlLayoutFormat();
            htmlLayoutFormat.IsWaiting = true;
            
            String url = "https://www.wikipedia.org/";
         
            Thread thread = new Thread(() =>
            { doc.LoadFromHTML(url, false, false, false, setting,htmlLayoutFormat); });
            thread.SetApartmentState(ApartmentState.STA);
            thread.Start();
            thread.Join();
            //Save pdf file.
            doc.SaveToFile("output-wiki.pdf");
            doc.Close();
            //Launching the Pdf file.
            System.Diagnostics.Process.Start("output-wiki.pdf");
        }
    }
}

Effective Screenshot:

How to convert HTML into PDF in C#