HTML to PDF for .NET
You can convert HTML to PDF using the Docotic.Pdf library. The free HtmlToPdf add-on to the library makes it possible to convert HTML, SVG, WEBP, and other web formats to PDF.
This guide outlines the HTML to PDF features provided by the add-on and includes links to pages that provide additional details on the topics discussed.

The basics of HTML to PDF in C#
You will need the HtmlToPdf add-on, a conversion snippet, and a license key. You can start with a free trial key.
Install the add-on from NuGet
Install-Package BitMiracle.Docotic.Pdf.HtmlToPdf
This is the recommended way because it automatically handles dependencies and updates. You can also install the add-on manually from the zip with the Docotic.Pdf binaries, even though it is more complicated and error-prone.
Get a license key
To try the library, obtain a free time-limited license key from the Docotic.Pdf download page. If you have already purchased a license, use the code provided to you after the purchase.
All Docotic.Pdf licenses include HTML to PDF features. There is no need to purchase an additional license to use the add-on.
Add the conversion code
BitMiracle.Docotic.LicenseManager.AddLicenseData("PUT-LICENSE-HERE");
using var converter = await HtmlConverter.CreateAsync();
var html = "<h1>Hello, World<h1>";
using var pdf = await converter.CreatePdfFromStringAsync(html);
pdf.Save("output.pdf");
In the code, replace the placeholder value in the AddLicenseData method call with a valid license
key.
Run the code
The conversion code will create a PDF from the HTML code in the string. With the default conversion options, the output will contain one A4-sized page.
The library provides a lot of options for customizing the conversion. You can change the output size or add headers and footers to the generated pages. It is also possible to convert resources that require authentication.
Read about the different ways to convert HTML to PDF in the dedicated article, which explains each approach in great detail.
Why Docotic.Pdf is the right HTML to PDF converter?
The ability to preserve styles and layout during conversion makes Docotic.Pdf the right choice for producing PDFs from HTML reports, invoices, and other documents. The library produces pixel-perfect PDF documents from HTML and other web formats such as SVG. Reusing existing HTML content is easy with the library.
The converter uses the Google Chrome rendering engine. This means the same level of web-standards compliance as one of the best web browsers.
You can use Docotic.Pdf to produce PDFs from very complex layouts with modern CSS, JavaScript, and images. Responsive web design is very well supported, too.
API architecture overview
The HTML to PDF API is available only when using Docotic.Pdf together with the free HtmlToPdf add-on.
The add-on provides an asynchronous-only API. We designed it to work with async event handlers and async methods. This design allows long‑running tasks to be handled gracefully, and media conversion is an ideal example of such a task.
.NET versions and platform support
The library and the add-on target .NET Standard 2.0. This means both are compatible with .NET 5 through .NET 10. In addition, .NET Core 2.0+ and .NET Framework 4.6.1+ are also supported.
You can use the HTML to PDF features in Windows Forms, WPF, ASP.NET, and console applications. The add-on can run in cloud environments and in Docker containers.
With the help of the add-on, you can generate PDF from HTML in Windows, macOS, and Linux environments.
What happens during a conversion?
By default, a conversion consists of these stages:
- Your code calls the
CreateAsyncmethod of the HtmlConverter class. - The add-on checks whether an eligible version of Google Chrome exists in the
.local-chromiumfolder inside the current working directory. - If there is no eligible version, the add-on downloads one and unpacks it into the
.local-chromiumfolder. - When your code calls the
CreatePdfAsyncorCreatePdfFromStringAsyncmethod, the add-on uses Google Chrome to load the provided HTML. - When the content is ready for conversion, the add-on instructs the browser to produce a PDF.
- Google Chrome generates the PDF using the rendering capabilities of Chromium.
- The add‑on returns a PdfDocument containing the produced PDF to your code.
Cloud platforms and Docker images
The HtmlToPdf add-on supports Azure and AWS cloud platforms, including serverless environments. You can also use the HTML to PDF API in Docker containers. Here is the list of supported environments:
- Azure: Azure Functions, Azure App Service, Azure VPS
- Amazon Web Services: AWS ECS, Amazon EC2
- Docker: Windows and Linux containers.
The library and the add‑on fully support dynamic hardware changes, autoscaling, and other cloud‑native runtime features.
Refer to the article on running the add-on in clouds and in Docker images for more information.
What license types are supported for cloud apps?
In most cases, you will need an unbound license (Ultimate or Ultimate+). A Server license may also work if the hardware ID does not change.
Server licenses are tied to the hardware ID of the server. If the hardware changes between runs or reboots, the Server license will no longer be valid. It also won't work in environments where the number of servers can change dynamically, because each production server requires a unique license.
To ensure your server's hardware ID remains consistent, you can check the value of the LicenseManager.Uid property. Alternatively, you can use our UID generator application to retrieve the same ID.
How to generate PDF from HTML template
Follow these simple steps:
- Retrieve the data for the template.
- Fill the template with the data to produce a complete HTML.
- Use Docotic.Pdf to convert the complete HTML to PDF.

