How to Programmatically Convert HTML to PDF in C#
| Quick Start Guide | |
|---|---|
| Tutorial Concept | This tutorial demonstrates how to convert HTML content into PDF files programmatically using the DsHtml and DsPdf libraries included in the Document Solutions for PDF API library in .NET 8+. |
| What You Will Need |
|
| Controls Referenced |
This tutorial uses the following key classes from the DS.Documents.Html and DS.Documents.Pdf namespaces:
|
HyperText Markup Language (HTML) has served as the foundation of web content creation and navigation since the earliest days of the internet. As the world continues to move rapidly toward digital transformation, the importance of HTML has only increased. Today, information presented in HTML is no longer intended solely for online viewing; users also expect to access the same content seamlessly in offline and portable formats. The PDF format provides an ideal solution for meeting this need, and this blog demonstrates how to achieve that conversion effectively.
Document Solutions offers the DsHtml library, a dedicated solution for converting HTML content into high-quality PDF documents and images. With each release, the DsHtml package has evolved to eliminate dependencies on specific browser versions and GPL/LGPL-licensed components. It no longer relies on a custom Chromium build and can now operate using the Chrome or Edge browsers already installed on the system. Alternatively, DsHtml can automatically download a compatible Chromium build from a public source and install it in a local directory for use by the application.
In this blog, we will introduce the latest DsHtml package, share key considerations for migrating from older versions, and walk through practical examples demonstrating how to convert HTML to PDF using DsHtml in the sections that follow.
Ready to Test it Out? Download Document Solutions Today!
.NET Developer Guide to Converting PDF to HTML using C#
- Setup and Installation
- Rendering HTML to PDF
- Best Practices for HTML to PDF Conversion
- Customizing the PDF Output
- Conclusion
Setup and Installation
To get started, install the DsHtml package in your application using the NuGet Package Manager. In Visual Studio, search for DS.Documents.Html on NuGet and install the package into your project, as shown in the screenshot below.

DsHtml uses either a Chrome or Edge browser, typically already installed on the system or a Chromium build downloaded from a public source running in headless mode. Communication with the browser is established through the WebSocket protocol. As with recent versions, platform-specific (OS-specific) NuGet packages are no longer required, simplifying deployment across environments.
The following classes within the DS.Documents.Html namespace represent the core components of the HTML-to-PDF conversion workflow:
- BrowserFetcher – Locates an installed Chrome or Edge browser, or downloads a compatible Chromium build from a public server.
- GcHtmlBrowser – Represents a headless browser process, such as Chrome, Edge, or Chromium.
- HtmlPage – Represents a browser tab that loads HTML content and provides methods to export the content as PDF or images.
For detailed information on these and other classes available in the package, refer to the official documentation.
Note: The legacy GcHtmlRenderer class is now obsolete. While it remains available for backward compatibility, it is internally implemented using GcHtmlBrowser.
Rendering HTML to PDF in .NET Apps
To begin, let’s first understand how the DsHtml library helps convert HTML to PDF. The DsHtml library provides two different ways to perform HTML to PDF conversion. The list below summarizes these methods:
1. Using GcHtmlBrowser class: This approach can be considered when you want to generate a PDF document from scratch or a PDF document that solely consists of the HTML content you are looking forward to rendering.
To implement this approach, the NewPage method of the GcHtmlBrowser class should be invoked to prepare a browser page with HTML content. This method has two overloads, one that accepts Uri to the source HTML page and the other that accepts HTML as a plain string.
This method returns an instance of the HtmlPage class, and then the SaveAsPdf method of the HtmlPage class helps to convert the source HTML to PDF. It accepts the output file path as the first parameter. The second parameter (optional) is the PdfOptions instance that defines parameters for the output PDF file.
2. Using DrawHtml method: This approach can be considered when you would like to append the HTML information into an existing PDF file that already has some other content available. All the HTML content you want to render as PDF will be appended on a new page in the existing document.
This method extends the GcPdfGraphics class and allows it to render an HTML text or page in a PDF. This also allows inserting HTML fragments into a PDF file along with other (non-HTML) content.
DrawHtml method has two overloads:
Draws an HTML string on GcPdfGraphics at a specified position:
bool GcPdfGraphics.DrawHtml(GcHtmlBrowser browser, string html, float x, float y, HtmlToPdfFormat format, out SizeF size);
Draws an HTML page specified by a URI on GcPdfGraphics at a specified position:
bool GcPdfGraphics.DrawHtml(GcHtmlBrowser browser, Uri htmlUri, float x, float y, HtmlToPdfFormat format, out SizeF size);
Here, the HtmlToPdfFormat class contains attributes for rendering HTML on a GcPdfGraphics instance using the DrawHtml extension methods.
Best Practices for HTML to PDF Conversion in .NET
Convert Local HTML Files to PDF in .NET
Consider a scenario in which invoices are generated dynamically within an e-commerce platform. These invoices are typically produced in HTML to allow for quick viewing in a web browser. However, when customers access these invoices offline or on different devices, the formatting and layout may not always appear consistently.
To preserve the original layout, styling, and structure across all platforms, converting HTML invoices to PDF provides a far more reliable solution. Once converted, the PDF invoices can be securely emailed, archived for record-keeping, or downloaded by users without any risk of formatting inconsistencies.
Below is an example of an invoice template that was originally displayed in HTML format and later converted into a PDF using the DsHtml and DsPdf libraries:

