Convert HTML String to PDF C#

HTML plays a pivotal role in web content, and converting HTML to PDF is crucial for archiving, sharing, and ensuring consistent formatting across various platforms. In this article, you’ll learn how to convert an HTML string to a PDF using the Aspose.HTML for .NET library, a powerful tool designed for efficient and reliable HTML-to-PDF conversion.

Topics Covered:

  1. C# API for HTML to PDF Conversion
  2. Steps to Convert HTML String to PDF
  3. Code Example for HTML to PDF Conversion

C# API to Convert HTML String to PDF

Aspose.HTML for .NET is a robust library specifically designed for creating, editing, and converting HTML into various formats, including PDF. It offers direct conversion of HTML strings to PDF, ensuring content accuracy and formatting preservation. The library includes the Converter class and PdfSaveOptions that enhance flexibility in HTML to PDF conversion workflows.

Key Features:

  • Convert HTML strings or files to PDF effectively.
  • Supports advanced rendering and customization options, such as background colors, watermarks, and styling.
  • Compatible with .NET Framework, .NET Core, and .NET Standard for cross-platform development.
  • A reliable and high-performance HTML to PDF conversion solution with support for large files.

Installation:
To incorporate Aspose.HTML for .NET into your project, you can simply add it via NuGet:

PM> Install-Package Aspose.Html

How to Convert HTML String to PDF in C#

You can easily convert an HTML string to PDF by following these straightforward steps:

  1. Define an HTML string.
  2. Specify PDF Save Options.
  3. Convert the HTML code to PDF.

The following section details how to implement these steps in C# code to generate a PDF from an HTML string.

Convert HTML String to PDF using C#

To convert an HTML string to a PDF document, adhere to the steps outlined below:

  1. First, define your HTML content within a string variable.
  2. Next, create an instance of the PdfSaveOptions class.
  3. Optionally, specify additional save options, such as BackgroundColor and other styling preferences.
  4. Finally, use the Converter.ConvertHTML() method to produce the PDF. This method requires the HTML string, PdfSaveOptions, and the output PDF file path as arguments.

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

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, ideal for testing the C# HTML to PDF conversion capabilities or the affordable HTML to PDF conversion solution.

Conclusion

In this article, we have learned how to convert an HTML string to a PDF in C#. You can further explore the Aspose.HTML for .NET API through the documentation. For any questions or clarifications, please feel free to reach out on our free support forum.

See Also