Template data usually comes from a database or an API response. With a database, it can be a single record or a set of records. For an API, it is often a JSON object describing one or more entities.
For the examples below, I will use this fictional person:
var person = new
{
Name = "Alice Johnson",
Age = 27,
Email = "alicej@example.com",
Occupation = "Truck driver"
};
Now that I have the data, I will present three options for preparing and filling an HTML template. In all three cases, the resulting complete HTML will be the same, even though the corresponding templates are different.
To convert the complete HTML, use the code I have already provided.
Named placeholders
Named placeholders are tokens enclosed in double delimiters that use non‑alphanumeric symbols. One
of the most collision-resistant delimiters is %%.
Here is a template with named placeholders, along with the code that produces complete HTML from it:
var template = @"<head><title>%%NAME%%'s Profile</title></head>
<body>
<h1>%%NAME%%</h1>
<p><strong>Age:</strong> %%AGE%%</p>
<p><strong>Email:</strong> %%EMAIL%%</p>
<p><strong>Occupation:</strong> %%OCCUPATION%%</p>
</body></html>";
var completeHtml = template
.Replace("%%NAME%%", person.Name)
.Replace("%%AGE%%", person.Age.ToString())
.Replace("%%EMAIL%%", person.Email)
.Replace("%%OCCUPATION%%", person.Occupation);
Using named placeholders is the recommended approach in most cases. However, remember to escape any values you insert in place of placeholders.
Template engines
When your template is very complex and/or requires reusable parts, the named placeholders may not be very convenient. Instead, try a template engine such as Handlebars.Net.
Here is an example that uses a different template and code but produces the same HTML:
var template = @"<head><title>{{name}}'s Profile</title></head>
<body>
<h1>{{name}}</h1>
<p><strong>Age:</strong> {{age}}</p>
<p><strong>Email:</strong> {{email}}</p>
<p><strong>Occupation:</strong> {{occupation}}</p>
</body></html>";
var compiledTemplate = Handlebars.Compile(template);
var completeHtml = compiledTemplate(person);
Handlebars.Net templates are logic-less. If that feels too restrictive, try Scriban. It provides conditionals, loops, expressions, function calls, and more.
Positional placeholders
These are very similar to named placeholders but use position numbers instead of names. You've seen
them in string.Format method calls.
var template = @"<head><title>{0}'s Profile</title></head>
<body>
<h1>{1}</h1>
<p><strong>Age:</strong> {2}</p>
<p><strong>Email:</strong> {3}</p>
<p><strong>Occupation:</strong> {4}</p>
</body></html>";
var completeHtml = string.Format(
template, person.Name, person.Name,
person.Age, person.Email, person.Occupation);
I suggest you don't use positional placeholders for anything except most simple cases. Here are a couple of reasons:
- When the template uses a value more than once, you must provide that value multiple times in the call.
- It's too easy to change the order in the template but forget to update the code.
Convert ASPX to PDF
Use Docotic.Pdf together with the free HtmlToPdf add-on to convert ASPX to PDF. The process is straightforward:
- Provide an implementation of the
Rendermethod that accumulates the produced HTML. - Let the ASP.NET engine generate the HTML for the ASPX page by executing server-side code and controls.
- Convert the accumulated HTML to PDF and return the PDF in the updated response.
Check out the sample code to see how to generate a PDF from an ASPX page in an ASP.NET Web Forms application. The sample application demonstrates the above process by creating an invoice in either HTML or PDF format. You can use the same approach to produce high-fidelity PDF versions of your reports, statements and other documents.
Convert SVG to PDF
SVG to vector PDF conversions are possible with the HtmlToPdf add-on for the Docotic.Pdf library.
You can use the HtmlConverter class as an SVG to PDF converter. The following C# code shows one
way to perform the conversion:
using var converter = await HtmlConverter.CreateAsync();
var uri = new Uri("https://bitmiracle.com/images/team.svg");
using var pdf = await converter.CreatePdfAsync(uri);
pdf.Save("output.pdf");
The result of the above code is a high-quality vector PDF. The converter provided by the HtmlToPdf add-on uses the width and height specified in the SVG to determine the aspect ratio. Depending on the SVG size, the converter may scale the SVG proportionally to fit the PDF page.
Options that affect output size
To produce a PDF of a different size, set the page size and/or margins. The converted SVG may still be scaled proportionally.
Another option is to specify SVG's width and/or height in the HTML code and convert that HTML. In the output, the image will have the specified size. If the size is larger than the PDF page, some parts of the image will not be visible.
using var converter = await HtmlConverter.CreateAsync();
var html = $"<img src='https://bitmiracle.com/images/team.svg' width='200' />";
using var pdf = await converter.CreatePdfFromStringAsync(html);
pdf.Save("output.pdf");
SVG file to PDF
To convert an SVG file to PDF, create a file Uri and pass it to the CreatePdfAsync method.
Another option is to create an HTML snippet with an img tag and use that snippet with the
CreatePdfFromStringAsync method. If you use relative paths in the HTML code, provide the base
URL through the conversion options.
To convert multiple SVG files to PDF, create an HTML snippet containing multiple img tags and use
it with the CreatePdfFromStringAsync method. If all the files are located in the same folder, I
recommend using relative paths in the HTML code and supplying the base URL.
Adding SVG to PDF
Start by converting the SVG to PDF using one of the HtmlConverter methods.
using var converter = await HtmlConverter.CreateAsync();
var uri = new Uri("https://bitmiracle.com/images/quote.svg");
using var svgPdf = await converter.CreatePdfAsync(uri);
You can then either overlay the contents of the produced PDF on top of another document, or merge the document with another PDF.
To overlay an SVG onto PDF, create an XObject from the first page of the converted document and draw that XObject on top of a PDF page in another document. Like this:
using var pdf = new PdfDocument("some-other.pdf");
var xObj = pdf.CreateXObject(svgPdf.Pages[0]);
pdf.Pages[0].Canvas.DrawXObject(xObj, 0, 0);
pdf.Save("output.pdf");
To merge an SVG into PDF, combine the converted PDF document with another PDF using one of the available merging approaches.
Convert WEBP to PDF
WebP is a web format, so you can convert it to PDF using Docotic.Pdf with the HtmlToPdf add-on. The following C# code demonstrates how to convert from WebP to PDF with high quality:
using var converter = await HtmlConverter.CreateAsync();
var html = $"<img src='https://bitmiracle.com/pdf-library/images/edit/reorder-pages.webp'/>";
using var pdf = await converter.CreatePdfFromStringAsync(html);
pdf.Save("output.pdf");
The code above does not specify width or height attributes for the img tag, but it is a good
idea to include them. Keep in mind that if the image size you specify is larger than the PDF page,
some parts of the image will not be visible.
Since WebP is a raster format, it won't scale up well. I recommend using images at the maximum size and resolution you expect to need.
To convert a WebP file to PDF, use the same code. If your HTML uses relative paths, provide the
base URL through the load options. Use a file
Uri as the base URL when converting local images.
Convert XML to PDF using XSLT
To convert XML to PDF, first transform the XML to HTML using an XSLT transformation. Then convert the resulting HTML to PDF using Docotic.Pdf with the HtmlToPdf add-on.
Here is the C# XML to PDF conversion code:
var transform = CreateTransform("invoice.xsl");
var html = TransformToHtml("invoice.xml", transform);
using var converter = await HtmlConverter.CreateAsync();
using var pdf = await converter.CreatePdfFromStringAsync(html);
pdf.Save("invoice.pdf");
The code:
- Creates an XSLT transformation object on the first line.
- Transforms the XML file into an HTML document on the second line.
- Converts the transformaton result (the HTML string) to PDF on the remaining lines.
Let's take a closer look at the first two points. The third point is fully covered in this section.
Create an XSLT transformation
The first step in the conversion process is to create an XSLT transformation object. The following code demonstrates how to create such an object:
public static XslCompiledTransform CreateTransform(string xsltFileName)
{
var transform = new XslCompiledTransform();
transform.Load(xsltFileName);
return transform;
}
As the name suggests, XslCompiledTransform compiles the provided stylesheet and produces IL code
from it. If your code needs to transform XML to PDF in bulk, reuse the same transformation object
for improved performance.
Transform XML to HTML
The second step is to generate HTML from the XML using the XSLT transformation object created in the previous step.
public static string TransformToHtml(string xmlFileName, XslCompiledTransform transform)
{
using var xmlReader = XmlReader.Create(xmlFileName);
using var sw = new StringWriter();
using var writer = XmlWriter.Create(sw, transform.OutputSettings);
transform.Transform(xmlReader, null, writer);
return sw.ToString();
}
The code uses XmlReader and XmlWriter because they are well‑suited for large XML files and help
keep memory usage low.
Sample code for XML to PDF conversion
Our samples repository includes C# and VB.NET versions of a sample application that converts an XML invoice into a PDF. The sample application contains an example XML invoice and the corresponding XSLT stylesheet.
When you navigate to a URL that returns XML in a modern browser, the browser can automatically apply the associated XSLT (if present) to generate and display readable HTML. This only works when both the XML and XSLT files are hosted on the same server. To prevent cross-origin requests, the browser will not load or apply the stylesheet when you open the XML file directly from the local file system.
Trade-offs and alternative ways to create PDF
The HTML to PDF API is not the only way to generate PDFs with Docotic.Pdf, and it's not always the most efficient. This section outlines the alternatives to help you choose the right option for your scenario.

