Convert HTML String to PDF C#

HTML is a markup language that enables the creation of web pages. A PDF is a format for capturing content for use in electronic documents, such as printouts and documents on screen. Both HTML and PDF have been around for quite some time, but their purpose has changed in recent years. Have you ever been in a situation where you wanted to convert an HTML string to a PDF document? The need to convert HTML to PDF will arise when you want to save your website in a portable format or print the document out. In this article, we will learn how to convert an HTML string to a PDF in C#.

The following topics shall be covered in this article:

  1. C# API to Convert HTML String to PDF
  2. Steps to Convert HTML String to PDF
  3. Convert HTML String to PDF

C# API to Convert HTML String to PDF

To convert an HTML string to a PDF document, we will be using the Aspose.HTML for .NET API. It allows creating, modifying, and extracting data from HTML documents. It also allows converting HTML documents to supported formats without any external software.

The API provides the PdfSaveOptions class that allows specifying various save options while saving as a PDF. The Converter class provides a wide range of conversions to the popular formats, such as PDF, XPS, image formats, etc. It provides the ConvertHTML() methods to convert HTML to other formats.

Please either download the DLL of the API or install it using NuGet.

PM> Install-Package Aspose.Html

How to Convert HTML String to PDF in C#

We can easily convert an HTML string to PDF by following the steps given below:

  • Define an HTML string.
  • Specify PDF Save Options.
  • Convert HTML code to PDF.

The following section describes how to transform these steps into C# code and generate a PDF from an HTML string.

Convert HTML String to PDF using C#

We can convert an HTML string to a PDF document by following the steps given below:

  1. Firstly, define HTML code in a string.
  2. Next, create an instance of the PdfSaveOptions class.
  3. Optionally, define save options such as BackgroundColor.
  4. Finally, call the Converter.ConvertHTML() method to generate a PDF. It takes HTML string, PdfSaveOptions and output PDF file path as arguments.

The following code sample shows how to convert an HTML string to a PDF document in C#.

Convert HTML String to PDF using C#

Convert HTML String to PDF using C#

Get Free License

You can get a free temporary license to try Aspose.HTML for .NET without evaluation limitations.

Conclusion

In this article, we have learned how to convert an HTML string to a PDF in C#. Besides, you can learn more about Aspose.HTML for .NET API using documentation. In case of any ambiguity, please feel free to contact us on our free support forum.

See Also