In this article, you will learn how to convert HTML documents or web pages to PDF programmatically using 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
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
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#.
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#.