When HTML to PDF is the right choice
Choose the HTML to PDF approach when your team already creates documents with HTML/CSS. Especially if your documents resemble web pages: invoices, purchase orders, certificates, receipts, and the like.
The HtmlToPdf add-on allows teams to reuse existing HTML/CSS templates and benefit from high-fidelity layout and rendering capabilities. Using the add-on, the path to high‑quality PDF output can be the fastest.
Limitations to keep in mind
The HTML to PDF API uses the Google Chrome HTML rendering engine. This engine is powerful, but it comes with overhead. A typical HTML to PDF conversion consumes more CPU and memory than drawing directly onto a PDF page canvas, for example. This overhead can slow down high‑volume batch generation.
The browser engine also increases the runtime footprint, which may be undesirable in minimal Docker images or constrained environments. For example, the API may not work in serverless environments with very strict limits on memory consumption and execution time.
Other ways to produce PDFs in Docotic.Pdf
The Docotic.Pdf library provides several other ways to generate documents, each suited to different needs:
-
Direct PDF generation via the Canvas API
Ideal for structured, predictable layouts such as tickets, labels, or forms. Offers maximum performance and full control over coordinates, typography, and content placement. -
Template‑based PDF generation
Often the best choice when working with approved, compliance‑controlled templates. You start from an existing PDF and fill fields, replace placeholders, and attach related documents as needed. -
PDF generation with the Layout API
Provides building blocks such as pages, containers, images, paragraphs of text, and other layout elements. You describe the PDF layout entirely in code using a fluent API, and the library generates the PDF from your layout. -
Composition from other PDFs and images
Offers a lightweight way to assemble statements, reports, document bundles, and other documents from existing PDFs and images. You convert images into PDF pages, combine multiple PDFs, append pages, or reuse fragments.
Comparison with other HTML to PDF solutions
To help you choose the right HTML‑to‑PDF library for .NET, here is information about how Docotic.Pdf with the HtmlToPdf add‑on compares to other popular solutions for converting HTML to PDF.
Key comparison takeaways
Most browser‑based solutions provide high‑quality rendering and fully support modern HTML, CSS, and JavaScript. However, there are important differences.
| Solution | When to use | Best for |
|---|---|---|
| Docotic.Pdf with the HtmlToPdf add-on | Converting reports, invoices, and receipts with pixel‑perfect visual fidelity | Professional‑grade software needing both HTML to PDF conversion and PDF editing, backed by professional support |
| Puppeteer | When modern HTML/CSS/JS rendering with browser‑level fidelity is required and only HTML‑to‑PDF output is needed | Pixel-perfect HTML to PDF generation with free or open‑source requirements |
| IronPDF | When your team has an Iron Suite license or prior experience with IronPDF | Teams relying on multiple Iron Software components |
| wkhtmltopdf | When a relatively lightweight footprint is required and your HTML/CSS is simple and free of external or untrusted references | Legacy compatibility with systems already using wkhtmltopdf |
Detailed comparison
Check the information in the table to get the full picture and draw your own conclusions.
| Docotic.Pdf with HtmlToPdf | Puppeteer | IronPDF | wkhtmltopdf | |
|---|---|---|---|---|
| Engine | Headless Chrome | Headless Chrome / Chromium | Headless Chrome | Legacy Qt WebKit |
| Rendering fidelity | Pixel-perfect | Pixel-perfect | Pixel-perfect | Pixel-perfect with quirks and limitations |
| HTML5 Support | Full | Full | Full | Partial and limited |
| CSS3 Support | Full | Full | Full | Extremely limited |
| JavaScript Support | Full | Full | Full | Partial and outdated |
| Integration with .NET code | Async .NET API | Async .NET API when using PuppeteerSharp; Node.js scripts otherwise. | Async .NET API | Command line process or C# wrapper library (such as DinkToPdf) |
| PDF features beyond HTML conversion | Extensive | None | Limited | None |
| Support | Commercial, priority support offered | Community, sponsor-based priority support offered for PuppeteerSharp | Commercial, priority support offered | Community with no formal support channels |
| Maintenance Status | Actively maintained | Actively maintained | Actively maintained | No longer maintained |
| License | Commercial, with free licenses for eligible use cases | Apache-2.0; MIT for PuppeteerSharp | Commercial | LGPL-3.0; MIT for DinkToPdf |
| Redistribution rights | Royalty‑free with all licenses | Royalty‑free with all licenses | Not included; requires a separate purchase | Royalty‑free with all licenses |
| Developer licensing | Unlimited developers with all licenses | Unlimited developers with all licenses | Varies by license tier; unlimited only in the highest‑tier license | Unlimited developers with all licenses |
| Online license verification | No online verification needed | No license verification performed | Required for all but the premium license | No license verification performed |
Conclusion
Docotic.Pdf with the HtmlToPdf add‑on provides reliable, high‑quality HTML to PDF conversions alongside a full‑featured PDF API. The library works well for generating PDF reports, invoices, receipts, and other business documents from HTML, preserving pixel‑perfect visual fidelity.
The add-on provides an async .NET API that runs completely on-premise. Your data never leaves your servers, giving you complete control over security and privacy.
Beyond HTML to PDF conversion, Docotic.Pdf can add password protection to the generated PDFs and sign them with digital signatures, including LTV-enabled signatures.
You can assemble final documents by merging multiple generated PDFs. If a PDF becomes too large after HTML conversion or merging, the library can remove duplicate objects inside the file and apply other methods to reduce the file size. To improve the reading experience, Docotic.Pdf can also optimize PDFs for Fast Web View (linearize the PDF).
Next steps:
- Review HTML to PDF code samples
- Explore the broader library API
- Contact us with questions or suggestions
Frequently Asked Questions
How to choose an HTML to PDF library for .NET?
Before selecting a library, define and collect your requirements. You will save time during evaluation if you know that a candidate library can not merge converted PDFs and this feature is required for your solution. See the comparison section for a side‑by‑side look at popular HTML to PDF libraries for .NET.
Why does my HTML not render correctly in PDF?
If your HTML looks correct in Google Chrome but not in the generated PDF, then check the conversion options. Make sure there is enough width to accommodate the content. The HTML might also require executing JavaScript before conversion.
Why use HTML templates instead of direct PDF APIs?
Using HTML templates makes your solution very flexible in the layout of documents. You can easily change the appearance of your PDFs using the powerful styling capabilities of HTML and CSS. Also, you don't need to duplicate the design of your online documents with a PDF API.
How to convert ASPX to PDF?
To convert ASPX to PDF, let the ASP.NET engine generate the HTML for the ASPX page, and then convert that HTML to PDF using the Docotic.Pdf library. More details are available in the corresponding section.
How to overlay an SVG onto a PDF?
To overlay an SVG onto a PDF, generate a PDF from the SVG, then create an XObject from the first page of the generated document. Because the XObject has a transparent background, you can place it on top of a PDF page in another document.
How to add a watermark to the generated PDF?
To add a watermark to a PDF document produced from HTML, create an XObject, fill it with the watermark content, and then draw the XObject on top of the document pages. You can use vector graphics, images, and text for the watermark.
Is Docotic.Pdf better than wkhtmltopdf?
Docotic.Pdf fully supports modern HTML, CSS, and JavaScript, whereas wkhtmltopdf often produces inconsistent rendering for modern web documents. In addition, Docotic.Pdf provides APIs beyond HTML to PDF conversion. For example, the library can sign PDFs with LTV-enabled digital signatures, while wkhtmltopdf can only convert HTML.