To accomplish this using .NET 8+, follow these steps:
- Create a new .NET Console Application in Visual Studio.
- Right-click Dependencies → Manage NuGet Packages.
- Install the following packages:
- DS.Documents.Pdf
- DS.Documents.Html
- Accept the preview and license dialogs.
Add the required namespaces:
using GrapeCity.Documents.Html;
using GrapeCity.Documents.Pdf;
using GrapeCity.Documents.Drawing;
using System.Drawing;
Once the setup is complete, you can convert the HTML invoice to PDF using either of the two DsHtml approaches:
- Rendering the full web page or HTML file into a PDF
- Embedding the HTML directly inside an existing PDF
The examples below demonstrate both approaches.
Approach 1: Using GcHtmlBrowser
In this example, the invoice is generated from a live HTML webpage (the SparkSuite invoice template). The browser loads the URL, renders the page in headless mode, and exports it directly to PDF.
namespace MyApp
{
internal class Program
{
static void Main(string[] args)
{
// Use BrowserFetcher to get a compatible Chromium executable.
var browserExecutablePath = new BrowserFetcher().GetDownloadedPath();
// Create the GcHtmlBrowser instance using the fetched Chromium path.
using var browser = new GcHtmlBrowser(browserExecutablePath);
// Define the URL of the HTML invoice template to be converted to PDF.
var uri = new Uri("https://sparksuite.github.io/simple-html-invoice-template/", UriKind.Absolute);
// Create a new page and load the URL
using (var page = browser.NewPage(uri, new PageOptions
{
WindowSize = new Size(1024, 1024)
}))
{
// Save the rendered HTML page as a PDF file
page.SaveAsPdf("Invoice_Example.pdf", new PdfOptions
{
FullPage = false
});
Console.WriteLine("PDF saved as 'Invoice_Example.pdf'");
}
}
}
}
Result: The generated PDF faithfully reproduces the HTML invoice, preserving fonts, layout, spacing, and styling.
Approach 2: Using DrawHtml
If you already have a PDF document and want to embed HTML content into a specific location (for example, adding a styled invoice section inside a custom PDF template), you can use the DrawHtml method.
In this approach, the HTML is read from a local file (invoice.html), and the HTML is drawn onto a new PDF page.
using GrapeCity.Documents.Html;
using GrapeCity.Documents.Pdf;
using GrapeCity.Documents.Drawing;
using System.Drawing;
using System.IO;
namespace MyApp
{
internal class Program
{
static void Main(string[] args)
{
// Use BrowserFetcher to locate or download a compatible Chromium build
var browserExecutablePath = new BrowserFetcher().GetDownloadedPath();
// Create the GcHtmlBrowser instance with the fetched Chromium executable
using var browser = new GcHtmlBrowser(browserExecutablePath);
// Create a GcPdfDocument instance
var doc = new GcPdfDocument();
// Add a new page to the document
var page = doc.Pages.Add();
// Take the Graphics instance of the page
var g = page.Graphics;
// Add the HTML file to it, using the DrawHtml method which reads the HTML content from the invoice file
g.DrawHtml(
browser,
File.ReadAllText("invoice.html"),
72, 72,
new HtmlToPdfFormat(false)
{
MaxPageWidth = 6.5f,
MaxPageHeight = 9f
},
out SizeF size);
// Save the PDF Document
doc.Save("Invoice_Draw.pdf");
Console.WriteLine("PDF saved as 'Invoice_Draw.pdf'");
}
}
}
Result: The output PDF renders the HTML inside an existing page:

