Convert HTML Files to PDF in C# .NET

In this article, you will learn how to convert HTML documents or web pages to PDF programmatically using C#.

HTML to PDF in C#

There are various scenarios when you need to perform HTML to PDF conversion. For example, you may want to convert a web page to PDF from within your application or you may need to generate PDF from the content of a WYSIWYG HTML editor. Another scenario could be converting the HTML page from a specific URL to PDF. In order to deal with such cases, I’ll show you how to convert HTML to PDF in C# .NET. We’ll perform the following HTML to PDF conversions:

  • HTML to PDF in C#
  • HTML to password-protected PDF in C#
  • HTML page from a particular URL to PDF in C#

C# HTML to PDF Converter API

We’ll use Aspose.PDF for .NET API to convert HTML documents to PDF. You can either download API’s DLL or install its package using one of the following ways in Visual Studio.

NuGet Package Manager


Package Manager Console

PM> Install-Package Aspose.PDF

Convert HTML to PDF in C#

The following are the simple steps to convert an HTML file to PDF using Aspose.PDF for .NET.

  • Create an instance of the HtmlLoadOptions class.
  • Create an instance of Document class and initialize it with the HTML file’s path and HtmlLoadOptions object.
  • Call Document.Save(String) method with the output PDF file’s name.

The following code sample shows how to convert HTML to PDF in C#.

Input HTML File

Convert HTML to PDF

Converted PDF Document


Convert HTML to Password-Protected PDF in C#

You can also convert HTML files to encrypted PDF documents using Aspose.PDF for .NET. The resultant PDF document can be protected with the user’s password, the owner’s password, access permissions, and cryptographic algorithm. You can encrypt the converted PDF using the Document.Encrypt() method. The following code sample shows how to convert HTML file to encrypted PDF in C#.


HTML to encrypted PDF

Convert Web Page to PDF from URL in C#

Aspose.PDF for .NET also supports HTML to PDF conversion from the live URLs. The following are the steps to convert a web page from a URL to PDF.

  • Make a web request to the URL using WebRequest.
  • Get the response of the web request into the Stream object.
  • Create the Document object and initialize it with InputStream and HtmlLoadOptions objects.
  • Save HTML stream as PDF using Document.Save() method.

The following code sample shows how to convert the HTML web page to PDF in C#.

Related Article