How to convert HTML into PDF in C#, VB.NET

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# and VB.NET:
[C#]
static void Main(string[] args)
{
 //Create a pdf document.
 PdfDocument doc = new PdfDocument();
 String url = "http://www.london2012.com/news/articles/paralympic-torch-relay-route-revealed-1258473.html";
 Thread thread = new Thread(() =>
 { doc.LoadFromHTML(url, false, true, true);});
 thread.SetApartmentState(ApartmentState.STA);
 thread.Start();
 thread.Join();
 //Save pdf file.
 doc.SaveToFile("sample.pdf");
 doc.Close();
 //Launching the Pdf file.
 System.Diagnostics.Process.Start("sample.pdf");
}
[VB.NET]
 Sub Main()

        Dim thread As Thread = New Thread(AddressOf LoadHtml)
        thread.SetApartmentState(ApartmentState.STA)
        thread.Start()
        thread.Join()

    End Sub
    Private Sub LoadHtml()
        Dim path As String = "sample.pdf"
        Dim pdfDoc As PdfDocument = New PdfDocument()
        Dim url As String = "http://www.london2012.com/news/articles/paralympic-torch-relay-route-revealed-1258473.html"
        pdfDoc.LoadFromHTML(url, False, True, True)
        pdfDoc.SaveToFile(path, FileFormat.PDF)
        pdfDoc.Close()
        pdfDoc.Dispose()
    End Sub

Effective Screenshot:

HTML TO PDF c#/vb.net