Generate PDF from an HTML String in .NET Apps
Simple HTML strings can be directly rendered to PDF using the DrawHtml method. This can be done using HTML files, allowing you to directly specify the HTML content.
Follow steps as mentioned above. After that, add the following code in the Program.cs file, which performs the HTML to PDF conversion using the DrawHtml method approach:
using GrapeCity.Documents.Html;
using GrapeCity.Documents.Pdf;
using GrapeCity.Documents.Drawing;
using System.Drawing;
namespace MyApp
{
internal class Program
{
static void Main(string[] args)
{
//Create a variable containing the HTML code as string
var html = "<!DOCTYPE html>" +
"<html>" +
"<head>" +
"<style>" +
"p.round {" +
"font: 36px verdana;" +
"color: Red;" +
"border: 4px solid SlateBlue;" +
"border-radius: 16px;" +
"padding: 3px 5px 3px 5px;" +
"}" +
"</style>" +
"</head>" +
"<body>" +
"<p class='round'>Thank You for shopping with us!</p>" +
"<p class='round'>Hope to see you again soon.</p>" +
"</body>" +
"</html>";
// Create a GcPdfDocument instance
var doc = new GcPdfDocument();
// Add a new page to the document
var page = doc.Pages.Add();
// Take the Graphics instance of the page
var g = page.Graphics;
//Define GcHtmlBrowser instance
var path = new BrowserFetcher().GetDownloadedPath();
using (var browser = new GcHtmlBrowser(path))
{
// Render the HTML string on the PDF, using the DrawHtml method
var ok = g.DrawHtml(browser, html, 72, 72,
new HtmlToPdfFormat(false) { MaxPageWidth = 6.5f },
out SizeF size);
// Additionally, draw a rounded rectangle around this HTML string
if (ok)
{
var rc = new RectangleF(72 - 4, 72 - 4, size.Width + 8, size.Height + 8);
g.DrawRoundRect(rc, 8, Color.PaleVioletRed);
}
// Save the PDF Document
doc.Save("HTMLStringToPDF.pdf");
}
}
}
}
Executing the code above generates a PDF containing the rendered HTML string, styled according to the embedded CSS. The rectangle drawn around the text demonstrates how HTML output can be combined with additional PDF graphics.

Convert Live Web Pages to PDF in .NET
The GcHtmlBrowser class and HtmlPage class can be used to render webpages to a PDF. If the above-discussed firm wants to update its customers or the stakeholders with the new products every month, it sends a PDF generated from the New Releases page on its website. The process should be automated to make the stakeholders aware of the new launches regularly and create a consolidated report at the end of every year.
Here is a view of one such web page:

The GcHtmlBrowser class, along with HtmlPage class, can be used to perform the conversion. The Uri of the webpage will be used, and the required settings of the PDF are applied using the PdfOptions class.
Follow steps as mentioned above. After that, add the following code in the Program.cs file, which performs the HTML to PDF conversion using the GcHtmlBrowser class approach:
using GrapeCity.Documents.Html;
using GrapeCity.Documents.Pdf;
using GrapeCity.Documents.Drawing;
using System.Drawing;
namespace MyApp
{
internal class Program
{
static void Main(string[] args)
{
// Specify a PDF file name
var fn = @"webpage.pdf";
// Specify the URL to be used for PDF conversion
var uri = new Uri(@"https://www.amazon.com/gp/new-releases/electronics/ref=zg_bs_tab_t_bsnr");
// Define GcHtmlBrowser instance
var path = new BrowserFetcher().GetDownloadedPath();
using (var browser = new GcHtmlBrowser(path))
{
// Define PDF-related settings
var pdfOptions = new PdfOptions()
{
PageRanges = "1-100",
Margins = new PdfMargins(0.2f), // narrow margins all around
Landscape = false,
PreferCSSPageSize = true
};
// Create an HtmlPage instance from the source URL
using var htmlPage = browser.NewPage(uri);
// Render the webpage into a PDF file
htmlPage.SaveAsPdf(fn, pdfOptions);
}
}
}
}
Here is a quick view of the PDF file generated from the web page:

Customizing the PDF Output
As mentioned earlier in the blog, the PdfOptions class exists to allow the developer to control how the PDF output will appear once generated. Below are the different features available within the class:
- DisplayHeaderFooter: Gets or sets a value indicating whether the header and footer are rendered.
- FooterTemplate: Gets or sets the HTML template for the page footer.
- FullPage: Gets or sets a value indicating whether the whole HTML page should be rendered as a single PDF page.
- HeaderTemplate: Gets or sets the HTML template for the page header.
- Landscape: Gets or sets a value indicating whether the paper orientation is Landscape.
- Margins: Gets or sets page margins in inches.
- PageHeight: Gets or sets the page height in inches.
- PageRanges: Gets or sets the range of pages to render, e.g., '1-5, 8, 11-13'.
- PageWidth: Gets or sets the page width in inches.
- PreferCSSPageSize: Gets or sets a value indicating whether the CSS-defined page size should have priority over what is declared in PageWidth and PageHeight.
- PrintBackground: Gets or sets a value indicating whether to print background graphics.
- Scale: Gets or sets the scale factor between 0.1 and 2.0.
Conclusion: Key Takeaways for HTML to PDF Conversion in .NET
In this blog, we explored the two main approaches to utilizing the DsHtml library when converting HTML content to PDF format. If you enjoyed learning about this topic and are interested in more code examples, please check out our in-depth HTML conversion demos, complete with code and comments, as well as rendered PDF output. These are a great resource when testing out different features contained within the library. The documentation linked throughout this blog is also a valuable resource for learning more about the API library.