# How to Convert HTML to PDF in C# (Developer Guide)
This complete tutorial covers strings, URLs, files, deployment, and scaling. To get started, install IronPDF from NuGet and call `ChromePdfRenderer.RenderHtmlAsPdf()`. Three lines of code would be enough to produce a pixel-perfect PDF. IronPDF's Chrome-based engine handles the rendering, deployment, and scaling limits that trip up simpler tools. If you are still choosing a library, [compare all C# HTML to PDF libraries](/blog/compare-to-other-components/csharp-html-to-pdf-libraries-compared/) first.
*as-heading:2(TL;DR: Quickstart Guide to Convert HTML to PDF)*
You can easily convert HTML to PDF in C# using the [IronPDF](/) library, which provides the `ChromePdfRenderer.RenderHtmlAsPdf` method to create high-quality PDF files from HTML, CSS, and JavaScript.
```csharp
:title=Get started making PDFs now!
new IronPdf.ChromePdfRenderer()
.RenderHtmlAsPdf("<p>Hello World</p>")
.SaveAs("pixelperfect.pdf");
```
*All code in this guide was verified on IronPDF v2026.8.1 · .NET 10 · July 2026.*
*as-heading:2(Why Convert HTML to PDF?)*
Converting HTML to PDF lets your team build documents with the web stack it already knows, rather than learning a separate PDF layout API. A few reasons it works well:
- **Reuse the design language you already know:** Lay out documents in the HTML and CSS you write every day instead of a proprietary PDF drawing API.
- **Reuse existing web templates:** The templates already behind your web app become PDF sources, so developers write less bespoke PDF code.
- **Clean split of work:** Designers can own the look end-to-end while developers own rendering and wiring it into the application.
- **One pipeline, many document types:** The same approach covers invoices, reports, receipts, and archives without a separate tool for each.
*as-heading:2(Why NET Developers Need an HTML to PDF Converter for C#)*
IronPDF leverages an embedded Google Chromium rendering engine to ensure high-fidelity conversions, accurately preserving the layout and styling of your web content.
<ul>
<li>✅ <strong>Robust Chrome Rendering Engine:</strong> uses Chrome's <a href="https://www.chromium.org/blink/" target="_blank" rel="noopener">Blink engine</a> for accurate HTML to PDF conversion.</li>
<li>✅ <strong>Pixel-Perfect Accuracy:</strong> generated PDFs match the web precisely, not a printer-friendly version.</li>
<li>✅ <strong>Full Modern Web Support:</strong> complete CSS3, HTML5, and JavaScript support for all HTML elements.</li>
<li>✅ <strong>5-20x Performance Boost:</strong> significantly faster than browser automation or web drivers.</li>
<li>✅ <strong><a href="https://pdfa.org/" target="_blank" rel="noopener">PDF/UA</a> Compliance:</strong> accessible PDF generation that meets <a href="https://www.section508.gov/" target="_blank" rel="noopener">Section 508 standards</a>.</li>
<li>✅ <strong>No External Dependencies:</strong> no executables to install on servers.</li>
<li>✅ Designed for C#, F#, and VB.NET on <a href="https://learn.microsoft.com/en-us/dotnet/core/whats-new/dotnet-10/overview" target="_blank" rel="noopener">.NET 10</a>, <a href="https://learn.microsoft.com/en-us/dotnet/core/releases-and-support" target="_blank" rel="noopener">9, 8, 7, 6, Core, Standard, and Framework</a>.</li>
</ul>
[[i:(Latest in v2026.8.1 (June 2026): access to PDF Optional Content Groups (layers) with layer hierarchy and visibility metadata, a new CSS page-rule policy and header/footer overlap detection for cleaner margin handling, greater engine stability under heavy load and constrained-CPU environments, more accurate PDF redaction with corrected signature timestamps across daylight-saving changes, and clearer, actionable errors when PDF generation stalls. See the full changelog for the [complete release history](/product-updates/changelog/).)]]
IronPDF gives .NET developers a straightforward way to turn their web application's HTML into professional-looking PDFs. From invoices and reports to certificates and archives, developers can work with their familiar web stack while IronPDF handles the complex in just a few lines of code.
**RELATED:** <a class="content-anchor" href="/product-updates/changelog/">IronPDF Changelog: Updates, milestones, roadmap <i class="fa-solid fa-arrow-right"></i></a>
*as-heading:2(What You'll Learn)*
<ol class="space-y-5">
<li>
<div class="flex flex-wrap items-center gap-3">
<a href="#1-how-to-convert-html-to-pdf-c-num">How to Convert HTML to PDF C#</a>
<span class="inline-block rounded-md px-2.5 py-1 text-xs font-bold bg-[#E8F6F1] text-[#44806B]">Beginner</span>
</div>
<ul class="mt-2 mb-0 list-none space-y-1.5 pl-0 [&_i]:mr-1 [&_i]:text-[#678CB1]">
<li><i class="fa-regular fa-link"></i> <a href="#how-to-convert-html-string-to-pdf">How to Convert HTML String to PDF</a></li>
<li><i class="fa-regular fa-link"></i> <a href="#how-to-export-existing-url-to-pdf">How to Export Existing URL to PDF</a></li>
<li><i class="fa-regular fa-link"></i> <a href="#how-to-convert-html-file-to-pdf">How to Convert HTML File to PDF</a></li>
<li><i class="fa-regular fa-link"></i> <a href="#how-to-convert-razor-pages-to-pdf">How to Convert Razor Pages to PDF</a></li>
<li><i class="fa-regular fa-link"></i> <a href="#how-to-convert-mvc-views-to-pdf">How to Convert MVC Views to PDF</a></li>
</ul>
</li>
<li>
<div class="flex flex-wrap items-center gap-3">
<a href="#2-how-to-configure-html-to-pdf-settings">How to Configure HTML to PDF Settings</a>
<span class="inline-block rounded-md px-2.5 py-1 text-xs font-bold bg-[#E6E2F0] text-[#3B2A66]">Setup</span>
</div>
<ul class="mt-2 mb-0 list-none space-y-1.5 pl-0 [&_i]:mr-1 [&_i]:text-[#678CB1]">
<li><i class="fa-regular fa-link"></i> <a href="#how-to-set-custom-http-headers-cookies-and-login-credentials">How to Set Custom HTTP Headers, Cookies, and Login Credentials</a></li>
<li><i class="fa-regular fa-link"></i> <a href="#how-to-configure-proxy-for-pdf-rendering">How to Configure Proxy for PDF Rendering</a></li>
</ul>
</li>
<li>
<div class="flex flex-wrap items-center gap-3">
<a href="#3-how-to-use-advanced-pdf-generation-security-features">How to Use Advanced PDF Generation & Security Features</a>
<span class="inline-block rounded-md px-2.5 py-1 text-xs font-bold bg-[#FFF2DA] text-[#A66E0A]">Advanced</span>
</div>
<ul class="mt-2 mb-0 list-none space-y-1.5 pl-0 [&_i]:mr-1 [&_i]:text-[#678CB1]">
<li><i class="fa-regular fa-link"></i> <a href="#how-to-generate-html-template-for-batch-pdf-creation">How to Generate HTML Template for Batch PDF Creation</a></li>
<li><i class="fa-regular fa-link"></i> <a href="#how-to-generate-pdf-using-async-method">How to Generate PDF Using Async Method</a></li>
<li><i class="fa-regular fa-link"></i> <a href="#how-to-add-advanced-security-features">How to Add Advanced Security Features</a></li>
<li><i class="fa-regular fa-link"></i> <a href="#how-to-convert-html-forms-to-fillable-pdfs">How to Convert HTML Forms to Fillable PDFs</a></li>
<li><i class="fa-regular fa-link"></i> <a href="#how-to-convert-specific-html-elements-to-pdf">How to Convert Specific HTML Elements to PDF</a></li>
<li><i class="fa-regular fa-link"></i> <a href="#how-to-render-authenticated-pages-to-pdf">How to Render Authenticated Pages to PDF</a></li>
</ul>
</li>
<li>
<div class="flex flex-wrap items-center gap-3">
<a href="#4-how-to-deploy-html-to-pdf-on-cloud-platforms">How to Deploy HTML to PDF on Cloud Platforms</a>
<span class="inline-block rounded-md px-2.5 py-1 text-xs font-bold bg-[#DEEFFC] text-[#1D629B]">Deployment</span>
</div>
<ul class="mt-2 mb-0 list-none space-y-1.5 pl-0 [&_i]:mr-1 [&_i]:text-[#678CB1]">
<li><i class="fa-regular fa-link"></i> <a href="#how-to-deploy-on-azure">How to Deploy on Azure</a></li>
<li><i class="fa-regular fa-link"></i> <a href="#how-to-deploy-on-aws-lambda">How to Deploy on AWS Lambda</a></li>
<li><i class="fa-regular fa-link"></i> <a href="#how-to-deploy-with-docker">How to Deploy with Docker</a></li>
</ul>
</li>
<li>
<div class="flex flex-wrap items-center gap-3">
<a href="#5-compare-ironpdf-with-other-net-pdf-libraries">Compare IronPDF with Other .NET PDF Libraries</a>
<span class="inline-block rounded-md px-2.5 py-1 text-xs font-bold bg-[#F0E5EE] text-[#6B3567]">Compare</span>
</div>
<ul class="mt-2 mb-0 list-none space-y-1.5 pl-0 [&_i]:mr-1 [&_i]:text-[#678CB1]">
<li><i class="fa-regular fa-link"></i> <a href="#quick-decision-matrix-ironpdf-versus-other-net-pdf-converters">Quick Decision Matrix: IronPDF versus Other .NET PDF Converters</a></li>
<li><i class="fa-regular fa-link"></i> <a href="#detailed-comparison-ironpdf-versus-other-net-pdf-converters">Detailed Comparison: IronPDF versus Other .NET PDF Converters</a></li>
<li><i class="fa-regular fa-link"></i> <a href="#real-life-html-to-pdf-conversion-comparison-rendering-reddits-homepage">Real-life HTML to PDF Conversion Comparison: Rendering Reddit's Homepage</a></li>
<li><i class="fa-regular fa-link"></i> <a href="#conclusion-on-performance-and-output-pdf-quality">Conclusion on Performance and Output PDF Quality</a></li>
<li><i class="fa-regular fa-link"></i> <a href="#summary">Summary</a></li>
</ul>
</li>
<li>
<div class="flex flex-wrap items-center gap-3">
<a href="#6-troubleshooting--technical-support">Troubleshooting & Technical Support</a>
<span class="inline-block rounded-md px-2.5 py-1 text-xs font-bold bg-[#FFE1E2] text-[#A8181D]">Help</span>
</div>
<ul class="mt-2 mb-0 list-none space-y-1.5 pl-0 [&_i]:mr-1 [&_i]:text-[#678CB1]">
<li><i class="fa-regular fa-link"></i> <a href="#quick-fixes-on-common-errors">Quick Fixes on Common Errors</a></li>
<li><i class="fa-regular fa-link"></i> <a href="#get-help-from-the-engineers-who-built-ironpdf-247">Get Help From The Engineers Who Built IronPDF, 24/7</a></li>
</ul>
</li>
</ol>
*as-heading:2(Choose Your HTML to PDF Path by Use Case)*
Not sure where to start? Jump straight to the path that matches what you're building:
<div class="my-6 max-w-full overflow-x-auto">
<table class="w-full border-separate border-spacing-0 overflow-clip rounded-lg border border-[#D9E5E9] [&_th]:border [&_th]:border-[#D9E5E9] [&_th]:px-3 [&_th]:py-4 [&_th]:text-center [&_th]:text-sm [&_th]:font-medium [&_td]:border [&_td]:border-[#D9E5E9] [&_td]:px-3 [&_td]:py-4 [&_td]:align-top [&_td]:text-[13.5px]/[1.5] [&_td]:text-[#181818] [&_td_ul]:m-0 [&_td_ul]:list-none [&_td_ul]:p-0 [&_td_ul>li+li]:mt-2">
<thead>
<tr>
<th><strong>What you're building</strong></th>
<th><strong>Start here</strong></th>
</tr>
</thead>
<tbody>
<tr>
<td><span>Converting a one-off HTML string</span></td>
<td><a class="content-anchor" href="#how-to-convert-html-string-to-pdf">HTML String to PDF <i class="fa-solid fa-arrow-right"></i></a></td>
</tr>
<tr>
<td><span>Archiving a live URL or web page</span></td>
<td><a class="content-anchor" href="#how-to-export-existing-url-to-pdf">URL to PDF <i class="fa-solid fa-arrow-right"></i></a></td>
</tr>
<tr>
<td><span>Building a Razor Pages or MVC app</span></td>
<td><a class="content-anchor" href="#how-to-convert-razor-pages-to-pdf">Razor / MVC to PDF <i class="fa-solid fa-arrow-right"></i></a></td>
</tr>
<tr>
<td><span>Batch or high-volume server-side generation</span></td>
<td><a class="content-anchor" href="#how-to-generate-pdf-using-async-method">Async & batch generation <i class="fa-solid fa-arrow-right"></i></a></td>
</tr>
<tr>
<td><span>Needing a code-first layout engine (no HTML) or a zero-budget open-source route</span></td>
<td><a class="content-anchor" href="#free-and-open-source-alternatives">Free & Open-Source Alternatives <i class="fa-solid fa-arrow-right"></i></a></td>
</tr>
</tbody>
</table>
</div>
## 1. How to Convert HTML to PDF C#
Whether you're working with HTML strings, URLs, or HTML files, IronPDF gives you flexible options for producing high-quality PDFs.
In this tutorial, we will walk you through the most common scenarios, including HTML string to PDF, URL to PDF, and HTML file to PDF. Additionally, IronPDF also provides a variety of operations for manipulating PDF documents:
### How to Convert HTML String to PDF
The most fundamental operation is HTML string to PDF. This method is perfect for dynamically generated HTML content. The `RenderHtmlAsPdf` method fully supports HTML5, CSS3, JavaScript, and images.
```csharp
using IronPdf;
// Create the Chrome renderer
var renderer = new ChromePdfRenderer();
// Convert HTML string to PDF
var pdf = renderer.RenderHtmlAsPdf("<h1>Hello IronPdf</h1>");
// Save the PDF
pdf.SaveAs("output.pdf");
```
#### Output
Run the snippet above and IronPDF returns a one-page PDF holding exactly the heading you passed in, the simplest possible render:
<iframe loading="lazy" title="HTML string to PDF output" src="/static-assets/pdf/tutorials/html-to-pdf/output.pdf#view=fit" width="100%" height="600px" style="border: 1px solid #D9E5E9; border-radius: 8px;">
</iframe>
#### Performance
The performance of IronPDF's conversion to PDF from string, URL, and HTML was measured using a Lenovo laptop with 16GB RAM. The test document is a 3-page enterprise invoice with standard CSS Grid, gradients and multi-section tables.
The results are as follows:
| Metric | Value |
|---|---|
| Average render time | ~486 ms |
| Memory per render | ~3.6 MB |
*Measured across 5 successive renders on an 8-core / 16-thread laptop (Windows 11, .NET 8). The first call also includes one-time Chromium engine initialization (~1.3 s)*
The first time I ran the test, render time was sluggish (Over a second per call!). After looking at what was happening, I realized I had several open Chromium instances running and was on battery power, neither of which let the library show its real speed. Once I closed the competing processes and plugged in, things sharpened up: warm runs averaged ~486 ms with the fastest landing near 473 ms.
[[t:(Recent updates fix issues with special characters/emojis in HTML metadata and ensure better handling of html form fields, including Chinese characters on Linux. Test dynamic content with <span style="color: red;">`EnableJavaScript = true`</span> for optimal results.)]]
When your HTML string references local assets like images or stylesheets, use the `baseUrlOrPath` parameter to properly convert HTML content with all resources:
```csharp
:path=/static-assets/pdf/content-code-examples/tutorials/html-to-pdf-2.cs
```
[[t:(baseUrlOrPath tells IronPDF where to find your CSS, JavaScript, and image files. All relative paths in your HTML string will be resolved from this directory.)]]
[[w:(One issue to keep an eye out for, and why testing the output is important regardless of what library you use for automated document generation, is that the enterprise document may have broken elements or missing assets when references default back to system settings. IronPDF gives you the `baseUrlOrPath` parameter to point relative paths at the right directory, so a quick output check before bulk runs is usually all you need to catch it.)]]
**RELATED HOW-TO ARTICLE:** <a class="content-anchor" href="/how-to/html-string-to-pdf/">How to Convert HTML String to PDF in C# <i class="fa-solid fa-arrow-right"></i></a>
### How to Export Existing URL to PDF
Rendering entire web pages to PDFs with C# enables teams to separate PDF design and back-end rendering work. This approach lets you convert any specified URL directly to PDF format.
The core method is `RenderUrlAsPdf`, which fetches a live page and renders it in a single call:
```csharp
using IronPdf;
// Create a PDF from any existing web page
var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderUrlAsPdf("https://en.wikipedia.org/wiki/PDF");
pdf.SaveAs("wikipedia.pdf");
```
#### Output
Here `RenderUrlAsPdf` captures a live Wikipedia article into a static, print-ready PDF, with text, images, tables, and layout preserved across all 33 pages:
<iframe loading="lazy" title="URL (Wikipedia) to PDF output" src="/static-assets/pdf/tutorials/html-to-pdf/wikipedia.pdf#view=fit" width="100%" height="600px" style="border: 1px solid #D9E5E9; border-radius: 8px;">
</iframe>
**Print vs Screen CSS**
You can configure IronPDF to render using either CSS media type.
```csharp
:path=/static-assets/pdf/content-code-examples/tutorials/html-to-pdf-4.cs
```
**JavaScript Support**
IronPDF fully supports JavaScript, jQuery, and even AJAX. For dynamic content, you can configure IronPDF to wait for JavaScript to finish before rendering. This is perfect for single-page applications and dynamic websites.
```csharp
:path=/static-assets/pdf/content-code-examples/tutorials/html-to-pdf-5.cs
```
JavaScript execution can also be shown when rendering an advanced d3.js chord chart from a web page to PDF format:
```csharp
:path=/static-assets/pdf/content-code-examples/tutorials/html-to-pdf-6.cs
```
**Responsive CSS**
As responsive web pages are designed to be viewed in a browser, and IronPDF does not open a real browser window in your server's OS, responsive HTML elements may render at their smallest size. `PdfCssMediaType.Print` is recommended to navigate this issue when rendering entire web pages.
```csharp
:path=/static-assets/pdf/content-code-examples/tutorials/html-to-pdf-7.cs
```
**RELATED HOW-TO ARTICLE:** <a class="content-anchor" href="/how-to/url-to-pdf/">How to Render URL to PDF <i class="fa-solid fa-arrow-right"></i></a>
### How to Convert HTML File to PDF
Converting local HTML files to PDF preserves all relative assets including CSS, images, and JavaScript, as if opened using the file:// protocol. This method is best for converting templates or pre-designed HTML pages.
```csharp
:path=/static-assets/pdf/content-code-examples/tutorials/html-to-pdf-8.cs
```
#### Output
Point `RenderHtmlFileAsPdf` at an HTML invoice template and the file's full design (logo, line-item table, totals) comes through pixel-perfect, with no extra code on your side:
<iframe loading="lazy" title="HTML file (invoice) to PDF output" src="/static-assets/pdf/tutorials/html-to-pdf/Invoice.pdf#view=fit" width="100%" height="600px" style="border: 1px solid #D9E5E9; border-radius: 8px;">
</iframe>
#### Performance
Performance was measured again by keeping all variables constant to render the previous 3-page enterprise invoice from a file on disk:
| Metric | Value |
|---|---|
| Average render time | ~502 ms |
| Memory per render | ~3.1 MB |
*Measured across 5 successive renders on the same 8-core / 16-thread laptop (Windows 11, .NET 8). File-based rendering matches in-memory string rendering within about 3%; reading the HTML from disk adds no measurable overhead.*
[[t:(Keep your HTML files in a separate folder with their assets (CSS, images) to edit and test in a browser before converting HTML file to PDF. This ensures your HTML renders perfectly for high quality PDF documents.)]]
**RELATED HOW-TO Article:** <a class="content-anchor" href="/how-to/html-file-to-pdf/">Render HTML File to PDF <i class="fa-solid fa-arrow-right"></i></a>
### How to Convert Razor Pages to PDF
If your ASP.NET Core project already uses Razor Pages, you can convert them directly to PDF without rebuilding your HTML. IronPDF's Razor extension adds the `RenderRazorToPdf` method, which takes your .cshtml page (complete with its model and layout) and renders it as a PDF document in a single call.
```shell
:InstallCmd Install-Package IronPdf.Extensions.Razor
```
```csharp
using IronPdf;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
public class ReportModel : PageModel
{
public IActionResult OnGet()
{
var renderer = new ChromePdfRenderer();
// Render a Razor Page directly to PDF
PdfDocument pdf = renderer.RenderRazorToPdf(this);
Response.Headers.Add("Content-Disposition", "inline");
return new FileContentResult(pdf.BinaryData, "application/pdf");
}
}
```
[[i:(RenderRazorToPdf requires an ASP.NET Core Web App project. It will not work in console applications or class libraries; the Razor view engine must be available in the hosting pipeline.)]]
**RELATED HOW-TO Article:** <a class="content-anchor" href="/how-to/cshtml-to-pdf-razor/">How to Convert CSHTML to PDF in Razor Pages <i class="fa-solid fa-arrow-right"></i></a>
### How to Convert MVC Views to PDF
Teams using the MVC pattern can generate PDFs straight from their existing Views and controllers. Install the MVC Core extension package, then call `RenderRazorViewToPdf` with your view path and model; IronPDF handles the Razor rendering pipeline and outputs a finished PDF.
This is especially useful for reports, invoices, and any page where the HTML is already designed and tested in the browser. The generated PDF preserves the full View output, including layout pages and partial views.
```shell
:InstallCmd Install-Package IronPdf.Extensions.Mvc.Core
```
First, register the `IRazorViewRenderer` service in your Program.cs so your controllers can inject it:
```csharp
using IronPdf.Extensions.Mvc.Core;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllersWithViews();
// Register the Razor view renderer for IronPDF
builder.Services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
builder.Services.AddSingleton<IRazorViewRenderer, RazorViewRenderer>();
```
Then in your controller action, inject the renderer and convert any View to PDF:
```csharp
using IronPdf;
using IronPdf.Extensions.Mvc.Core;
using Microsoft.AspNetCore.Mvc;
public class ReportController : Controller
{
private readonly IRazorViewRenderer _viewRenderService;
// Inject the view renderer via constructor
public ReportController(IRazorViewRenderer viewRenderService)
{
_viewRenderService = viewRenderService;
}
public IActionResult Download()
{
var reportModel = new { Title = "Quarterly Report", Total = 1250.00 };
var renderer = new ChromePdfRenderer();
// Render an MVC View with model data to PDF
PdfDocument pdf = renderer.RenderRazorViewToPdf(
_viewRenderService, "Views/Home/Report.cshtml", reportModel);
Response.Headers.Add("Content-Disposition", "inline");
return new FileContentResult(pdf.BinaryData, "application/pdf");
}
}
```
**RELATED HOW-TO Article:** <a class="content-anchor" href="/how-to/cshtml-to-pdf-mvc-core/">How to Convert Views to PDF in ASP.NET Core MVC <i class="fa-solid fa-arrow-right"></i></a>
### Dynamic Web Page to PDFs
Do you need your dynamic web page preserved and converted to PDFs while preserving the exact layout and formatting? Look no further than IronPDF, which quickly converts a variety of popular dynamic web page frameworks to PDFs.
#### PDF from ASPX Pages
Here's a brief code snippet on converting ASPX Pages as PDF in Active Server Pages.
```cs
:path=/static-assets/pdf/content-code-examples/how-to/aspx-to-pdf-2.cs
```
For a more detailed explanation of this code snippet and to explore its additional functionality, please refer to our comprehensive [how-to guide](https://ironpdf.com/how-to/aspx-to-pdf/).
#### XAML to PDF (MAUI)
For developers looking to build cross-platform applications, .NET MAUI is a popular choice among the frameworks. IronPDF fully supports converting XAML to PDF with a few steps.
```cs
:path=/static-assets/pdf/content-code-examples/how-to/xaml-to-pdf-maui-mainpage-xaml-cs.cs
```
For a more detailed explanation of this code snippet and to explore its additional functionality, please refer to our comprehensive [how-to guide](https://ironpdf.com/how-to/xaml-to-pdf-maui/).
#### Generate PDF Reports
When it comes to generating PDF Reports, the exact dimensions and format are crucial. As such, IronPDF allows you to generate PDFs seamlessly with only a couple of steps.
```cs
:path=/static-assets/pdf/content-code-examples/how-to/csharp-pdf-reports-render-html-file.cs
```
For a more detailed explanation of this code snippet and to explore its additional functionality, please refer to our comprehensive [how-to guide](https://ironpdf.com/how-to/csharp-pdf-reports/).
#### Create PDFs in Blazor Servers
IronPDF supports .NET 6, and as it includes project types like Blazor, this code snippet provides a brief example of how to create PDFs in Blazor Server.
```csharp
@code {
// Model to bind user input
private InputHTMLModel _InputMsgModel = new InputHTMLModel();
private async Task SubmitHTML()
{
// Set your IronPDF license key
IronPdf.License.LicenseKey = "IRONPDF-MYLICENSE-KEY-1EF01";
// Create a renderer to convert HTML to PDF
var render = new IronPdf.ChromePdfRenderer();
// Render the HTML input into a PDF document
var doc = render.RenderHtmlAsPdf(_InputMsgModel.HTML);
var fileName = "iron.pdf";
// Create a stream reference for the PDF content
using var streamRef = new DotNetStreamReference(stream: doc.Stream);
// Invoke JavaScript function to download the PDF in the browser
await JS.InvokeVoidAsync("SubmitHTML", fileName, streamRef);
}
public class InputHTMLModel
{
public string HTML { get; set; } = "My new message";
}
}
```
For a more detailed explanation of this code snippet and to explore its additional functionality, please refer to our comprehensive [how-to guide](https://ironpdf.com/how-to/blazor-tutorial/).
#### Razor to PDF (Blazor Servers)
Aside from creating PDFs in Blazor Servers, IronPDF also supports generating PDF documents from Razor components within a Blazor page. Making the creation of PDF files and pages much more streamlined.
```csharp
[Parameter]
public IEnumerable<PersonInfo> persons { get; set; }
public Dictionary<string, object> Parameters { get; set; } = new Dictionary<string, object>();
protected override async Task OnInitializedAsync()
{
persons = new List<PersonInfo>
{
new PersonInfo { Name = "Alice", Title = "Mrs.", Description = "Software Engineer" },
new PersonInfo { Name = "Bob", Title = "Mr.", Description = "Software Engineer" },
new PersonInfo { Name = "Charlie", Title = "Mr.", Description = "Software Engineer" }
};
}
private async void PrintToPdf()
{
ChromePdfRenderer renderer = new ChromePdfRenderer();
// Apply text footer
renderer.RenderingOptions.TextFooter = new TextHeaderFooter()
{
LeftText = "{date} - {time}",
DrawDividerLine = true,
RightText = "Page {page} of {total-pages}",
Font = IronSoftware.Drawing.FontTypes.Arial,
FontSize = 11
};
Parameters.Add("persons", persons);
// Render razor component to PDF
PdfDocument pdf = renderer.RenderRazorComponentToPdf<Person>(Parameters);
File.WriteAllBytes("razorComponentToPdf.pdf", pdf.BinaryData);
}
```
For a more detailed explanation of this code snippet and to explore its additional functionality, please refer to our comprehensive [how-to guide](https://ironpdf.com/how-to/razor-to-pdf-blazor-server/).
#### CSHTML to PDF
Converting CSHTML (Razor) to PDF allows you to generate professional, print-ready documents directly from your web applications. This is useful for invoices, reports, contracts, or any dynamic content. IronPDF supports Razor Pages, MVC Core, and MVC Framework, as well as headless rendering, making it seamless to integrate PDF generation into your .NET applications with just a few lines of code.
##### CSHTML to PDF (Razor Pages)
```csharp
using IronPdf.Razor.Pages;
public IActionResult OnPostAsync()
{
persons = new List<Person>
{
new Person { Name = "Alice", Title = "Mrs.", Description = "Software Engineer" },
new Person { Name = "Bob", Title = "Mr.", Description = "Software Engineer" },
new Person { Name = "Charlie", Title = "Mr.", Description = "Software Engineer" }
};
ViewData["personList"] = persons;
ChromePdfRenderer renderer = new ChromePdfRenderer();
// Render Razor Page to PDF document
PdfDocument pdf = renderer.RenderRazorToPdf(this);
Response.Headers.Add("Content-Disposition", "inline");
return File(pdf.BinaryData, "application/pdf", "razorPageToPdf.pdf");
}
```
For a more detailed explanation of this code snippet and to explore its additional functionality, please refer to our comprehensive [how-to guide](https://ironpdf.com/how-to/cshtml-to-pdf-razor/).
##### CSHTML to PDF (MVC Core)
```csharp
public async Task<IActionResult> Persons()
{
var persons = new List<Person>
{
new Person { Name = "Alice", Title = "Mrs.", Description = "Software Engineer" },
new Person { Name = "Bob", Title = "Mr.", Description = "Software Engineer" },
new Person { Name = "Charlie", Title = "Mr.", Description = "Software Engineer" }
};
if (_httpContextAccessor.HttpContext.Request.Method == HttpMethod.Post.Method)
{
ChromePdfRenderer renderer = new ChromePdfRenderer();
// Render View to PDF document
PdfDocument pdf = renderer.RenderRazorViewToPdf(_viewRenderService, "Views/Home/Persons.cshtml", persons);
Response.Headers.Add("Content-Disposition", "inline");
// Output PDF document
return File(pdf.BinaryData, "application/pdf", "viewToPdfMVCCore.pdf");
}
return View(persons);
}
```
For a more detailed explanation of this code snippet and to explore its additional functionality, please refer to our comprehensive [how-to guide](https://ironpdf.com/how-to/cshtml-to-pdf-mvc-core/).
##### CSHTML to PDF (MVC Framework)
```csharp
public ActionResult Persons()
{
var persons = new List<Person>
{
new Person { Name = "Alice", Title = "Mrs.", Description = "Software Engineer" },
new Person { Name = "Bob", Title = "Mr.", Description = "Software Engineer" },
new Person { Name = "Charlie", Title = "Mr.", Description = "Software Engineer" }
};
if (HttpContext.Request.HttpMethod == "POST")
{
// Provide the path to your view file
var viewPath = "~/Views/Home/Persons.cshtml";
ChromePdfRenderer renderer = new ChromePdfRenderer();
// Render Razor view to PDF document
PdfDocument pdf = renderer.RenderView(this.HttpContext, viewPath, persons);
Response.Headers.Add("Content-Disposition", "inline");
// View the PDF
return File(pdf.BinaryData, "application/pdf");
}
return View(persons);
}
```
For a more detailed explanation of this code snippet and to explore its additional functionality, please refer to our comprehensive [how-to guide](https://ironpdf.com/how-to/cshtml-to-pdf-mvc-framework/).
##### CSHTML to PDF (Headlessly)
```csharp
:path=/static-assets/pdf/content-code-examples/tutorials/convert-pdf-20.cs
```
For a more detailed explanation of this code snippet and to explore its additional functionality, please refer to our comprehensive [how-to guide](https://ironpdf.com/how-to/cshtml-to-pdf-razor-headlessly/).
## 2. How to Configure HTML to PDF Settings
IronPDF provides extensive customizations through the `ChromePdfRenderer.RenderingOptions` property.
<div class="my-6 max-w-full overflow-x-auto">
<table class="w-full border-separate border-spacing-0 overflow-clip rounded-lg border border-[#D9E5E9] [&_th]:border [&_th]:border-[#D9E5E9] [&_th]:px-3 [&_th]:py-4 [&_th]:text-center [&_th]:text-sm [&_th]:font-medium [&_td]:border [&_td]:border-[#D9E5E9] [&_td]:px-3 [&_td]:py-4 [&_td]:align-top [&_td]:text-[13.5px]/[1.5] [&_td]:text-[#181818] [&_td_ul]:m-0 [&_td_ul]:list-none [&_td_ul]:p-0 [&_td_ul>li+li]:mt-2">
<thead>
<tr>
<th><strong>Settings</strong></th>
<th><strong>Description</strong></th>
<th><strong>Example</strong></th>
</tr>
</thead>
<tbody>
<tr>
<td>
<span><code>PaperSize</code></span>
</td>
<td>
<span>Set page dimensions for existing PDFs (A4, Letter, Legal, etc.)</span>
</td>
<td>
<span><code>PdfPaperSize.A4</code></span>
</td>
</tr>
<tr>
<td>
<span><code>PaperOrientation</code></span>
</td>
<td>
<span>Set Portrait or Landscape for existing PDFs</span>
</td>
<td>
<span><code>PdfPaperOrientation.Landscape</code></span>
</td>
</tr>
<tr>
<td>
<span><code>MarginTop</code>/<code>Bottom</code>/<code>Left</code>/<code>Right</code></span>
</td>
<td>
<span>Set page margins in millimeters (default: 25mm)</span>
</td>
<td>
<span>25</span>
</td>
</tr>
<tr>
<td>
<span><code>CssMediaType</code></span>
</td>
<td>
<span>Screen or Print CSS for HTML to PDF</span>
</td>
<td>
<span><code>PdfCssMediaType.Print</code></span>
</td>
</tr>
<tr>
<td>
<span><code>PrintHtmlBackgrounds</code></span>
</td>
<td>
<span>Include background colors/images (default: true)</span>
</td>
<td>
<span>true</span>
</td>
</tr>
<tr>
<td>
<span><code>EnableJavaScript</code></span>
</td>
<td>
<span>Execute JavaScript before rendering HTML content</span>
</td>
<td>
<span>true</span>
</td>
</tr>
<tr>
<td>
<span><code>WaitFor.RenderDelay</code></span>
</td>
<td>
<span>Wait time for dynamic HTML content (ms)</span>
</td>
<td>
<span>500</span>
</td>
</tr>
</tbody>
</table>
</div>
See this code snippet for a complete configuration example for manipulating PDF documents:
```csharp
using IronPdf;
using IronPdf.Rendering;
var renderer = new ChromePdfRenderer();
// Apply print-specific CSS rules
renderer.RenderingOptions.CssMediaType = PdfCssMediaType.Print;
// Set custom margins in millimeters
renderer.RenderingOptions.MarginTop = 50;
renderer.RenderingOptions.MarginBottom = 50;
// Enable background colors and images
renderer.RenderingOptions.PrintHtmlBackgrounds = true;
// Set paper size and orientation
renderer.RenderingOptions.PaperSize = PdfPaperSize.A4;
renderer.RenderingOptions.PaperOrientation = PdfPaperOrientation.Landscape;
// Generate PDFs with all settings applied to HTML content
var htmlContent = "<div style='background-color: #f0f0f0; padding: 20px;'><h1>Styled Content</h1></div>";
var pdfDocument = renderer.RenderHtmlAsPdf(htmlContent);
pdfDocument.SaveAs("styled-output.pdf");
```
[[t:(Use PdfCssMediaType for cleaner, print-optimized layouts in your rendered PDF file format. Use Screen to match exactly what users see in their browser.)]]
**RELATED HOW-TO ARTICLES:**
<div class="my-6 max-w-full overflow-x-auto">
<table class="w-full border-separate border-spacing-0 overflow-clip rounded-lg border border-[#D9E5E9] [&_th]:border [&_th]:border-[#D9E5E9] [&_th]:px-3 [&_th]:py-4 [&_th]:text-center [&_th]:text-sm [&_th]:font-medium [&_td]:border [&_td]:border-[#D9E5E9] [&_td]:px-3 [&_td]:py-4 [&_td]:align-top [&_td]:text-[13.5px]/[1.5] [&_td]:text-[#181818] [&_td_ul]:m-0 [&_td_ul]:list-none [&_td_ul]:p-0 [&_td_ul>li+li]:mt-2">
<thead>
<tr>
<th>Tailor PDF Conversion</th>
<th>Refine PDF Layout</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<ul>
<li><a class="content-anchor" href="/how-to/rendering-options/">Explore All PDF Rendering Methods <i class="fa-solid fa-arrow-right"></i></a></li>
<li><a class="content-anchor" href="/how-to/custom-margins/">How to Set Custom Margins <i class="fa-solid fa-arrow-right"></i></a></li>
<li><a class="content-anchor" href="/how-to/color-grayscale/">How to Generate Grayscale <i class="fa-solid fa-arrow-right"></i></a></li>
</ul>
</td>
<td>
<ul>
<li><a class="content-anchor" href="/how-to/table-of-contents/">How to Add a Table of Contents <i class="fa-solid fa-arrow-right"></i></a></li>
<li><a class="content-anchor" href="/how-to/html-to-pdf-page-breaks/">How to Add or Avoid Page Breaks <i class="fa-solid fa-arrow-right"></i></a></li>
<li><a class="content-anchor" href="/how-to/viewport-zoom/">How to Fit to Paper & Zoom <i class="fa-solid fa-arrow-right"></i></a></li>
</ul>
</td>
</tr>
</tbody>
</table>
</div>
Rendering pages that require authentication? See [How to Render Authenticated Pages to PDF](#how-to-render-authenticated-pages-to-pdf) for setting HTTP headers, cookies, and login credentials with runnable examples.
### How to Configure Proxy for PDF Rendering
When rendering HTML that loads external resources behind a corporate proxy, pass the proxy address as the third parameter on `RenderHtmlAsPdf()`. This is a method parameter, not a property on `ChromePdfRenderOptions`, so it's set per render call, not on the renderer instance.
For authenticated proxies, embed credentials directly in the URL using `http://user:pass@host:port` format. URL-encode special characters in passwords with `Uri.EscapeDataString()`.
```csharp
using IronPdf;
var renderer = new ChromePdfRenderer();
// Proxy is the third parameter, not a render option
var pdf = renderer.RenderHtmlAsPdf(
"<h1>Report</h1><link rel='stylesheet' href='https://cdn.example.com/styles.css'>",
baseUrlOrPath: null,
proxy: "http://proxy.corp.local:8080"
);
pdf.SaveAs("proxied-report.pdf");
```
Note that `RenderUrlAsPdf()` does not accept a proxy parameter. To render a live URL behind a proxy, fetch the HTML first with `HttpClient` configured with a `WebProxy`, then pass it to `RenderHtmlAsPdf()` with the proxy parameter for asset loading.
**RELATED HOW-TO Article:** <a class="content-anchor" href="/how-to/proxy/">How to Configure Proxy Servers for PDF Rendering <i class="fa-solid fa-arrow-right"></i></a>
## 3. How to Use Advanced PDF Generation & Security Features
Unlock enterprise-level capabilities for HTML to PDF conversion with advanced templating, async operations, and security features. These methods let you generate documents at scale, protect sensitive files, and ensure document authenticity.
### How to Generate HTML Template for Batch PDF Creation
**Basic Batch PDF Creation**
Batch PDF creation is essential for generating multiple personalized PDF documents efficiently. For basic scenarios, the `String.Format` method in C# works best for simple PDF manipulation.
```csharp
// Simple HTML templating with String.Format
string htmlTemplate = String.Format("<h1>Hello {0}!</h1>", "World");
// Results in HTML content: <h1>Hello World!</h1>
```
For longer templates, use placeholder replacement in your HTML content:
```csharp
:path=/static-assets/pdf/content-code-examples/tutorials/html-to-pdf-16.cs
```
**HTML to PDF Templating with Handlebars.NET**
For complex templates with loops and conditionals, use `Handlebars.NET` to render dynamic HTML content.
```shell
# First, install Handlebars.NET for HTML to PDF templating
PM > Install-Package Handlebars.NET
```
```csharp
:path=/static-assets/pdf/content-code-examples/tutorials/html-to-pdf-21.cs
```
**RELATED HOW-TO Article:** <a class="content-anchor" href="https://github.com/rexm/Handlebars.NET">Learn more about Handlebars.NET on GitHub <i class="fa-solid fa-arrow-right"></i></a>
<div>
<h4 style="color: #181818;">Control PDF Page Breaks:</h4> Managing pagination in generated PDF documents ensures professional, readable layouts when you convert HTML snippets. Use CSS to control where pages break in your PDF files.
</div>
```html
<!DOCTYPE html>
<html>
<head>
<style type="text/css" media="print">
.page {
page-break-after: always;
page-break-inside: avoid;
}
</style>
</head>
<body>
<div class="page">
<h1>Page 1 Content</h1>
</div>
<div class="page">
<h1>Page 2 Content</h1>
</div>
<div class="page">
<h1>Page 3 Content</h1>
</div>
</body>
</html>
```
### How to Generate PDF Using Async Method
IronPDF delivers enterprise-grade performance with full <a href="https://learn.microsoft.com/en-us/dotnet/standard/parallel-programming/task-based-asynchronous-programming" target="_blank" rel="noopener">async and multithreading</a> support for your HTML to PDF conversion requirements when you need to generate PDF files at scale.
```csharp
using IronPdf;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
public class PdfGenerationService
{
// Async method for non-blocking PDF generation from HTML content
public async Task<byte[]> GeneratePdfAsync(string html)
{
var renderer = new ChromePdfRenderer();
// Async HTML to PDF conversion preserves thread pool
var pdf = await renderer.RenderHtmlAsPdfAsync(html);
// Return PDF files as byte array for web responses
return pdf.BinaryData;
}
// Concurrent batch PDF generation for multiple HTML strings
public async Task GenerateMultiplePdfsAsync(List<string> htmlTemplates)
{
var renderer = new ChromePdfRenderer();
// Create parallel conversion tasks to generate PDF documents
var tasks = htmlTemplates.Select(html =>
renderer.RenderHtmlAsPdfAsync(html)
);
// Await all PDF conversions simultaneously
var pdfs = await Task.WhenAll(tasks);
// Save generated PDF files from HTML content
for (int i = 0; i < pdfs.Length; i++)
{
pdfs[i].SaveAs($"document-{i}.pdf");
}
}
}
```
[[t:(Performance optimization tips for HTML to PDF conversion)]]
- Use 64-bit systems for optimal PDF generation performance.
- Ensure adequate server resources when you generate PDF documents (avoid underpowered free tiers)
- Allow sufficient RenderDelay for complex JavaScript in HTML content.
- Reuse `ChromePdfRenderer` instances when possible.
- Leverage recent memory fixes for batch/async ops to reduce resource usage; test for reduced file sizes with repeated custom headers/footers.
**RELATED HOW-TO Article:** <a class="content-anchor" href="/how-to/async/">How to Generate PDFs with Async and Multithreading <i class="fa-solid fa-arrow-right"></i></a>
### How to Add Advanced Security Features
**How to Add Password Protect for PDF Files in .NET**
Secure sensitive PDF documents with passwords and permissions.
```csharp
:path=/static-assets/pdf/content-code-examples/tutorials/html-to-pdf-24.cs
```
**How to Add Digital Signatures to PDF Files**
Add cryptographic signatures to ensure PDF document authenticity. Once signed, you can [verify the signature and read the signer's certificate](/how-to/verify-pdf-signatures/) for audit and compliance checks.
```csharp
:path=/static-assets/pdf/content-code-examples/tutorials/html-to-pdf-25.cs
```
**RELATED HOW-TO Article:** <a class="content-anchor" href="/how-to/signing/">Digitally Signing PDF Documents with C# <i class="fa-solid fa-arrow-right"></i></a>
### How to Convert HTML Forms to Fillable PDFs
To convert standard HTML form elements into interactive, fillable PDF form fields, enable the `CreatePdfFormsFromHtml` rendering option. This preserves text inputs, checkboxes, radio buttons, and dropdown menus as editable fields in the generated PDF document.
```csharp
:path=/static-assets/pdf/content-code-examples/tutorials/html-to-pdf-26.cs
```
[[w:(Each form field in your HTML must have a unique `name` attribute. Duplicate names will cause fields to share the same value in the generated PDF, leading to unexpected behavior when users fill out the form.)]]
**RELATED HOW-TO Article:** <a class="content-anchor" href="/how-to/create-forms/">How to Create Fillable PDF Forms in C# <i class="fa-solid fa-arrow-right"></i></a>
### How to Convert Specific HTML Elements to PDF
To render a specific section of a page rather than the full document, isolate the target element before rendering. The most direct approach uses the `Javascript` rendering option to replace the document body with the target element's content, combined with `WaitFor.HtmlQuerySelector()` to ensure the element exists before extraction. The snippet below preserves `document.head` so stylesheets and fonts carry over; without that step, CSS rules relying on ancestor selectors would be lost in the extracted PDF.
For server-side scenarios where you have access to the raw HTML, extract the target fragment with a parser like AngleSharp and pass it to `RenderHtmlAsPdf()`, no JavaScript execution needed.
```csharp
:path=/static-assets/pdf/content-code-examples/tutorials/html-to-pdf-27.cs
```
**RELATED HOW-TO Article:** <a class="content-anchor" href="/how-to/html-element-to-pdf/">How to Convert HTML Elements and Partial Pages to PDF <i class="fa-solid fa-arrow-right"></i></a>
### How to Render Authenticated Pages to PDF
There are three mechanisms for rendering pages that sit behind authentication: network login credentials, custom cookies, and HTTP request headers. These cover the most common authentication scenarios when converting protected web content to PDF. This enables rendering of intranet dashboards, restricted reports, or API-generated pages directly to PDF without needing to retrieve the HTML separately.
**Login Credentials**
Use `ChromeHttpLoginCredentials` for basic, digest, or NTLM authentication when converting protected URLs to PDF.
```csharp
:path=/static-assets/pdf/content-code-examples/tutorials/html-to-pdf-28.cs
```
**Cookies and HTTP Headers**
For token-based or session-based authentication, attach custom cookies and HTTP headers directly to the rendering request.
```csharp
:path=/static-assets/pdf/content-code-examples/tutorials/html-to-pdf-29.cs
```
[[t:(For HTML form-based logins (POST username/password), consider using `HttpClient` to authenticate first, then pass the resulting cookies to the `CustomCookies` dictionary for rendering the protected page.)]]
**RELATED HOW-TO Articles:** <a class="content-anchor" href="/how-to/logins/">How to Convert HTML Behind Login Authentication to PDF <i class="fa-solid fa-arrow-right"></i></a> | <a class="content-anchor" href="/how-to/http-request-header/">Custom HTTP Request Headers <i class="fa-solid fa-arrow-right"></i></a>
### How Do I Generate PDFs from Multiple HTML Snippets?
To generate PDFs by combining HTML snippets, you can [merge](https://ironpdf.com/examples/merge-pdfs/) them. This creates multi-section reports or combines content from different sources:
```cs
var renderer = new ChromePdfRenderer();
PdfDocument part1 = renderer.RenderHtmlAsPdf("<h1>Section 1</h1><p>First section content</p>");
PdfDocument part2 = renderer.RenderHtmlAsPdf("<h1>Section 2</h1><p>Second section content</p>");
var merged = PdfDocument.Merge(part1, part2);
merged.SaveAs("Merged.pdf");
// Alternative approach: copy specific pages
var combinedDoc = new PdfDocument();
combinedDoc.CopyPage(part1, 0); // Copy first page
combinedDoc.CopyPage(part2, 0); // Copy first page
combinedDoc.SaveAs("Combined.pdf");
```
This helps when creating multi-section reports from different HTML fragments. You can also [add bookmarks](https://ironpdf.com/how-to/bookmarks/) to improve navigation.

### How Do I Convert HTML to PDF in Web APIs?
In ASP.NET Web API, generate and return PDFs without saving to disk using [MemoryStream](https://ironpdf.com/how-to/pdf-to-memory-stream/). This pattern is ideal for [Blazor applications](https://ironpdf.com/how-to/blazor-tutorial/) and RESTful services:
```cs
[HttpGet("download")]
public IActionResult GetPdf()
{
var renderer = new ChromePdfRenderer();
string html = "<h1>Web Report</h1><p>Generated dynamically.</p>";
var pdf = renderer.RenderHtmlAsPdf(html);
var bytes = pdf.BinaryData;
// Optional: Add metadata
pdf.MetaData.Author = "API Service";
pdf.MetaData.CreationDate = DateTime.Now;
return File(bytes, "application/pdf", "report.pdf");
}
```
This pattern works great for server-side PDF generation in .NET 10 web applications. You can integrate with [CSHTML views](https://ironpdf.com/how-to/cshtml-to-pdf-mvc-core/) for MVC applications.
### How Do You Add Headers, Watermarks, and Security?
#### Adding Professional Headers and Footers
Headers and footers that display page numbers, dates, or branding make multi-page documents far more readable and professional. IronPDF processes them as HTML fragments, so you can use full CSS styling including images and brand colors:
```csharp
using IronPdf;
var renderer = new ChromePdfRenderer();
renderer.RenderingOptions.HtmlHeader = new HtmlHeaderFooter
{
MaxHeight = 50,
HtmlFragment = "<div style='text-align:center;font-size:12px;'>Annual Report 2025 -- Confidential</div>",
BaseUrl = new Uri(@"file:///C:/assets/")
};
renderer.RenderingOptions.HtmlFooter = new HtmlHeaderFooter
{
MaxHeight = 30,
HtmlFragment = "<div style='text-align:center;font-size:10px;'>Page {page} of {total-pages}</div>",
DrawDividerLine = true
};
renderer.RenderingOptions.MarginTop = 60;
renderer.RenderingOptions.MarginBottom = 40;
var pdf = renderer.RenderHtmlAsPdf("<h1>Report Content</h1><p>Body text here.</p>");
pdf.SaveAs("report-with-headers.pdf");
```
Placeholders like `{page}` and `{total-pages}` are replaced automatically at render time. Review the [headers and footers tutorial](https://ironpdf.com/how-to/headers-and-footers/) for dynamic date injection, logo placement, and alternating page styles.
#### Applying Watermarks, Encryption, and Digital Signatures
Watermarks protect draft documents and confidential reports. Password protection and permission settings restrict who can print, copy, or edit a PDF. Digital signatures add a verifiable authenticity layer for contracts and regulated documents. You can combine all three in a single workflow:
```csharp
using IronPdf;
using System.Security.Cryptography.X509Certificates;
var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderHtmlAsPdf("<h1>Contract Agreement</h1><p>Terms and conditions.</p>");
// Watermark
pdf.ApplyWatermark(
"<div style='font-size:72px;color:red;opacity:0.3;'>DRAFT</div>",
rotation: 45,
opacity: 30
);
// Encryption and permissions
pdf.SecuritySettings.UserPassword = "user123";
pdf.SecuritySettings.OwnerPassword = "owner456";
pdf.SecuritySettings.AllowUserPrinting = IronPdf.Security.PdfPrintSecurity.NoPrint;
pdf.SecuritySettings.AllowUserCopyPasteContent = false;
// Digital signature
var cert = X509CertificateLoader.LoadPkcs12FromFile("certificate.pfx", "password");
var signature = new PdfSignature(cert)
{
SigningContact = "Jane Smith",
SigningLocation = "New York, NY",
SigningReason = "Contract Approval"
};
pdf.Sign(signature);
pdf.SaveAsRevision("signed-contract.pdf");
```
Learn about [watermarking techniques](https://ironpdf.com/how-to/custom-watermark/), [PDF security settings](https://ironpdf.com/how-to/pdf-permissions-passwords/), and [certificate-based signing](https://ironpdf.com/examples/digitally-sign-a-pdf/) including HSM integration for hardware security modules.
### Security Considerations
When converting HTML supplied by users or external systems, validate the input before rendering. Sanitizing HTML helps prevent malicious scripts or unexpected content from being processed.
If your application loads external resources, restrict them to trusted domains whenever possible. Using HTTPS URLs for stylesheets, fonts, and images also improves reliability and security.
Testing the rendering process in your production environment is recommended because network configuration, authentication, resource availability, and the underlying operating system can affect the generated PDF; by contrast, PuppeteerSharp may require custom startup scripts for Azure App Service, which can complicate deployment compared with IronPDF.
## 4. How to Deploy HTML to PDF on Cloud Platforms
Deploying HTML to PDF conversion in cloud environments requires specific configuration for headless rendering, temporary file paths, and resource allocation. This section covers the most common cloud platforms and containerized deployments with IronPDF.
<div class="my-6 max-w-full overflow-x-auto">
<table class="w-full border-separate border-spacing-0 overflow-clip rounded-lg border border-[#D9E5E9] [&_th]:border [&_th]:border-[#D9E5E9] [&_th]:px-3 [&_th]:py-4 [&_th]:text-center [&_th]:text-sm [&_th]:font-medium [&_td]:border [&_td]:border-[#D9E5E9] [&_td]:px-3 [&_td]:py-4 [&_td]:align-top [&_td]:text-[13.5px]/[1.5] [&_td]:text-[#181818] [&_td_ul]:m-0 [&_td_ul]:list-none [&_td_ul]:p-0 [&_td_ul>li+li]:mt-2">
<thead>
<tr>
<th>Platform</th>
<th>Min Resources</th>
<th>Package</th>
<th>AutoConfig</th>
<th>Temp Path</th>
<th>Key Gotcha</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<span>Azure App Service</span>
</td>
<td>
<span>B1 tier (Basic)</span>
</td>
<td>
<span><code>IronPdf.Linux</code></span>
</td>
<td>
<span><code>true</code></span>
</td>
<td>
<span>/tmp</span>
</td>
<td>
<span>Free/Shared tiers fail (no GPU, low memory)</span>
</td>
</tr>
<tr>
<td>
<span>Azure Functions (Windows)</span>
</td>
<td>
<span>B1 tier</span>
</td>
<td>
<span><code>IronPdf</code></span>
</td>
<td>
<span><code>true</code></span>
</td>
<td>
<span>/tmp</span>
</td>
<td>
<span>Uncheck "Run from package file"</span>
</td>
</tr>
<tr>
<td>
<span>AWS Lambda</span>
</td>
<td>
<span>512 MB / 60s timeout</span>
</td>
<td>
<span><code>IronPdf.Linux</code></span>
</td>
<td>
<span><code>true</code></span>
</td>
<td>
<span>/tmp (required)</span>
</td>
<td>
<span>Default filesystem is read-only</span>
</td>
</tr>
<tr>
<td>
<span>Docker (Ubuntu/Debian)</span>
</td>
<td>
<span>Image-dependent</span>
</td>
<td>
<span><code>IronPdf.Linux</code></span>
</td>
<td>
<span><code>false</code></span>
</td>
<td>
<span>Image default</span>
</td>
<td>
<span>Set <code>false</code> (Dockerfile handles deps)</span>
</td>
</tr>
</tbody>
</table>
</div>
### How to Deploy on Azure
When deploying to Azure Functions or App Service, disable GPU acceleration and ensure your hosting tier provides enough memory for Chrome-based rendering. Add these settings at application startup, before any rendering calls.
Azure sandboxes run headless with no GPU access, and Free/Shared tiers (F1, D1) lack the resources Chrome requires. Target a **B1 (Basic)** tier or higher.
```csharp
:path=/static-assets/pdf/content-code-examples/tutorials/html-to-pdf-30.cs
```
[[e:(Azure App Service Free and Shared tiers (F1, D1) do not have enough resources for Chrome-based PDF rendering. Use at minimum a **B1 (Basic)** tier or higher to avoid out-of-memory errors and process timeouts.)]]
**RELATED GET-STARTED Guide:** <a class="content-anchor" href="/get-started/azure/">How to Deploy IronPDF on Azure <i class="fa-solid fa-arrow-right"></i></a>
### How to Deploy on AWS Lambda
AWS Lambda requires Docker-based deployment for Chrome-based PDF rendering. The default Lambda filesystem is read-only, so all temp and deployment paths must point to `/tmp`.
Configure these settings at the top of your function handler, before any rendering calls.
```csharp
using Amazon.Lambda.Core;
using IronPdf;
public class PdfFunction
{
public string FunctionHandler(string input, ILambdaContext context)
{
// Lambda's only writable directory
var tmpPath = "/tmp/";
IronPdf.Installation.TempFolderPath = tmpPath;
IronPdf.Installation.CustomDeploymentDirectory = tmpPath;
IronPdf.Installation.ChromeGpuMode = IronPdf.Engines.Chrome.ChromeGpuModes.Disabled;
// Let IronPDF install Chrome dependencies on first cold start
IronPdf.Installation.LinuxAndDockerDependenciesAutoConfig = true;
context.Logger.LogLine("Rendering PDF...");
var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderHtmlAsPdf(input);
// Save to /tmp before uploading to S3 or returning
var outputPath = $"{tmpPath}output.pdf";
pdf.SaveAs(outputPath);
return outputPath;
}
}
```
[[i:(Configure your Lambda function with at least **512 MB of memory** and a **60-second timeout** minimum. Chrome-based rendering is memory-intensive, and cold starts require additional initialization time for the embedded browser engine.)]]
**RELATED GET-STARTED Guide:** <a class="content-anchor" href="/get-started/aws/">How to Deploy IronPDF on AWS Lambda <i class="fa-solid fa-arrow-right"></i></a>
### How to Deploy with Docker
For Docker deployments, use the `IronPdf.Linux` NuGet package to reduce image size and avoid runtime asset downloads. This package includes pre-bundled Linux-native binaries optimized for containerized environments.
Set `LinuxAndDockerDependenciesAutoConfig = false` when your Dockerfile already installs Chrome's shared-library dependencies via `apt-get`. The runtime auto-install is redundant in that case and can cause permission errors or longer cold starts.
<div class="my-6 max-w-full overflow-x-auto">
<table class="w-full border-separate border-spacing-0 overflow-clip rounded-lg border border-[#D9E5E9] [&_th]:border [&_th]:border-[#D9E5E9] [&_th]:px-3 [&_th]:py-4 [&_th]:text-center [&_th]:text-sm [&_th]:font-medium [&_td]:border [&_td]:border-[#D9E5E9] [&_td]:px-3 [&_td]:py-4 [&_td]:align-top [&_td]:text-[13.5px]/[1.5] [&_td]:text-[#181818] [&_td_ul]:m-0 [&_td_ul]:list-none [&_td_ul]:p-0 [&_td_ul>li+li]:mt-2">
<thead>
<tr>
<th>Platform</th>
<th>Package</th>
<th>Key Configuration</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<span>Ubuntu 22.04 / Debian</span>
</td>
<td>
<span><code>IronPdf.Linux</code></span>
</td>
<td>
<span>Default, works out of the box</span>
</td>
</tr>
<tr>
<td>
<span>Alpine Linux</span>
</td>
<td>
<span><code>IronPdf.Linux</code></span>
</td>
<td>
<span>Install chromium via apk in Dockerfile</span>
</td>
</tr>
<tr>
<td>
<span>Amazon Linux 2</span>
</td>
<td>
<span><code>IronPdf.Linux</code></span>
</td>
<td>
<span>Use <code>LinuxAndDockerDependenciesAutoConfig = true</code></span>
</td>
</tr>
<tr>
<td>
<span>Windows Containers</span>
</td>
<td>
<span><code>IronPdf</code></span>
</td>
<td>
<span>No additional configuration required</span>
</td>
</tr>
</tbody>
</table>
</div>
<br />
A minimal multi-stage Dockerfile for an Ubuntu/Debian-based image:
```dockerfile
FROM mcr.microsoft.com/dotnet/sdk:10.0 AS build
WORKDIR /app
COPY . .
RUN dotnet publish -c Release -o /out
FROM mcr.microsoft.com/dotnet/aspnet:10.0
# Install Chrome dependencies for PDF rendering
RUN apt-get update && apt-get install -y \
libglib2.0-0 libnss3 libatk1.0-0 libatk-bridge2.0-0 \
libcups2 libdrm2 libxkbcommon0 libxcomposite1 \
libxdamage1 libxrandr2 libgbm1 libpango-1.0-0 \
libcairo2 libasound2 libxshmfence1 && \
rm -rf /var/lib/apt/lists/*
WORKDIR /app
COPY --from=build /out .
ENTRYPOINT ["dotnet", "MyApp.dll"]
```
<br />
```csharp
:path=/static-assets/pdf/content-code-examples/tutorials/html-to-pdf-33.cs
```
A real gotcha I came across with the Docker setup: IronPdfEngine (the Docker image) runs as a single instance, so the engine itself does not scale horizontally. The fix-around is simple. Any app using the IronPdf library, with or without IronPdfEngine, scales horizontally just by spinning up new instances, and the workload spreads across them quite easily.
**RELATED GET-STARTED Guide:** <a class="content-anchor" href="/get-started/ironpdf-docker/">How to Use IronPDF with Docker <i class="fa-solid fa-arrow-right"></i></a>
### How can HTML-to-PDF performance be optimized and scaled in .NET Core?
IronPDF's Chromium engine already renders quickly on modern hardware, but throughput can be multiplied by **batching renders, enabling multi-threading, and trimming Headless Chrome overhead**. The tips below apply equally to all .NET versions.
#### 1. Batch renders on a background thread pool
```csharp
:path=/static-assets/pdf/content-code-examples/tutorials/dotnet-core-pdf-generating-12.cs
```
- `ChromePdfRenderer` is **[thread-safe](/examples/threading/)**; a single instance may serve dozens of concurrent tasks without deadlocks.
- `Parallel.ForEach` saturates every CPU core, improving throughput compared with a single-thread loop.
- If ASP.NET requests queue up, [move heavy renders to a hosted background service or message queue](https://stackoverflow.com/questions/65237160/ironpdf-deadlocks-when-running-in-parallel) to keep response times low.
#### 2. Trim Headless Chrome startup cost
IronPDF ships its own Chromium build, but each render incurs a small startup tax. Pooling helps, and **Linux containers** must include two native libs:
```dockerfile
RUN apt-get update && \
apt-get install -y --no-install-recommends libnss3 libatk1.0-0
```
Missing either library manifests as a `libnss3.so not found` error in Docker logs.
[Recommended Chrome flags (automatically applied by IronPDF)](https://stackoverflow.com/questions/66947545/chrome-headless-not-working-as-root-with-no-sandbox) include `--disable-gpu` and `--no-sandbox` to reduce memory and root-user issues in containers.
#### 3. Wait for late JavaScript with `RenderDelay` or `WaitFor`
Pages that animate counters or fetch data after `DOMContentLoaded` may need a short delay:
```csharp
renderer.RenderingOptions.RenderDelay = 200; // ms
// OR: renderer.RenderingOptions.WaitFor.JavaScript("window.doneLoading === true");
```
See the dedicated **[WaitFor tutorial](/how-to/waitfor/)** for custom promises and DOM polling.
#### 4. Enable debug logging for one request
```csharp
:path=/static-assets/pdf/content-code-examples/tutorials/dotnet-core-pdf-generating-15.cs
```
Live DevTools traces expose missing fonts, 404 images, and timing events without re-compiling code.
#### 5. Reuse template PDFs instead of re-rendering
For invoice runs, [create a **template PDF** with placeholders](/troubleshooting/ironpdf-performance-assistance/) like `[[name]]` and perform a text replace instead of rebuilding complex HTML. It avoids re-rendering complex HTML and is memory-light.
#### Further Reading
- How-to - [Generate PDFs with async / multithreading](/how-to/async/)
- Troubleshooting - [Performance assistance centre](/troubleshooting/ironpdf-performance-assistance/)
- Example - [Threaded rendering demo](/examples/threading/)
---
## 5. Compare IronPDF with other .NET PDF Libraries
IronPDF is the solution of choice for many teams when it comes to C# PDF generation thanks to its robust Chromium-powered rendering engine, intuitive APIs and frequent product enhancements. Let's compare IronPDF with other PDF converters to find the best fit for your PDF generation needs.
### Free and Open-Source Alternatives
Some tools that might come into consideration:
- **PuppeteerSharp:** an MIT-licensed .NET port of Puppeteer that drives headless Chrome.
- **Playwright for .NET:** Microsoft's Apache-2.0 automation library, also Chromium-based.
- **wkhtmltopdf:** a long-standing standalone HTML-to-PDF binary.
- **Native browser routes:** print-to-PDF straight from a headless browser or OS print driver.
A distinction worth drawing first: PuppeteerSharp and Playwright are browser-automation frameworks rather than PDF libraries. They expose a print-to-PDF call on top of real Chromium, so rendering fidelity is excellent, but PDF specifics like headers and footers, encryption, signatures, and PDF/A, along with the browser's lifecycle, are left to you: shipping and updating the Chromium binary, handling concurrency and crash recovery, and building document structure by hand. Playwright adds a constraint worth knowing early: its `PdfAsync` runs only in headless Chromium (not Firefox or WebKit), so deployments must guarantee a headless Chrome, which matters in containers and serverless.
wkhtmltopdf sits differently again. The project was archived in 2024, and its final release (0.12.6, 2020) runs a ~2012 Qt WebKit engine receiving no further security patches, including an unpatched critical SSRF advisory (CVE-2022-35583); it remains workable for simple static documents on trusted input, but less so for public-facing output. Native browser routes need no library at all, at the cost of any .NET-native PDF API or real control over server-side automation.
For prototypes, internal tools, and zero-budget work, these are legitimate choices. The comparison below covers the commercial libraries feature by feature.
### Quick Decision Matrix: IronPDF versus .NET PDF Converters
<div class="my-6 max-w-full overflow-x-auto">
<table class="w-full border-separate border-spacing-0 overflow-clip rounded-lg border border-[#D9E5E9] [&_th]:border [&_th]:border-[#D9E5E9] [&_th]:px-3 [&_th]:py-4 [&_th]:text-center [&_th]:text-sm [&_th]:font-medium [&_td]:border [&_td]:border-[#D9E5E9] [&_td]:px-3 [&_td]:py-4 [&_td]:align-top [&_td]:text-[13.5px]/[1.5] [&_td]:text-[#181818] [&_td_ul]:m-0 [&_td_ul]:list-none [&_td_ul]:p-0 [&_td_ul>li+li]:mt-2">
<thead>
<tr>
<th>Solution</th>
<th>When to use</th>
<th>Best for</th>
</tr>
</thead>
<tbody>
<tr style="background-color: #f8fdff;">
<td>
<span><strong>IronPDF</strong></span>
</td>
<td>
<span>Converting modern websites/HTML to PDF with exact visual fidelity.</span>
</td>
<td>
<span>Enterprise applications requiring reliable HTML rendering engine, dynamic content, and professional support.</span>
</td>
</tr>
<tr>
<td>
<span>wkhtmltopdf</span>
</td>
<td>
<span>Simple HTML conversion in non-critical applications where outdated rendering is acceptable.</span>
</td>
<td>
<span>Basic document generation with legacy HTML/CSS.</span>
</td>
</tr>
<tr>
<td>
<span>Syncfusion</span>
</td>
<td>
<span>When already invested in Syncfusion ecosystem or eligible for free community license.</span>
</td>
<td>
<span>Organizations using multiple Syncfusion components.</span>
</td>
</tr>
<tr>
<td>
<span>Aspose.PDF</span>
</td>
<td>
<span>Complex PDF manipulation when HTML rendering quality is less critical.</span>
</td>
<td>
<span>Extensive PDF editing features beyond HTML conversion.</span>
</td>
</tr>
</tbody>
</table>
</div>
**RELATED COMPARISONS:**
<ul>
<li><a class="content-anchor" href="/competitors/syncfusion-vs-ironpdf/">Compare IronPDF and Syncfusion <i class="fa-solid fa-arrow-right"></i></a></li>
<li><a class="mt-2 content-anchor" href="/competitors/aspose-vs-ironpdf/">Compare IronPDF and Aspose <i class="fa-solid fa-arrow-right"></i></a></li>
</ul>
### Detailed Comparison: IronPDF versus Other .NET PDF Converters
<div>
<div class="my-6 max-w-full overflow-x-auto">
<table class="w-full min-w-[1000px] border-separate border-spacing-0 overflow-clip rounded-lg border border-[#D9E5E9] [&_th]:border [&_th]:border-[#D9E5E9] [&_th]:px-3 [&_th]:py-4 [&_th]:text-center [&_th]:text-sm [&_th]:font-bold [&_th]:text-[#181818] [&_td]:border [&_td]:border-[#D9E5E9] [&_td]:px-3 [&_td]:py-3 [&_td]:text-center [&_td]:align-middle [&_td]:text-[13.5px]/[1.5] [&_td]:text-[#181818] [&_a]:underline [&_.iron-col]:bg-[#F1F9FB] [&_.recommended]:block [&_.recommended]:text-[11px] [&_.recommended]:font-bold [&_.recommended]:text-[#E01A59] [&_.col-name]:block [&_.col-name]:text-sm [&_.col-name]:font-bold [&_.section-row_td]:bg-[#F5F8FA] [&_.section-row_td]:font-bold [&_.section-row_td]:uppercase [&_.section-row_td]:tracking-wide [&_.section-row_td]:text-xs [&_.section-row_td]:text-[#5A6B77] [&_.chip]:inline-block [&_.chip]:whitespace-nowrap [&_.chip]:rounded [&_.chip]:px-2 [&_.chip]:py-0.5 [&_.chip]:text-xs [&_.chip]:font-semibold [&_.chip-full]:bg-[#E8F6F1] [&_.chip-full]:text-[#44806B] [&_.chip-good]:bg-[#E8F6F1] [&_.chip-good]:text-[#44806B] [&_.chip-free]:bg-[#E8F6F1] [&_.chip-free]:text-[#44806B] [&_.chip-partial]:bg-[#FFF2DA] [&_.chip-partial]:text-[#A66E0A] [&_.chip-limited]:bg-[#FFF2DA] [&_.chip-limited]:text-[#A66E0A] [&_.chip-no]:bg-[#FFE1E2] [&_.chip-no]:text-[#A8181D] [&_.chip-iron]:bg-[#DEEFFC] [&_.chip-iron]:text-[#1D629B] [&_.price-val]:block [&_.price-val]:font-bold [&_.price-note]:mt-0.5 [&_.price-note]:block [&_.price-note]:text-[11px] [&_.price-note]:leading-snug [&_.price-note]:text-[#5A6B77] [&_.winner-tag]:ml-1 [&_.winner-tag]:inline-block [&_.winner-tag]:rounded [&_.winner-tag]:bg-[#E8F6F1] [&_.winner-tag]:px-1.5 [&_.winner-tag]:py-0.5 [&_.winner-tag]:text-[11px] [&_.winner-tag]:font-bold [&_.winner-tag]:text-[#44806B]">
<thead>
<tr>
<th>Feature</th>
<th class="iron-col">
<span class="recommended">★ Recommended</span>
<span class="col-name">IronPDF</span>
</th>
<th>wkhtmltopdf</th>
<th>iText</th>
<th>Aspose.PDF</th>
<th>Syncfusion</th>
<th>Apryse</th>
<th>SelectPdf</th>
<th>Spire.PDF</th>
<th>PDFSharp</th>
<th>QuestPDF</th>
</tr>
</thead>
<tbody>
<tr class="section-row">
<td colspan="11">Rendering & Conversion</td>
</tr>
<tr>
<td>Rendering Accuracy</td>
<td class="iron-col">Pixel-Perfect </td>
<td>Print-Style</td>
<td>Programmatic Only</td>
<td>Good</td>
<td>Good</td>
<td>Good</td>
<td>Good</td>
<td>Low-Level</td>
<td>No Rendering</td>
<td>Code-First Layout</td>
</tr>
<tr>
<td>HTML5 Support</td>
<td class="iron-col"><span class="chip chip-full">Full</span></td>
<td><span class="chip chip-limited">Outdated</span></td>
<td><span class="chip chip-partial">Add-on</span></td>
<td><span class="chip chip-partial">Partial</span></td>
<td><span class="chip chip-full">Full</span></td>
<td><span class="chip chip-partial">Module</span></td>
<td><span class="chip chip-full">Full</span></td>
<td><span class="chip chip-limited">Limited</span></td>
<td><span class="chip chip-no">No</span></td>
<td><span class="chip chip-no">No (Code-First)</span></td>
</tr>
<tr>
<td>CSS3 Support</td>
<td class="iron-col"><span class="chip chip-full">Full</span></td>
<td><span class="chip chip-limited">Limited</span></td>
<td><span class="chip chip-partial">Add-on</span></td>
<td><span class="chip chip-partial">Partial</span></td>
<td><span class="chip chip-full">Full</span></td>
<td><span class="chip chip-partial">Module</span></td>
<td><span class="chip chip-full">Full</span></td>
<td><span class="chip chip-limited">Limited</span></td>
<td><span class="chip chip-no">No</span></td>
<td><span class="chip chip-no">No (Code-First)</span></td>
</tr>
<tr>
<td>JavaScript Execution</td>
<td class="iron-col">
<span class="chip chip-full">Full</span>
</td>
<td><span class="chip chip-no">No</span></td>
<td><span class="chip chip-no">No</span></td>
<td><span class="chip chip-limited">Disputed</span></td>
<td><span class="chip chip-partial">Limited</span></td>
<td><span class="chip chip-partial">Limited</span></td>
<td><span class="chip chip-partial">Limited</span></td>
<td><span class="chip chip-limited">Very Limited</span></td>
<td><span class="chip chip-no">No</span></td>
<td><span class="chip chip-no">No</span></td>
</tr>
<tr>
<td>HTML→PDF (Modern Layout)</td>
<td class="iron-col">Embedded Chromium </td>
<td>Qt WebKit (Outdated)</td>
<td>Paid Add-on</td>
<td>Partial; JS Disputed</td>
<td>Blink Engine</td>
<td>Requires Module</td>
<td>Full HTML→PDF</td>
<td>Image-Based</td>
<td><span class="chip chip-no">No</span></td>
<td><span class="chip chip-no">Not an HTML Renderer</span></td>
</tr>
<tr>
<td>PDF→Image Rendering</td>
<td class="iron-col"><span class="chip chip-full">Yes</span></td>
<td><span class="chip chip-no">No</span></td>
<td><span class="chip chip-partial">Yes</span></td>
<td><span class="chip chip-partial">Yes</span></td>
<td><span class="chip chip-full">Yes</span></td>
<td><span class="chip chip-full">Yes</span></td>
<td><span class="chip chip-no">No</span></td>
<td><span class="chip chip-partial">Limited</span></td>
<td><span class="chip chip-no">No</span></td>
<td><span class="chip chip-partial">Own Docs Only</span></td>
</tr>
<tr class="section-row">
<td colspan="11">Document Operations</td>
</tr>
<tr>
<td>Generate PDFs Programmatically</td>
<td class="iron-col"><span class="chip chip-full">Yes</span></td>
<td><span class="chip chip-no">No</span></td>
<td><span class="chip chip-full">Yes</span></td>
<td><span class="chip chip-full">Yes</span></td>
<td><span class="chip chip-full">Yes</span></td>
<td><span class="chip chip-full">Yes</span></td>
<td><span class="chip chip-partial">HTML Only</span></td>
<td><span class="chip chip-full">Yes</span></td>
<td><span class="chip chip-good">Basic</span></td>
<td><span class="chip chip-full">Yes (Fluent API)</span></td>
</tr>
<tr>
<td>Merge, Split & Rearrange</td>
<td class="iron-col"><span class="chip chip-full">Yes</span></td>
<td><span class="chip chip-no">No</span></td>
<td><span class="chip chip-full">Yes</span></td>
<td><span class="chip chip-full">Yes</span></td>
<td><span class="chip chip-full">Yes</span></td>
<td><span class="chip chip-full">Yes</span></td>
<td><span class="chip chip-full">Yes</span></td>
<td><span class="chip chip-full">Yes</span></td>
<td><span class="chip chip-partial">Limited</span></td>
<td><span class="chip chip-full">Yes</span></td>
</tr>
<tr>
<td>Headers / Footers / Page Numbers</td>
<td class="iron-col">HTML/Text/Image </td>
<td>Limited</td>
<td>Yes</td>
<td>Via Events</td>
<td>Via Events</td>
<td>Yes</td>
<td>Templates</td>
<td>Manual</td>
<td>Manual Only</td>
<td><span class="chip chip-full">First-Class Slots</span></td>
</tr>
<tr>
<td>Watermarks & Stamping</td>
<td class="iron-col"><span class="chip chip-full">Text & Image</span></td>
<td><span class="chip chip-no">No</span></td>
<td><span class="chip chip-full">Yes</span></td>
<td><span class="chip chip-full">Yes</span></td>
<td><span class="chip chip-full">Yes</span></td>
<td><span class="chip chip-full">Yes</span></td>
<td><span class="chip chip-full">Yes</span></td>
<td><span class="chip chip-partial">Limited</span></td>
<td><span class="chip chip-no">No</span></td>
<td><span class="chip chip-full">Yes (Overlays)</span></td>
</tr>
<tr>
<td>Extract Text from PDFs</td>
<td class="iron-col"><span class="chip chip-full">Yes</span></td>
<td><span class="chip chip-no">No</span></td>
<td><span class="chip chip-full">Yes</span></td>
<td><span class="chip chip-full">Yes</span></td>
<td><span class="chip chip-full">Yes</span></td>
<td><span class="chip chip-full">Yes</span></td>
<td><span class="chip chip-full">Yes</span></td>
<td><span class="chip chip-full">Yes</span></td>
<td><span class="chip chip-good">Basic</span></td>
<td><span class="chip chip-no">No</span></td>
</tr>
<tr>
<td>OCR for Scanned PDFs</td>
<td class="iron-col">Via IronOCR <span class="winner-tag">Integrated</span></td>
<td><span class="chip chip-no">No</span></td>
<td><span class="chip chip-partial">Add-on</span></td>
<td><span class="chip chip-partial">Separate Product</span></td>
<td><span class="chip chip-partial">Add-on</span></td>
<td><span class="chip chip-partial">Add-on</span></td>
<td><span class="chip chip-no">No</span></td>
<td><span class="chip chip-partial">Workaround</span></td>
<td><span class="chip chip-no">No</span></td>
<td><span class="chip chip-no">No</span></td>
</tr>
<tr class="section-row">
<td colspan="11">Security & Compliance</td>
</tr>
<tr>
<td>Digital Signatures</td>
<td class="iron-col"><span class="chip chip-full">Yes</span></td>
<td><span class="chip chip-no">No</span></td>
<td><span class="chip chip-full">Yes</span></td>
<td><span class="chip chip-full">Yes</span></td>
<td><span class="chip chip-full">Yes</span></td>
<td><span class="chip chip-good">Sample Code</span></td>
<td><span class="chip chip-full">Yes</span></td>
<td><span class="chip chip-no">No</span></td>
<td><span class="chip chip-no">No</span></td>
<td><span class="chip chip-no">Not Documented</span></td>
</tr>
<tr>
<td>PDF/A Compliance</td>
<td class="iron-col"><span class="chip chip-full">Yes (PDF/A-3B)</span></td>
<td><span class="chip chip-no">No</span></td>
<td><span class="chip chip-full">Full PDF/A</span></td>
<td><span class="chip chip-full">Validate & Create</span></td>
<td><span class="chip chip-good">Requires Native SDK</span></td>
<td><span class="chip chip-good">PDFACompliance</span></td>
<td><span class="chip chip-no">No</span></td>
<td><span class="chip chip-full">Yes</span></td>
<td><span class="chip chip-partial">Limited</span></td>
<td><span class="chip chip-full">PDF/A-2x & 3x</span></td>
</tr>
<tr class="section-row">
<td colspan="11">Platform & Developer Experience</td>
</tr>
<tr>
<td>Cross-Platform</td>
<td class="iron-col">Windows · Linux · macOS <span class="winner-tag">All 3</span></td>
<td>Depends on Binaries</td>
<td>.NET Standard 2.0</td>
<td>Linux Extra Setup</td>
<td>Blink + .NET Server</td>
<td>Native SDK</td>
<td>Windows-Only *</td>
<td>Limited Linux Docs</td>
<td>Windows-Focused</td>
<td><span class="chip chip-full">Win/Linux/macOS</span></td>
</tr>
<tr>
<td>Cloud & Docker Deploy</td>
<td class="iron-col">Azure · AWS · Docker </td>
<td>Complex; Legacy</td>
<td>Multiple Packages</td>
<td>Partial; Containers</td>
<td>Blink Extras Needed</td>
<td>Native Deps</td>
<td>Windows-Only</td>
<td>Limited Info</td>
<td>Simple; Lightweight</td>
<td><span class="chip chip-full">Docker/K8s; Local</span></td>
</tr>
<tr class="section-row">
<td colspan="11">Support & Documentation</td>
</tr>
<tr>
<td>Documentation</td>
<td class="iron-col">Extensive + Copy/Paste </td>
<td>Partial CLI Docs</td>
<td>Extensive; KB</td>
<td>Broad; GitHub</td>
<td>Help Center</td>
<td>Cross-Language Catalog</td>
<td>Getting Started Guides</td>
<td>Program Guide</td>
<td>Community Guides</td>
<td><span class="chip chip-full">Structured + Companion App</span></td>
</tr>
<tr>
<td>Developer Support</td>
<td class="iron-col">24/7 Support · 24/5 Chat</td>
<td>Community Only</td>
<td>Subscription Included</td>
<td>Forum + Paid</td>
<td>24/5 Direct-Trac</td>
<td>Commercial</td>
<td>Email</td>
<td>Forum + Email</td>
<td>Community Only</td>
<td><span class="chip chip-partial">Community + GitHub</span></td>
</tr>
<tr class="section-row">
<td colspan="11">Licensing & Pricing</td>
</tr>
<tr>
<td>License Model</td>
<td class="iron-col"><span class="chip chip-iron">Perpetual</span></td>
<td><span class="chip chip-free">Open Source</span></td>
<td><span class="chip chip-partial">AGPL / Subscription</span></td>
<td><span class="chip chip-good">Perpetual</span></td>
<td><span class="chip chip-partial">Annual Subscription</span></td>
<td><span class="chip chip-partial">Custom / Consumption</span></td>
<td><span class="chip chip-good">Perpetual</span></td>
<td><span class="chip chip-good">Perpetual</span></td>
<td><span class="chip chip-free">Free (MIT)</span></td>
<td><span class="chip chip-free">MIT Free / Paid Tiers</span></td>
</tr>
<tr>
<td>Starting Price</td>
<td class="iron-col">
<span class="price-val iron-price">
<a href="https://ironpdf.com/licensing/">`$liteLicense`</a>
</span>
<span class="price-note">Perpetual · 1 Developer</span>
</td>
<td><span class="price-val" style="color:#16a34a">Free</span></td>
<td>
<span class="price-val">~$45K/yr</span>
<span class="price-note">Custom Quote</span>
</td>
<td>
<span class="price-val">$1,175+</span>
<span class="price-note">Per Developer</span>
</td>
<td>
<span class="price-val">Custom Quote</span>
<span class="price-note">Free <$1M (Community)</span>
</td>
<td>
<span class="price-val">~$9K+/yr</span>
<span class="price-note">Custom Quote</span>
</td>
<td>
<span class="price-val">$499+</span>
<span class="price-note">Perpetual</span>
</td>
<td>
<span class="price-val">$999</span>
<span class="price-note">Perpetual · 1yr updates</span>
</td>
<td><span class="price-val" style="color:#16a34a">Free</span></td>
<td>
<span class="price-val" style="color:#16a34a">Free</span>
<span class="price-note">Community MIT <$1M</span>
</td>
</tr>
<tr>
<td>Free Trial</td>
<td class="iron-col">30 Days · Full Features <span class="winner-tag">No Limits</span></td>
<td>N/A (Free)</td>
<td>30 Days</td>
<td>Yes (Watermarked)</td>
<td>Community <$1M Rev</td>
<td>Yes</td>
<td>Community (5 Pages)</td>
<td>Free (10 Pages)</td>
<td>N/A (Free)</td>
<td>N/A (MIT Free <$1M)</td>
</tr>
<tr>
<td>Pricing Transparency</td>
<td class="iron-col">Published & Clear </td>
<td>Open Source</td>
<td><span class="chip chip-limited">Complex AGPL</span></td>
<td><span class="chip chip-partial">Many Tiers</span></td>
<td><span class="chip chip-good">Contact for Quote</span></td>
<td><span class="chip chip-limited">No Published Pricing</span></td>
<td><span class="chip chip-good">Published</span></td>
<td><span class="chip chip-good">Published</span></td>
<td>MIT; No Restrictions</td>
<td>MIT; Trust-Based</td>
</tr>
</tbody>
</table>
</div>
</div>
### Real-life HTML to PDF Conversion Comparison: Rendering Reddit's Homepage
To evaluate the output PDF quality, we tested these libraries with Reddit's homepage containing dynamic web content, modern CSS, and JavaScript HTML elements. This page serves as an ideal test case for output PDF generation.
https://www.reddit.com/

**IronPDF**

IronPDF delivers pixel-perfect results, preserving all dynamic web content, modern web fonts styling, and interactive elements exactly as displayed in Chrome, all in just a few lines of code.
**Syncfusion**

Syncfusion rendered PDF with most sections and styling missing, especially dynamic content. Initially blocked by Reddit's security. Achieving better results requires extensive command-line tuning, yet output remains incomplete.
**Aspose.PDF**

Aspose.PDF required manual HTML download first (no direct URL support). After conversion, output lacked proper formatting and missed nearly all content sections, making it unsuitable for modern web with dynamic content.
**wkhtmltopdf**

wkhtmltopdf completed quickly but produced a plain, static page missing critical content like live updates, dynamic elements, and interactive sections. This demonstrates wkhtmltopdf's incompatibility with modern, JavaScript-driven websites.
### Conclusion on Performance and Output PDF Quality
For .NET developers needing a reliable HTML to PDF converter, IronPDF stands out with minimal code, easy-to-use APIs, and frequent product enhancements.
In a real-world test on web content, it delivered the fastest, most accurate results while Syncfusion lagged behind, Aspose required extra steps, and wkhtmltopdf missed modern styling. IronPDF offers the best balance of speed, accuracy, and simplicity for today's HTML to PDF conversion workflows.
*Verified on IronPDF v2026.8.1 · .NET 10 · July 2026.*
[[i:(Aspose, Syncfusion, and wkhtmltopdf are trademarks of their respective owners. This site is not affiliated with or endorsed by them. All names, logos, and brands belong to their owners, and comparisons are based on publicly available information at the time of writing.)]]
### Summary
This guide covered everything needed to convert HTML to PDF in .NET: from basic string conversion to advanced features like async processing, digital signatures, and batch generation. We demonstrated three conversion methods, essential configurations, advanced features and security settings, and compared IronPDF with other libraries through real-world testing of dynamic document generation.
While competitors struggled with modern websites or required complex workarounds, IronPDF delivered flawless results with minimal code and powerful rendering engine.
Ready to streamline your PDF workflow and experience versatile PDF generation in just a few lines of code? Install IronPDF through NuGet Package Manager (or select Manage NuGet Package in Visual Studio) and convert your first HTML to PDF today.
[Start your free 30-day trial](/licensing/) for production testing without watermarks. [Flexible licensing](/licensing/) starts at `$liteLicense` with transparent team pricing that scales with your needs. Once you have a license, add it at the start of your application with `IronPdf.License.LicenseKey = "KEY";`.
<a class="content-anchor" href="/licensing/">View IronPDF Licensing <i class="fa-solid fa-arrow-right"></i></a>
## 6. Troubleshooting & Technical Support
Having trouble with the following errors in HTML to PDF conversion? IronPDF engineers provide support 24/7; live chat via the widget on [https://ironpdf.com/](/) is available 24/5.
### Quick Fixes on Common Errors
- Slow first render? Normal. Chrome initializes in 2-3s, then speeds up.
- Cloud issues? Use at least Azure B1 or equivalent resources.
- Missing assets? Set base paths or embed as base64.
- Missing elements? Add `RenderDelay` for JavaScript execution.
- Memory in rendering? Update to the latest version (v2026.8.1) for fixes in HTML to PDF, stamps, and headers/footers.
- Form field issues (e.g., long textareas, checkboxes)? Fixed in v2025.7.17; ensure unique names for checkboxes.
- Custom header/footer clipping or special characters corrupted? Resolved in v2025.8.8; test word-wrapping and metadata.
### Common Issues and Troubleshooting
#### Images Don't Appear
Ensure that image URLs are accessible during rendering. If the images are stored locally, use absolute file paths or embed them directly in the HTML.
#### CSS Styles Are Missing
Verify that all CSS files are available and that the paths are correct. If possible, use absolute URLs for external stylesheets.
#### JavaScript Content Doesn't Render
If the page loads data asynchronously, configure the renderer to wait for JavaScript execution before generating the PDF.
#### External Fonts Are Missing
Make sure custom web fonts can be accessed during rendering. Alternatively, embed fonts directly into the HTML using @font-face.
#### HTML Looks Different in the PDF
Browsers and printed pages use different layouts. Each html element can render differently on paper than it does on screen, so consider creating a dedicated print stylesheet using @media print to optimize the output.
### Get Help From The Engineers Who Built IronPDF, 24/7
<ul>
<li><a class="content-anchor" href="/troubleshooting/engineering-request-pdf/">Comprehensive troubleshooting guide <i class="fa-solid fa-arrow-right"></i></a></li>
<li><a class="mt-2 content-anchor" href="/troubleshooting/ironpdf-performance-assistance/">Performance optimization strategies <i class="fa-solid fa-arrow-right"></i></a></li>
<li><a class="mt-2 content-anchor" href="/troubleshooting/engineering-request-pdf/">Engineering support requests <i class="fa-solid fa-arrow-right"></i></a></li>
<li><a class="mt-2 content-anchor" href="/troubleshooting/quick-ironpdf-troubleshooting/">Quick troubleshooting checklist <i class="fa-solid fa-arrow-right"></i></a></li>
</ul>
*as-heading:2(Next Steps)*
<div class="my-6 grid grid-cols-1 gap-4 pb-10 sm:grid-cols-2 lg:grid-cols-3">
<div class="group flex h-full flex-col gap-8 rounded-lg border border-[#E7EEF0] bg-white p-6 transition-all duration-200 hover:shadow-[0_4px_12px_0_rgb(24_24_24/0.08)]">
<span class="flex flex-col gap-4">
<span class="flex h-8 max-w-10 items-center justify-center text-[32px] text-[#678CB1]"><i class="fa-solid fa-graduation-cap"></i></span>
<span class="text-[15px]/[1.6] font-bold text-[#181818]">How to Merge or Split PDF Documents</span>
</span>
<a href="/how-to/merge-or-split-pdfs/" class="mt-auto flex items-center gap-2 text-sm/[1.4] font-bold text-[#2A95D5] no-underline transition-colors duration-200 group-hover:text-[#E01A59]">See How-To <span class="inline-flex items-center transition-transform duration-200 group-hover:translate-x-1"><i class="fa-solid fa-arrow-right"></i></span></a>
</div>
<div class="group flex h-full flex-col gap-8 rounded-lg border border-[#E7EEF0] bg-white p-6 transition-all duration-200 hover:shadow-[0_4px_12px_0_rgb(24_24_24/0.08)]">
<span class="flex flex-col gap-4">
<span class="flex h-8 max-w-10 items-center justify-center text-[32px] text-[#678CB1]"><i class="fa-solid fa-graduation-cap"></i></span>
<span class="text-[15px]/[1.6] font-bold text-[#181818]">How to Add Custom Headers and Footers to PDF Files</span>
</span>
<a href="/how-to/headers-and-footers/" class="mt-auto flex items-center gap-2 text-sm/[1.4] font-bold text-[#2A95D5] no-underline transition-colors duration-200 group-hover:text-[#E01A59]">See How-To <span class="inline-flex items-center transition-transform duration-200 group-hover:translate-x-1"><i class="fa-solid fa-arrow-right"></i></span></a>
</div>
<div class="group flex h-full flex-col gap-8 rounded-lg border border-[#E7EEF0] bg-white p-6 transition-all duration-200 hover:shadow-[0_4px_12px_0_rgb(24_24_24/0.08)]">
<span class="flex flex-col gap-4">
<span class="flex h-8 max-w-10 items-center justify-center text-[32px] text-[#678CB1]"><i class="fa-solid fa-graduation-cap"></i></span>
<span class="text-[15px]/[1.6] font-bold text-[#181818]">How to Redact Text and Regions in PDF</span>
</span>
<a href="/how-to/redact-text/" class="mt-auto flex items-center gap-2 text-sm/[1.4] font-bold text-[#2A95D5] no-underline transition-colors duration-200 group-hover:text-[#E01A59]">See How-To <span class="inline-flex items-center transition-transform duration-200 group-hover:translate-x-1"><i class="fa-solid fa-arrow-right"></i></span></a>
</div>
</div>
<div class="tutorials-navigation">
<a href="/how-to/create-new-pdfs/" class="tutorials-navigation__cta tutorials-navigation__cta--left"><i class="fa-solid fa-chevron-left"></i>Creating PDFs in C#</a>
<a href="/tutorials/csharp-edit-pdf-complete-tutorial/" class="tutorials-navigation__cta tutorials_navigation__cta--right">Editing PDFs in C#<i class="fa-solid fa-arrow-right"></i></a>
</div>
This complete tutorial covers strings, URLs, files, deployment, and scaling. To get started, install IronPDF from NuGet and call ChromePdfRenderer.RenderHtmlAsPdf(). Three lines of code would be enough to produce a pixel-perfect PDF. IronPDF's Chrome-based engine handles the rendering, deployment, and scaling limits that trip up simpler tools. If you are still choosing a library, compare all C# HTML to PDF libraries first.
TL;DR: Quickstart Guide to Convert HTML to PDF
You can easily convert HTML to PDF in C# using the IronPDF library, which provides the ChromePdfRenderer.RenderHtmlAsPdf method to create high-quality PDF files from HTML, CSS, and JavaScript.
new IronPdf.ChromePdfRenderer()
.RenderHtmlAsPdf("<p>Hello World</p>")
.SaveAs("pixelperfect.pdf");
C#
3Deploy to test on your live environment
Start using IronPDF in your project today with a free trial
All code in this guide was verified on IronPDF v2026.8.1 · .NET 10 · July 2026.
Why Convert HTML to PDF?
Converting HTML to PDF lets your team build documents with the web stack it already knows, rather than learning a separate PDF layout API. A few reasons it works well:
Reuse the design language you already know: Lay out documents in the HTML and CSS you write every day instead of a proprietary PDF drawing API.
Reuse existing web templates: The templates already behind your web app become PDF sources, so developers write less bespoke PDF code.
Clean split of work: Designers can own the look end-to-end while developers own rendering and wiring it into the application.
One pipeline, many document types: The same approach covers invoices, reports, receipts, and archives without a separate tool for each.
Why NET Developers Need an HTML to PDF Converter for C#
IronPDF leverages an embedded Google Chromium rendering engine to ensure high-fidelity conversions, accurately preserving the layout and styling of your web content.
✅ Robust Chrome Rendering Engine: uses Chrome's Blink engine for accurate HTML to PDF conversion.
✅ Pixel-Perfect Accuracy: generated PDFs match the web precisely, not a printer-friendly version.
✅ Full Modern Web Support: complete CSS3, HTML5, and JavaScript support for all HTML elements.
✅ 5-20x Performance Boost: significantly faster than browser automation or web drivers.
Please note: Latest in v2026.8.1 (June 2026): access to PDF Optional Content Groups (layers) with layer hierarchy and visibility metadata, a new CSS page-rule policy and header/footer overlap detection for cleaner margin handling, greater engine stability under heavy load and constrained-CPU environments, more accurate PDF redaction with corrected signature timestamps across daylight-saving changes, and clearer, actionable errors when PDF generation stalls. See the full changelog for the complete release history.
IronPDF gives .NET developers a straightforward way to turn their web application's HTML into professional-looking PDFs. From invoices and reports to certificates and archives, developers can work with their familiar web stack while IronPDF handles the complex in just a few lines of code.
Whether you're working with HTML strings, URLs, or HTML files, IronPDF gives you flexible options for producing high-quality PDFs.
In this tutorial, we will walk you through the most common scenarios, including HTML string to PDF, URL to PDF, and HTML file to PDF. Additionally, IronPDF also provides a variety of operations for manipulating PDF documents:
How to Convert HTML String to PDF
The most fundamental operation is HTML string to PDF. This method is perfect for dynamically generated HTML content. The RenderHtmlAsPdf method fully supports HTML5, CSS3, JavaScript, and images.
using IronPdf;// Create the Chrome renderervar renderer = new ChromePdfRenderer();// Convert HTML string to PDFvar pdf = renderer.RenderHtmlAsPdf("<h1>Hello IronPdf</h1>");// Save the PDFpdf.SaveAs("output.pdf");
using IronPdf;
// Create the Chrome renderer
var renderer = new ChromePdfRenderer();
// Convert HTML string to PDF
var pdf = renderer.RenderHtmlAsPdf("<h1>Hello IronPdf</h1>");
// Save the PDF
pdf.SaveAs("output.pdf");
ImportsIronPdf' Create the Chrome rendererDim renderer As New ChromePdfRenderer()' Convert HTML string to PDFDim pdf = renderer.RenderHtmlAsPdf("<h1>Hello IronPdf</h1>")' Save the PDFpdf.SaveAs("output.pdf")
Imports IronPdf
' Create the Chrome renderer
Dim renderer As New ChromePdfRenderer()
' Convert HTML string to PDF
Dim pdf = renderer.RenderHtmlAsPdf("<h1>Hello IronPdf</h1>")
' Save the PDF
pdf.SaveAs("output.pdf")
Output
Run the snippet above and IronPDF returns a one-page PDF holding exactly the heading you passed in, the simplest possible render:
Performance
The performance of IronPDF's conversion to PDF from string, URL, and HTML was measured using a Lenovo laptop with 16GB RAM. The test document is a 3-page enterprise invoice with standard CSS Grid, gradients and multi-section tables.
The results are as follows:
Metric
Value
Average render time
~486 ms
Memory per render
~3.6 MB
Measured across 5 successive renders on an 8-core / 16-thread laptop (Windows 11, .NET 8). The first call also includes one-time Chromium engine initialization (~1.3 s)
The first time I ran the test, render time was sluggish (Over a second per call!). After looking at what was happening, I realized I had several open Chromium instances running and was on battery power, neither of which let the library show its real speed. Once I closed the competing processes and plugged in, things sharpened up: warm runs averaged ~486 ms with the fastest landing near 473 ms.
Tips: Recent updates fix issues with special characters/emojis in HTML metadata and ensure better handling of html form fields, including Chinese characters on Linux. Test dynamic content with EnableJavaScript = true for optimal results.
When your HTML string references local assets like images or stylesheets, use the baseUrlOrPath parameter to properly convert HTML content with all resources:
using IronPdf;var renderer = new ChromePdfRenderer();// Convert HTML content with local image and CSS referencesstring html = @" <link rel='stylesheet' href='styles.css'> <img src='logo.png' alt='Company Logo'> <h1>Company Report</h1> <p>Annual report content...</p>";// Set base path for resolving relative URLs in HTML to PDF conversionvar pdf = renderer.RenderHtmlAsPdf(html, @"C:\MyProject\Assets\");pdf.SaveAs("report.pdf");
using IronPdf;
var renderer = new ChromePdfRenderer();
// Convert HTML content with local image and CSS references
string html = @"
<link rel='stylesheet' href='styles.css'>
<img src='logo.png' alt='Company Logo'>
<h1>Company Report</h1>
<p>Annual report content...</p>";
// Set base path for resolving relative URLs in HTML to PDF conversion
var pdf = renderer.RenderHtmlAsPdf(html, @"C:\MyProject\Assets\");
pdf.SaveAs("report.pdf");
ImportsIronPdfDim renderer As New ChromePdfRenderer()' Convert HTML content with local image and CSS referencesDim html AsString = " <link rel='stylesheet' href='styles.css'> <img src='logo.png' alt='Company Logo'> <h1>Company Report</h1> <p>Annual report content...</p>"' Set base path for resolving relative URLs in HTML to PDF conversionDim pdf = renderer.RenderHtmlAsPdf(html, "C:\MyProject\Assets\")pdf.SaveAs("report.pdf")
Imports IronPdf
Dim renderer As New ChromePdfRenderer()
' Convert HTML content with local image and CSS references
Dim html As String = "
<link rel='stylesheet' href='styles.css'>
<img src='logo.png' alt='Company Logo'>
<h1>Company Report</h1>
<p>Annual report content...</p>"
' Set base path for resolving relative URLs in HTML to PDF conversion
Dim pdf = renderer.RenderHtmlAsPdf(html, "C:\MyProject\Assets\")
pdf.SaveAs("report.pdf")
Tips: baseUrlOrPath tells IronPDF where to find your CSS, JavaScript, and image files. All relative paths in your HTML string will be resolved from this directory.
Warning: One issue to keep an eye out for, and why testing the output is important regardless of what library you use for automated document generation, is that the enterprise document may have broken elements or missing assets when references default back to system settings. IronPDF gives you the baseUrlOrPath parameter to point relative paths at the right directory, so a quick output check before bulk runs is usually all you need to catch it.
Rendering entire web pages to PDFs with C# enables teams to separate PDF design and back-end rendering work. This approach lets you convert any specified URL directly to PDF format.
The core method is RenderUrlAsPdf, which fetches a live page and renders it in a single call:
using IronPdf;// Create a PDF from any existing web pagevar renderer = new ChromePdfRenderer();var pdf = renderer.RenderUrlAsPdf("https://en.wikipedia.org/wiki/PDF");pdf.SaveAs("wikipedia.pdf");
using IronPdf;
// Create a PDF from any existing web page
var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderUrlAsPdf("https://en.wikipedia.org/wiki/PDF");
pdf.SaveAs("wikipedia.pdf");
ImportsIronPdf' Create a PDF from any existing web pagePrivate renderer = New ChromePdfRenderer()Private pdf = renderer.RenderUrlAsPdf("https://en.wikipedia.org/wiki/PDF")pdf.SaveAs("wikipedia.pdf")
Imports IronPdf
' Create a PDF from any existing web page
Private renderer = New ChromePdfRenderer()
Private pdf = renderer.RenderUrlAsPdf("https://en.wikipedia.org/wiki/PDF")
pdf.SaveAs("wikipedia.pdf")
Output
Here RenderUrlAsPdf captures a live Wikipedia article into a static, print-ready PDF, with text, images, tables, and layout preserved across all 33 pages:
Print vs Screen CSS
You can configure IronPDF to render using either CSS media type.
using IronPdf;using IronPdf.Rendering;// Initialize HTML to PDF convertervar renderer = new ChromePdfRenderer();// Configure CSS media type for rendering specified URLsrenderer.RenderingOptions.CssMediaType = PdfCssMediaType.Print;// Screen media type shows the entire web page as displayed on screen
using IronPdf;
using IronPdf.Rendering;
// Initialize HTML to PDF converter
var renderer = new ChromePdfRenderer();
// Configure CSS media type for rendering specified URLs
renderer.RenderingOptions.CssMediaType = PdfCssMediaType.Print;
// Screen media type shows the entire web page as displayed on screen
ImportsIronPdfImportsIronPdf.Rendering' Initialize HTML to PDF converterDim renderer As New ChromePdfRenderer()' Configure CSS media type for rendering specified URLsrenderer.RenderingOptions.CssMediaType = PdfCssMediaType.Print' Screen media type shows the entire web page as displayed on screen
Imports IronPdf
Imports IronPdf.Rendering
' Initialize HTML to PDF converter
Dim renderer As New ChromePdfRenderer()
' Configure CSS media type for rendering specified URLs
renderer.RenderingOptions.CssMediaType = PdfCssMediaType.Print
' Screen media type shows the entire web page as displayed on screen
JavaScript Support
IronPDF fully supports JavaScript, jQuery, and even AJAX. For dynamic content, you can configure IronPDF to wait for JavaScript to finish before rendering. This is perfect for single-page applications and dynamic websites.
using IronPdf;// Configure JavaScript rendering for dynamic HTML content to PDFvar renderer = new ChromePdfRenderer();// Enable JavaScript execution during PDF generationrenderer.RenderingOptions.EnableJavaScript = true;// WaitFor.RenderDelay pauses before capturing the HTMLrenderer.RenderingOptions.WaitFor.RenderDelay(500); // milliseconds
using IronPdf;
// Configure JavaScript rendering for dynamic HTML content to PDF
var renderer = new ChromePdfRenderer();
// Enable JavaScript execution during PDF generation
renderer.RenderingOptions.EnableJavaScript = true;
// WaitFor.RenderDelay pauses before capturing the HTML
renderer.RenderingOptions.WaitFor.RenderDelay(500); // milliseconds
ImportsIronPdf' Configure JavaScript rendering for dynamic HTML content to PDFDim renderer As New ChromePdfRenderer()' Enable JavaScript execution during PDF generationrenderer.RenderingOptions.EnableJavaScript = True' WaitFor.RenderDelay pauses before capturing the HTMLrenderer.RenderingOptions.WaitFor.RenderDelay(500) ' milliseconds
Imports IronPdf
' Configure JavaScript rendering for dynamic HTML content to PDF
Dim renderer As New ChromePdfRenderer()
' Enable JavaScript execution during PDF generation
renderer.RenderingOptions.EnableJavaScript = True
' WaitFor.RenderDelay pauses before capturing the HTML
renderer.RenderingOptions.WaitFor.RenderDelay(500) ' milliseconds
JavaScript execution can also be shown when rendering an advanced d3.js chord chart from a web page to PDF format:
using IronPdf;// Create renderer for JavaScript-heavy HTMLvar renderer = new ChromePdfRenderer();// Convert d3.js visualization web page to PDFvar pdf = renderer.RenderUrlAsPdf("https://observablehq.com/@d3/chord-diagram");// Save the interactive chart as static PDFpdf.SaveAs("chart.pdf");
using IronPdf;
// Create renderer for JavaScript-heavy HTML
var renderer = new ChromePdfRenderer();
// Convert d3.js visualization web page to PDF
var pdf = renderer.RenderUrlAsPdf("https://observablehq.com/@d3/chord-diagram");
// Save the interactive chart as static PDF
pdf.SaveAs("chart.pdf");
ImportsIronPdf' Create renderer for JavaScript-heavy HTMLDim renderer As New ChromePdfRenderer()' Convert d3.js visualization web page to PDFDim pdf = renderer.RenderUrlAsPdf("https://observablehq.com/@d3/chord-diagram")' Save the interactive chart as static PDFpdf.SaveAs("chart.pdf")
Imports IronPdf
' Create renderer for JavaScript-heavy HTML
Dim renderer As New ChromePdfRenderer()
' Convert d3.js visualization web page to PDF
Dim pdf = renderer.RenderUrlAsPdf("https://observablehq.com/@d3/chord-diagram")
' Save the interactive chart as static PDF
pdf.SaveAs("chart.pdf")
Responsive CSS
As responsive web pages are designed to be viewed in a browser, and IronPDF does not open a real browser window in your server's OS, responsive HTML elements may render at their smallest size. PdfCssMediaType.Print is recommended to navigate this issue when rendering entire web pages.
// Configure for optimal responsive design handling in HTML to PDFrenderer.RenderingOptions.CssMediaType = IronPdf.Rendering.PdfCssMediaType.Print;
// Configure for optimal responsive design handling in HTML to PDF
renderer.RenderingOptions.CssMediaType = IronPdf.Rendering.PdfCssMediaType.Print;
Converting local HTML files to PDF preserves all relative assets including CSS, images, and JavaScript, as if opened using the file:// protocol. This method is best for converting templates or pre-designed HTML pages.
using IronPdf;// Initialize ChromePdfRenderer for HTML file conversionvar renderer = new ChromePdfRenderer();// Convert HTML file to PDF documents// Preserves all relative paths and linked resources in HTMLvar pdf = renderer.RenderHtmlFileAsPdf("Assets/TestInvoice1.html");// Save the HTML file as PDF pdf.SaveAs("Invoice.pdf");// All CSS, JavaScript, and images load correctly in the generated PDF
using IronPdf;
// Initialize ChromePdfRenderer for HTML file conversion
var renderer = new ChromePdfRenderer();
// Convert HTML file to PDF documents
// Preserves all relative paths and linked resources in HTML
var pdf = renderer.RenderHtmlFileAsPdf("Assets/TestInvoice1.html");
// Save the HTML file as PDF
pdf.SaveAs("Invoice.pdf");
// All CSS, JavaScript, and images load correctly in the generated PDF
ImportsIronPdf' Initialize ChromePdfRenderer for HTML file conversionDim renderer As New ChromePdfRenderer()' Convert HTML file to PDF documents' Preserves all relative paths and linked resources in HTMLDim pdf = renderer.RenderHtmlFileAsPdf("Assets/TestInvoice1.html")' Save the HTML file as PDF pdf.SaveAs("Invoice.pdf")' All CSS, JavaScript, and images load correctly in the generated PDF
Imports IronPdf
' Initialize ChromePdfRenderer for HTML file conversion
Dim renderer As New ChromePdfRenderer()
' Convert HTML file to PDF documents
' Preserves all relative paths and linked resources in HTML
Dim pdf = renderer.RenderHtmlFileAsPdf("Assets/TestInvoice1.html")
' Save the HTML file as PDF
pdf.SaveAs("Invoice.pdf")
' All CSS, JavaScript, and images load correctly in the generated PDF
Output
Point RenderHtmlFileAsPdf at an HTML invoice template and the file's full design (logo, line-item table, totals) comes through pixel-perfect, with no extra code on your side:
Performance
Performance was measured again by keeping all variables constant to render the previous 3-page enterprise invoice from a file on disk:
Metric
Value
Average render time
~502 ms
Memory per render
~3.1 MB
Measured across 5 successive renders on the same 8-core / 16-thread laptop (Windows 11, .NET 8). File-based rendering matches in-memory string rendering within about 3%; reading the HTML from disk adds no measurable overhead.
Tips: Keep your HTML files in a separate folder with their assets (CSS, images) to edit and test in a browser before converting HTML file to PDF. This ensures your HTML renders perfectly for high quality PDF documents.
If your ASP.NET Core project already uses Razor Pages, you can convert them directly to PDF without rebuilding your HTML. IronPDF's Razor extension adds the RenderRazorToPdf method, which takes your .cshtml page (complete with its model and layout) and renders it as a PDF document in a single call.
PM > Install-Package IronPdf.Extensions.Razor
Install-Package IronPdf.Extensions.Razor
using IronPdf;using Microsoft.AspNetCore.Mvc;using Microsoft.AspNetCore.Mvc.RazorPages;public class ReportModel : PageModel{ public IActionResultOnGet() { var renderer = new ChromePdfRenderer(); // Render a Razor Page directly to PDF PdfDocument pdf = renderer.RenderRazorToPdf(this);Response.Headers.Add("Content-Disposition", "inline"); return new FileContentResult(pdf.BinaryData, "application/pdf"); }}
using IronPdf;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
public class ReportModel : PageModel
{
public IActionResult OnGet()
{
var renderer = new ChromePdfRenderer();
// Render a Razor Page directly to PDF
PdfDocument pdf = renderer.RenderRazorToPdf(this);
Response.Headers.Add("Content-Disposition", "inline");
return new FileContentResult(pdf.BinaryData, "application/pdf");
}
}
ImportsIronPdfImportsMicrosoft.AspNetCore.MvcImportsMicrosoft.AspNetCore.Mvc.RazorPagesPublic Class ReportModelInheritsPageModel Public Function OnGet() AsIActionResult Dim renderer As New ChromePdfRenderer() ' Render a Razor Page directly to PDF Dim pdf AsPdfDocument = renderer.RenderRazorToPdf(Me) Response.Headers.Add("Content-Disposition", "inline") Return New FileContentResult(pdf.BinaryData, "application/pdf") End FunctionEnd Class
Imports IronPdf
Imports Microsoft.AspNetCore.Mvc
Imports Microsoft.AspNetCore.Mvc.RazorPages
Public Class ReportModel
Inherits PageModel
Public Function OnGet() As IActionResult
Dim renderer As New ChromePdfRenderer()
' Render a Razor Page directly to PDF
Dim pdf As PdfDocument = renderer.RenderRazorToPdf(Me)
Response.Headers.Add("Content-Disposition", "inline")
Return New FileContentResult(pdf.BinaryData, "application/pdf")
End Function
End Class
Please note: RenderRazorToPdf requires an ASP.NET Core Web App project. It will not work in console applications or class libraries; the Razor view engine must be available in the hosting pipeline.
Teams using the MVC pattern can generate PDFs straight from their existing Views and controllers. Install the MVC Core extension package, then call RenderRazorViewToPdf with your view path and model; IronPDF handles the Razor rendering pipeline and outputs a finished PDF.
This is especially useful for reports, invoices, and any page where the HTML is already designed and tested in the browser. The generated PDF preserves the full View output, including layout pages and partial views.
PM > Install-Package IronPdf.Extensions.Mvc.Core
Install-Package IronPdf.Extensions.Mvc.Core
First, register the IRazorViewRenderer service in your Program.cs so your controllers can inject it:
using IronPdf.Extensions.Mvc.Core;var builder = WebApplication.CreateBuilder(args);builder.Services.AddControllersWithViews();// Register the Razor view renderer for IronPDFbuilder.Services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();builder.Services.AddSingleton<IRazorViewRenderer, RazorViewRenderer>();
using IronPdf.Extensions.Mvc.Core;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllersWithViews();
// Register the Razor view renderer for IronPDF
builder.Services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
builder.Services.AddSingleton<IRazorViewRenderer, RazorViewRenderer>();
ImportsIronPdf.Extensions.Mvc.CoreDim builder = WebApplication.CreateBuilder(args)builder.Services.AddControllersWithViews()' Register the Razor view renderer for IronPDFbuilder.Services.AddSingleton(OfIHttpContextAccessor, HttpContextAccessor)()builder.Services.AddSingleton(OfIRazorViewRenderer, RazorViewRenderer)()
Imports IronPdf.Extensions.Mvc.Core
Dim builder = WebApplication.CreateBuilder(args)
builder.Services.AddControllersWithViews()
' Register the Razor view renderer for IronPDF
builder.Services.AddSingleton(Of IHttpContextAccessor, HttpContextAccessor)()
builder.Services.AddSingleton(Of IRazorViewRenderer, RazorViewRenderer)()
Then in your controller action, inject the renderer and convert any View to PDF:
using IronPdf;using IronPdf.Extensions.Mvc.Core;using Microsoft.AspNetCore.Mvc;public class ReportController : Controller{ private readonly IRazorViewRenderer _viewRenderService; // Inject the view renderer via constructor publicReportController(IRazorViewRenderer viewRenderService) { _viewRenderService = viewRenderService; } public IActionResultDownload() { var reportModel = new { Title = "Quarterly Report", Total = 1250.00 }; var renderer = new ChromePdfRenderer(); // Render an MVC View with model data to PDF PdfDocument pdf = renderer.RenderRazorViewToPdf( _viewRenderService, "Views/Home/Report.cshtml", reportModel);Response.Headers.Add("Content-Disposition", "inline"); return new FileContentResult(pdf.BinaryData, "application/pdf"); }}
using IronPdf;
using IronPdf.Extensions.Mvc.Core;
using Microsoft.AspNetCore.Mvc;
public class ReportController : Controller
{
private readonly IRazorViewRenderer _viewRenderService;
// Inject the view renderer via constructor
public ReportController(IRazorViewRenderer viewRenderService)
{
_viewRenderService = viewRenderService;
}
public IActionResult Download()
{
var reportModel = new { Title = "Quarterly Report", Total = 1250.00 };
var renderer = new ChromePdfRenderer();
// Render an MVC View with model data to PDF
PdfDocument pdf = renderer.RenderRazorViewToPdf(
_viewRenderService, "Views/Home/Report.cshtml", reportModel);
Response.Headers.Add("Content-Disposition", "inline");
return new FileContentResult(pdf.BinaryData, "application/pdf");
}
}
ImportsIronPdfImportsIronPdf.Extensions.Mvc.CoreImportsMicrosoft.AspNetCore.MvcPublic Class ReportControllerInheritsController PrivateReadOnly _viewRenderService AsIRazorViewRenderer ' Inject the view renderer via constructor Public Sub New(viewRenderService AsIRazorViewRenderer) _viewRenderService = viewRenderService End Sub Public Function Download() AsIActionResult Dim reportModel = New With {.Title = "Quarterly Report", .Total = 1250.0} Dim renderer = New ChromePdfRenderer() ' Render an MVC View with model data to PDF Dim pdf AsPdfDocument = renderer.RenderRazorViewToPdf(_viewRenderService, "Views/Home/Report.cshtml", reportModel) Response.Headers.Add("Content-Disposition", "inline") Return New FileContentResult(pdf.BinaryData, "application/pdf") End FunctionEnd Class
Imports IronPdf
Imports IronPdf.Extensions.Mvc.Core
Imports Microsoft.AspNetCore.Mvc
Public Class ReportController
Inherits Controller
Private ReadOnly _viewRenderService As IRazorViewRenderer
' Inject the view renderer via constructor
Public Sub New(viewRenderService As IRazorViewRenderer)
_viewRenderService = viewRenderService
End Sub
Public Function Download() As IActionResult
Dim reportModel = New With {.Title = "Quarterly Report", .Total = 1250.0}
Dim renderer = New ChromePdfRenderer()
' Render an MVC View with model data to PDF
Dim pdf As PdfDocument = renderer.RenderRazorViewToPdf(_viewRenderService, "Views/Home/Report.cshtml", reportModel)
Response.Headers.Add("Content-Disposition", "inline")
Return New FileContentResult(pdf.BinaryData, "application/pdf")
End Function
End Class
Do you need your dynamic web page preserved and converted to PDFs while preserving the exact layout and formatting? Look no further than IronPDF, which quickly converts a variety of popular dynamic web page frameworks to PDFs.
PDF from ASPX Pages
Here's a brief code snippet on converting ASPX Pages as PDF in Active Server Pages.
using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;using IronPdf;namespace AspxToPdfTutorial{ public partial class Invoice : System.Web.UI.Page { protected voidPage_Load(object sender, EventArgs e) {IronPdf.AspxToPdf.RenderThisPageAsPdf(IronPdf.AspxToPdf.FileBehavior.InBrowser); } }}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using IronPdf;
namespace AspxToPdfTutorial
{
public partial class Invoice : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
IronPdf.AspxToPdf.RenderThisPageAsPdf(IronPdf.AspxToPdf.FileBehavior.InBrowser);
}
}
}
ImportsSystemImportsSystem.Collections.GenericImportsSystem.LinqImportsSystem.WebImportsSystem.Web.UIImportsSystem.Web.UI.WebControlsImportsIronPdfNamespaceAspxToPdfTutorialPartialPublic Class InvoiceInheritsSystem.Web.UI.PageProtected Sub Page_Load(ByVal sender AsObject, ByVal e AsEventArgs)IronPdf.AspxToPdf.RenderThisPageAsPdf(IronPdf.AspxToPdf.FileBehavior.InBrowser) End Sub End ClassEndNamespace
Imports System
Imports System.Collections.Generic
Imports System.Linq
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports IronPdf
Namespace AspxToPdfTutorial
Partial Public Class Invoice
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
IronPdf.AspxToPdf.RenderThisPageAsPdf(IronPdf.AspxToPdf.FileBehavior.InBrowser)
End Sub
End Class
End Namespace
For a more detailed explanation of this code snippet and to explore its additional functionality, please refer to our comprehensive how-to guide.
XAML to PDF (MAUI)
For developers looking to build cross-platform applications, .NET MAUI is a popular choice among the frameworks. IronPDF fully supports converting XAML to PDF with a few steps.
using IronPdf.Extensions.Maui;namespace mauiSample;public partial class MainPage : ContentPage{ publicMainPage() {InitializeComponent(); } private voidPrintToPdf(object sender, EventArgs e) { ChromePdfRenderer renderer = new ChromePdfRenderer(); // Apply HTML header renderer.RenderingOptions.HtmlHeader = new HtmlHeaderFooter() {HtmlFragment = "<h1>Header</h1>", }; // Render PDF from Maui Page PdfDocument pdf = renderer.RenderContentPageToPdf<MainPage, App>().Result; pdf.SaveAs(@"C:\Users\lyty1\Downloads\contentPageToPdf.pdf"); }}
using IronPdf.Extensions.Maui;
namespace mauiSample;
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
}
private void PrintToPdf(object sender, EventArgs e)
{
ChromePdfRenderer renderer = new ChromePdfRenderer();
// Apply HTML header
renderer.RenderingOptions.HtmlHeader = new HtmlHeaderFooter()
{
HtmlFragment = "<h1>Header</h1>",
};
// Render PDF from Maui Page
PdfDocument pdf = renderer.RenderContentPageToPdf<MainPage, App>().Result;
pdf.SaveAs(@"C:\Users\lyty1\Downloads\contentPageToPdf.pdf");
}
}
ImportsIronPdf.Extensions.MauiNamespace mauiSamplePartialPublic Class MainPageInheritsContentPage Public Sub New()InitializeComponent() End Sub Private Sub PrintToPdf(ByVal sender AsObject, ByVal e AsEventArgs) Dim renderer As New ChromePdfRenderer() ' Apply HTML header renderer.RenderingOptions.HtmlHeader = New HtmlHeaderFooter() With {.HtmlFragment = "<h1>Header</h1>"} ' Render PDF from Maui Page Dim pdf AsPdfDocument = renderer.RenderContentPageToPdf(OfMainPage, App)().Result pdf.SaveAs("C:\Users\lyty1\Downloads\contentPageToPdf.pdf") End Sub End ClassEndNamespace
Imports IronPdf.Extensions.Maui
Namespace mauiSample
Partial Public Class MainPage
Inherits ContentPage
Public Sub New()
InitializeComponent()
End Sub
Private Sub PrintToPdf(ByVal sender As Object, ByVal e As EventArgs)
Dim renderer As New ChromePdfRenderer()
' Apply HTML header
renderer.RenderingOptions.HtmlHeader = New HtmlHeaderFooter() With {.HtmlFragment = "<h1>Header</h1>"}
' Render PDF from Maui Page
Dim pdf As PdfDocument = renderer.RenderContentPageToPdf(Of MainPage, App)().Result
pdf.SaveAs("C:\Users\lyty1\Downloads\contentPageToPdf.pdf")
End Sub
End Class
End Namespace
For a more detailed explanation of this code snippet and to explore its additional functionality, please refer to our comprehensive how-to guide.
Generate PDF Reports
When it comes to generating PDF Reports, the exact dimensions and format are crucial. As such, IronPDF allows you to generate PDFs seamlessly with only a couple of steps.
using IronPdf;ChromePdfRenderer renderer = new ChromePdfRenderer();renderer.RenderHtmlFileAsPdf("report.html").SaveAs("report.pdf");
using IronPdf;
ChromePdfRenderer renderer = new ChromePdfRenderer();
renderer.RenderHtmlFileAsPdf("report.html").SaveAs("report.pdf");
ImportsIronPdfPrivate renderer As New ChromePdfRenderer()renderer.RenderHtmlFileAsPdf("report.html").SaveAs("report.pdf")
Imports IronPdf
Private renderer As New ChromePdfRenderer()
renderer.RenderHtmlFileAsPdf("report.html").SaveAs("report.pdf")
For a more detailed explanation of this code snippet and to explore its additional functionality, please refer to our comprehensive how-to guide.
Create PDFs in Blazor Servers
IronPDF supports .NET 6, and as it includes project types like Blazor, this code snippet provides a brief example of how to create PDFs in Blazor Server.
@code { // Model to bind user input private InputHTMLModel _InputMsgModel = new InputHTMLModel(); private async TaskSubmitHTML() { // Set your IronPDF license keyIronPdf.License.LicenseKey = "IRONPDF-MYLICENSE-KEY-1EF01"; // Create a renderer to convert HTML to PDF var render = new IronPdf.ChromePdfRenderer(); // Render the HTML input into a PDF document var doc = render.RenderHtmlAsPdf(_InputMsgModel.HTML); var fileName = "iron.pdf"; // Create a stream reference for the PDF content using var streamRef = new DotNetStreamReference(stream: doc.Stream); // Invoke JavaScript function to download the PDF in the browser awaitJS.InvokeVoidAsync("SubmitHTML", fileName, streamRef); } public class InputHTMLModel { public stringHTML { get; set; } = "My new message"; }}
@code {
// Model to bind user input
private InputHTMLModel _InputMsgModel = new InputHTMLModel();
private async Task SubmitHTML()
{
// Set your IronPDF license key
IronPdf.License.LicenseKey = "IRONPDF-MYLICENSE-KEY-1EF01";
// Create a renderer to convert HTML to PDF
var render = new IronPdf.ChromePdfRenderer();
// Render the HTML input into a PDF document
var doc = render.RenderHtmlAsPdf(_InputMsgModel.HTML);
var fileName = "iron.pdf";
// Create a stream reference for the PDF content
using var streamRef = new DotNetStreamReference(stream: doc.Stream);
// Invoke JavaScript function to download the PDF in the browser
await JS.InvokeVoidAsync("SubmitHTML", fileName, streamRef);
}
public class InputHTMLModel
{
public string HTML { get; set; } = "My new message";
}
}
codeIf True Then ' Model to bind user input privateInputHTMLModel _InputMsgModel = New InputHTMLModel()'INSTANT VB TODO TASK: Local functions are not converted by Instant VB:' private async Task SubmitHTML()' {' ' Set your IronPDF license key' IronPdf.License.LicenseKey = "IRONPDF-MYLICENSE-KEY-1EF01";'' ' Create a renderer to convert HTML to PDF' var render = New IronPdf.ChromePdfRenderer();'' ' Render the HTML input into a PDF document' var doc = render.RenderHtmlAsPdf(_InputMsgModel.HTML);'' var fileName = "iron.pdf";'' ' Create a stream reference for the PDF content' var streamRef = New DotNetStreamReference(stream: doc.Stream);'' ' Invoke JavaScript function to download the PDF in the browser' await JS.InvokeVoidAsync("SubmitHTML", fileName, streamRef);' }'INSTANT VB TODO TASK: Local functions are not converted by Instant VB:' public class InputHTMLModel' {' public string HTML' {' get;' set;' } = "My new message";' }End If
code
If True Then
' Model to bind user input
private InputHTMLModel _InputMsgModel = New InputHTMLModel()
'INSTANT VB TODO TASK: Local functions are not converted by Instant VB:
' private async Task SubmitHTML()
' {
' ' Set your IronPDF license key
' IronPdf.License.LicenseKey = "IRONPDF-MYLICENSE-KEY-1EF01";
'
' ' Create a renderer to convert HTML to PDF
' var render = New IronPdf.ChromePdfRenderer();
'
' ' Render the HTML input into a PDF document
' var doc = render.RenderHtmlAsPdf(_InputMsgModel.HTML);
'
' var fileName = "iron.pdf";
'
' ' Create a stream reference for the PDF content
' var streamRef = New DotNetStreamReference(stream: doc.Stream);
'
' ' Invoke JavaScript function to download the PDF in the browser
' await JS.InvokeVoidAsync("SubmitHTML", fileName, streamRef);
' }
'INSTANT VB TODO TASK: Local functions are not converted by Instant VB:
' public class InputHTMLModel
' {
' public string HTML
' {
' get;
' set;
' } = "My new message";
' }
End If
For a more detailed explanation of this code snippet and to explore its additional functionality, please refer to our comprehensive how-to guide.
Razor to PDF (Blazor Servers)
Aside from creating PDFs in Blazor Servers, IronPDF also supports generating PDF documents from Razor components within a Blazor page. Making the creation of PDF files and pages much more streamlined.
[Parameter]publicIEnumerable<PersonInfo> persons { get; set; }publicDictionary<string, object> Parameters { get; set; } = new Dictionary<string, object>();protected override async TaskOnInitializedAsync(){ persons = new List<PersonInfo> { new PersonInfo { Name = "Alice", Title = "Mrs.", Description = "Software Engineer" }, new PersonInfo { Name = "Bob", Title = "Mr.", Description = "Software Engineer" }, new PersonInfo { Name = "Charlie", Title = "Mr.", Description = "Software Engineer" } };}private async voidPrintToPdf(){ ChromePdfRenderer renderer = new ChromePdfRenderer(); // Apply text footer renderer.RenderingOptions.TextFooter = new TextHeaderFooter() {LeftText = "{date} - {time}",DrawDividerLine = true,RightText = "Page {page} of {total-pages}",Font = IronSoftware.Drawing.FontTypes.Arial,FontSize = 11 };Parameters.Add("persons", persons); // Render razor component to PDF PdfDocument pdf = renderer.RenderRazorComponentToPdf<Person>(Parameters);File.WriteAllBytes("razorComponentToPdf.pdf", pdf.BinaryData);}
[Parameter]
public IEnumerable<PersonInfo> persons { get; set; }
public Dictionary<string, object> Parameters { get; set; } = new Dictionary<string, object>();
protected override async Task OnInitializedAsync()
{
persons = new List<PersonInfo>
{
new PersonInfo { Name = "Alice", Title = "Mrs.", Description = "Software Engineer" },
new PersonInfo { Name = "Bob", Title = "Mr.", Description = "Software Engineer" },
new PersonInfo { Name = "Charlie", Title = "Mr.", Description = "Software Engineer" }
};
}
private async void PrintToPdf()
{
ChromePdfRenderer renderer = new ChromePdfRenderer();
// Apply text footer
renderer.RenderingOptions.TextFooter = new TextHeaderFooter()
{
LeftText = "{date} - {time}",
DrawDividerLine = true,
RightText = "Page {page} of {total-pages}",
Font = IronSoftware.Drawing.FontTypes.Arial,
FontSize = 11
};
Parameters.Add("persons", persons);
// Render razor component to PDF
PdfDocument pdf = renderer.RenderRazorComponentToPdf<Person>(Parameters);
File.WriteAllBytes("razorComponentToPdf.pdf", pdf.BinaryData);
}
<Parameter>Public Property persons AsIEnumerable(OfPersonInfo)Public Property ParametersAsDictionary(OfString, Object) = New Dictionary(OfString, Object)()ProtectedOverridesAsync Function OnInitializedAsync() AsTask persons = New List(OfPersonInfo) From { New PersonInfoWith {.Name = "Alice", .Title = "Mrs.", .Description = "Software Engineer"}, New PersonInfoWith {.Name = "Bob", .Title = "Mr.", .Description = "Software Engineer"}, New PersonInfoWith {.Name = "Charlie", .Title = "Mr.", .Description = "Software Engineer"} }End FunctionPrivateAsync Sub PrintToPdf() Dim renderer As New ChromePdfRenderer() ' Apply text footer renderer.RenderingOptions.TextFooter = New TextHeaderFooter() With { .LeftText = "{date} - {time}", .DrawDividerLine = True, .RightText = "Page {page} of {total-pages}", .Font = IronSoftware.Drawing.FontTypes.Arial, .FontSize = 11 }Parameters.Add("persons", persons) ' Render razor component to PDF Dim pdf AsPdfDocument = renderer.RenderRazorComponentToPdf(OfPerson)(Parameters)File.WriteAllBytes("razorComponentToPdf.pdf", pdf.BinaryData)End Sub
<Parameter>
Public Property persons As IEnumerable(Of PersonInfo)
Public Property Parameters As Dictionary(Of String, Object) = New Dictionary(Of String, Object)()
Protected Overrides Async Function OnInitializedAsync() As Task
persons = New List(Of PersonInfo) From {
New PersonInfo With {.Name = "Alice", .Title = "Mrs.", .Description = "Software Engineer"},
New PersonInfo With {.Name = "Bob", .Title = "Mr.", .Description = "Software Engineer"},
New PersonInfo With {.Name = "Charlie", .Title = "Mr.", .Description = "Software Engineer"}
}
End Function
Private Async Sub PrintToPdf()
Dim renderer As New ChromePdfRenderer()
' Apply text footer
renderer.RenderingOptions.TextFooter = New TextHeaderFooter() With {
.LeftText = "{date} - {time}",
.DrawDividerLine = True,
.RightText = "Page {page} of {total-pages}",
.Font = IronSoftware.Drawing.FontTypes.Arial,
.FontSize = 11
}
Parameters.Add("persons", persons)
' Render razor component to PDF
Dim pdf As PdfDocument = renderer.RenderRazorComponentToPdf(Of Person)(Parameters)
File.WriteAllBytes("razorComponentToPdf.pdf", pdf.BinaryData)
End Sub
For a more detailed explanation of this code snippet and to explore its additional functionality, please refer to our comprehensive how-to guide.
CSHTML to PDF
Converting CSHTML (Razor) to PDF allows you to generate professional, print-ready documents directly from your web applications. This is useful for invoices, reports, contracts, or any dynamic content. IronPDF supports Razor Pages, MVC Core, and MVC Framework, as well as headless rendering, making it seamless to integrate PDF generation into your .NET applications with just a few lines of code.
CSHTML to PDF (Razor Pages)
using IronPdf.Razor.Pages;public IActionResultOnPostAsync(){ persons = new List<Person> { new Person { Name = "Alice", Title = "Mrs.", Description = "Software Engineer" }, new Person { Name = "Bob", Title = "Mr.", Description = "Software Engineer" }, new Person { Name = "Charlie", Title = "Mr.", Description = "Software Engineer" } };ViewData["personList"] = persons; ChromePdfRenderer renderer = new ChromePdfRenderer(); // Render Razor Page to PDF document PdfDocument pdf = renderer.RenderRazorToPdf(this);Response.Headers.Add("Content-Disposition", "inline"); returnFile(pdf.BinaryData, "application/pdf", "razorPageToPdf.pdf");}
using IronPdf.Razor.Pages;
public IActionResult OnPostAsync()
{
persons = new List<Person>
{
new Person { Name = "Alice", Title = "Mrs.", Description = "Software Engineer" },
new Person { Name = "Bob", Title = "Mr.", Description = "Software Engineer" },
new Person { Name = "Charlie", Title = "Mr.", Description = "Software Engineer" }
};
ViewData["personList"] = persons;
ChromePdfRenderer renderer = new ChromePdfRenderer();
// Render Razor Page to PDF document
PdfDocument pdf = renderer.RenderRazorToPdf(this);
Response.Headers.Add("Content-Disposition", "inline");
return File(pdf.BinaryData, "application/pdf", "razorPageToPdf.pdf");
}
ImportsIronPdf.Razor.PagesPublic Function OnPostAsync() AsIActionResult persons = New List(OfPerson) From { New PersonWith {.Name = "Alice", .Title = "Mrs.", .Description = "Software Engineer"}, New PersonWith {.Name = "Bob", .Title = "Mr.", .Description = "Software Engineer"}, New PersonWith {.Name = "Charlie", .Title = "Mr.", .Description = "Software Engineer"} }ViewData("personList") = persons Dim renderer As New ChromePdfRenderer() ' Render Razor Page to PDF document Dim pdf AsPdfDocument = renderer.RenderRazorToPdf(Me) Response.Headers.Add("Content-Disposition", "inline") ReturnFile(pdf.BinaryData, "application/pdf", "razorPageToPdf.pdf")End Function
Imports IronPdf.Razor.Pages
Public Function OnPostAsync() As IActionResult
persons = New List(Of Person) From {
New Person With {.Name = "Alice", .Title = "Mrs.", .Description = "Software Engineer"},
New Person With {.Name = "Bob", .Title = "Mr.", .Description = "Software Engineer"},
New Person With {.Name = "Charlie", .Title = "Mr.", .Description = "Software Engineer"}
}
ViewData("personList") = persons
Dim renderer As New ChromePdfRenderer()
' Render Razor Page to PDF document
Dim pdf As PdfDocument = renderer.RenderRazorToPdf(Me)
Response.Headers.Add("Content-Disposition", "inline")
Return File(pdf.BinaryData, "application/pdf", "razorPageToPdf.pdf")
End Function
For a more detailed explanation of this code snippet and to explore its additional functionality, please refer to our comprehensive how-to guide.
CSHTML to PDF (MVC Core)
public async Task<IActionResult> Persons(){ var persons = new List<Person> { new Person { Name = "Alice", Title = "Mrs.", Description = "Software Engineer" }, new Person { Name = "Bob", Title = "Mr.", Description = "Software Engineer" }, new Person { Name = "Charlie", Title = "Mr.", Description = "Software Engineer" } }; if (_httpContextAccessor.HttpContext.Request.Method == HttpMethod.Post.Method) { ChromePdfRenderer renderer = new ChromePdfRenderer(); // Render View to PDF document PdfDocument pdf = renderer.RenderRazorViewToPdf(_viewRenderService, "Views/Home/Persons.cshtml", persons);Response.Headers.Add("Content-Disposition", "inline"); // Output PDF document returnFile(pdf.BinaryData, "application/pdf", "viewToPdfMVCCore.pdf"); } returnView(persons);}
public async Task<IActionResult> Persons()
{
var persons = new List<Person>
{
new Person { Name = "Alice", Title = "Mrs.", Description = "Software Engineer" },
new Person { Name = "Bob", Title = "Mr.", Description = "Software Engineer" },
new Person { Name = "Charlie", Title = "Mr.", Description = "Software Engineer" }
};
if (_httpContextAccessor.HttpContext.Request.Method == HttpMethod.Post.Method)
{
ChromePdfRenderer renderer = new ChromePdfRenderer();
// Render View to PDF document
PdfDocument pdf = renderer.RenderRazorViewToPdf(_viewRenderService, "Views/Home/Persons.cshtml", persons);
Response.Headers.Add("Content-Disposition", "inline");
// Output PDF document
return File(pdf.BinaryData, "application/pdf", "viewToPdfMVCCore.pdf");
}
return View(persons);
}
PublicAsync Function Persons() AsTask(OfIActionResult) Dim persons = New List(OfPerson) From { New PersonWith {.Name = "Alice", .Title = "Mrs.", .Description = "Software Engineer"}, New PersonWith {.Name = "Bob", .Title = "Mr.", .Description = "Software Engineer"}, New PersonWith {.Name = "Charlie", .Title = "Mr.", .Description = "Software Engineer"} } If _httpContextAccessor.HttpContext.Request.Method = HttpMethod.Post.MethodThen Dim renderer As New ChromePdfRenderer() ' Render View to PDF document Dim pdf AsPdfDocument = renderer.RenderRazorViewToPdf(_viewRenderService, "Views/Home/Persons.cshtml", persons) Response.Headers.Add("Content-Disposition", "inline") ' Output PDF document ReturnFile(pdf.BinaryData, "application/pdf", "viewToPdfMVCCore.pdf") End If ReturnView(persons)End Function
Public Async Function Persons() As Task(Of IActionResult)
Dim persons = New List(Of Person) From {
New Person With {.Name = "Alice", .Title = "Mrs.", .Description = "Software Engineer"},
New Person With {.Name = "Bob", .Title = "Mr.", .Description = "Software Engineer"},
New Person With {.Name = "Charlie", .Title = "Mr.", .Description = "Software Engineer"}
}
If _httpContextAccessor.HttpContext.Request.Method = HttpMethod.Post.Method Then
Dim renderer As New ChromePdfRenderer()
' Render View to PDF document
Dim pdf As PdfDocument = renderer.RenderRazorViewToPdf(_viewRenderService, "Views/Home/Persons.cshtml", persons)
Response.Headers.Add("Content-Disposition", "inline")
' Output PDF document
Return File(pdf.BinaryData, "application/pdf", "viewToPdfMVCCore.pdf")
End If
Return View(persons)
End Function
For a more detailed explanation of this code snippet and to explore its additional functionality, please refer to our comprehensive how-to guide.
CSHTML to PDF (MVC Framework)
public ActionResultPersons(){ var persons = new List<Person> { new Person { Name = "Alice", Title = "Mrs.", Description = "Software Engineer" }, new Person { Name = "Bob", Title = "Mr.", Description = "Software Engineer" }, new Person { Name = "Charlie", Title = "Mr.", Description = "Software Engineer" } }; if (HttpContext.Request.HttpMethod == "POST") { // Provide the path to your view file var viewPath = "~/Views/Home/Persons.cshtml"; ChromePdfRenderer renderer = new ChromePdfRenderer(); // Render Razor view to PDF document PdfDocument pdf = renderer.RenderView(this.HttpContext, viewPath, persons);Response.Headers.Add("Content-Disposition", "inline"); // View the PDF returnFile(pdf.BinaryData, "application/pdf"); } returnView(persons);}
public ActionResult Persons()
{
var persons = new List<Person>
{
new Person { Name = "Alice", Title = "Mrs.", Description = "Software Engineer" },
new Person { Name = "Bob", Title = "Mr.", Description = "Software Engineer" },
new Person { Name = "Charlie", Title = "Mr.", Description = "Software Engineer" }
};
if (HttpContext.Request.HttpMethod == "POST")
{
// Provide the path to your view file
var viewPath = "~/Views/Home/Persons.cshtml";
ChromePdfRenderer renderer = new ChromePdfRenderer();
// Render Razor view to PDF document
PdfDocument pdf = renderer.RenderView(this.HttpContext, viewPath, persons);
Response.Headers.Add("Content-Disposition", "inline");
// View the PDF
return File(pdf.BinaryData, "application/pdf");
}
return View(persons);
}
Public Function Persons() AsActionResult Dim persons = New List(OfPerson) From { New PersonWith {.Name = "Alice", .Title = "Mrs.", .Description = "Software Engineer"}, New PersonWith {.Name = "Bob", .Title = "Mr.", .Description = "Software Engineer"}, New PersonWith {.Name = "Charlie", .Title = "Mr.", .Description = "Software Engineer"} } IfHttpContext.Request.HttpMethod = "POST" Then ' Provide the path to your view file Dim viewPath = "~/Views/Home/Persons.cshtml" Dim renderer As New ChromePdfRenderer() ' Render Razor view to PDF document Dim pdf AsPdfDocument = renderer.RenderView(Me.HttpContext, viewPath, persons) Response.Headers.Add("Content-Disposition", "inline") ' View the PDF ReturnFile(pdf.BinaryData, "application/pdf") End If ReturnView(persons)End Function
Public Function Persons() As ActionResult
Dim persons = New List(Of Person) From {
New Person With {.Name = "Alice", .Title = "Mrs.", .Description = "Software Engineer"},
New Person With {.Name = "Bob", .Title = "Mr.", .Description = "Software Engineer"},
New Person With {.Name = "Charlie", .Title = "Mr.", .Description = "Software Engineer"}
}
If HttpContext.Request.HttpMethod = "POST" Then
' Provide the path to your view file
Dim viewPath = "~/Views/Home/Persons.cshtml"
Dim renderer As New ChromePdfRenderer()
' Render Razor view to PDF document
Dim pdf As PdfDocument = renderer.RenderView(Me.HttpContext, viewPath, persons)
Response.Headers.Add("Content-Disposition", "inline")
' View the PDF
Return File(pdf.BinaryData, "application/pdf")
End If
Return View(persons)
End Function
For a more detailed explanation of this code snippet and to explore its additional functionality, please refer to our comprehensive how-to guide.
CSHTML to PDF (Headlessly)
app.MapGet("/PrintPdf", async () =>{ // Set your IronPDF license keyIronPdf.License.LicenseKey = "IRONPDF-MYLICENSE-KEY-1EF01"; // Enable detailed logging for troubleshootingIronPdf.Logging.Logger.LoggingMode = IronPdf.Logging.Logger.LoggingModes.All; // Render the Razor view to an HTML string string html = awaitRazorTemplateEngine.RenderAsync("Views/Home/Data.cshtml"); // Create a new instance of ChromePdfRenderer ChromePdfRenderer renderer = new ChromePdfRenderer(); // Render the HTML string as a PDF document PdfDocument pdf = renderer.RenderHtmlAsPdf(html, "./wwwroot"); // Return the PDF file as a response returnResults.File(pdf.BinaryData, "application/pdf", "razorViewToPdf.pdf");});
app.MapGet("/PrintPdf", async () =>
{
// Set your IronPDF license key
IronPdf.License.LicenseKey = "IRONPDF-MYLICENSE-KEY-1EF01";
// Enable detailed logging for troubleshooting
IronPdf.Logging.Logger.LoggingMode = IronPdf.Logging.Logger.LoggingModes.All;
// Render the Razor view to an HTML string
string html = await RazorTemplateEngine.RenderAsync("Views/Home/Data.cshtml");
// Create a new instance of ChromePdfRenderer
ChromePdfRenderer renderer = new ChromePdfRenderer();
// Render the HTML string as a PDF document
PdfDocument pdf = renderer.RenderHtmlAsPdf(html, "./wwwroot");
// Return the PDF file as a response
return Results.File(pdf.BinaryData, "application/pdf", "razorViewToPdf.pdf");
});
ImportsIronPdfImportsMicrosoft.AspNetCore.Httpapp.MapGet("/PrintPdf", Async Function() AsTask(OfIResult) ' Set your IronPDF license keyIronPdf.License.LicenseKey = "IRONPDF-MYLICENSE-KEY-1EF01" ' Enable detailed logging for troubleshootingIronPdf.Logging.Logger.LoggingMode = IronPdf.Logging.Logger.LoggingModes.All ' Render the Razor view to an HTML string Dim html AsString = AwaitRazorTemplateEngine.RenderAsync("Views/Home/Data.cshtml") ' Create a new instance of ChromePdfRenderer Dim renderer As New ChromePdfRenderer() ' Render the HTML string as a PDF document Dim pdf AsPdfDocument = renderer.RenderHtmlAsPdf(html, "./wwwroot") ' Return the PDF file as a response ReturnResults.File(pdf.BinaryData, "application/pdf", "razorViewToPdf.pdf")End Function)
Imports IronPdf
Imports Microsoft.AspNetCore.Http
app.MapGet("/PrintPdf", Async Function() As Task(Of IResult)
' Set your IronPDF license key
IronPdf.License.LicenseKey = "IRONPDF-MYLICENSE-KEY-1EF01"
' Enable detailed logging for troubleshooting
IronPdf.Logging.Logger.LoggingMode = IronPdf.Logging.Logger.LoggingModes.All
' Render the Razor view to an HTML string
Dim html As String = Await RazorTemplateEngine.RenderAsync("Views/Home/Data.cshtml")
' Create a new instance of ChromePdfRenderer
Dim renderer As New ChromePdfRenderer()
' Render the HTML string as a PDF document
Dim pdf As PdfDocument = renderer.RenderHtmlAsPdf(html, "./wwwroot")
' Return the PDF file as a response
Return Results.File(pdf.BinaryData, "application/pdf", "razorViewToPdf.pdf")
End Function)
For a more detailed explanation of this code snippet and to explore its additional functionality, please refer to our comprehensive how-to guide.
2. How to Configure HTML to PDF Settings
IronPDF provides extensive customizations through the ChromePdfRenderer.RenderingOptions property.
Settings
Description
Example
PaperSize
Set page dimensions for existing PDFs (A4, Letter, Legal, etc.)
PdfPaperSize.A4
PaperOrientation
Set Portrait or Landscape for existing PDFs
PdfPaperOrientation.Landscape
MarginTop/Bottom/Left/Right
Set page margins in millimeters (default: 25mm)
25
CssMediaType
Screen or Print CSS for HTML to PDF
PdfCssMediaType.Print
PrintHtmlBackgrounds
Include background colors/images (default: true)
true
EnableJavaScript
Execute JavaScript before rendering HTML content
true
WaitFor.RenderDelay
Wait time for dynamic HTML content (ms)
500
See this code snippet for a complete configuration example for manipulating PDF documents:
using IronPdf;using IronPdf.Rendering;var renderer = new ChromePdfRenderer();// Apply print-specific CSS rulesrenderer.RenderingOptions.CssMediaType = PdfCssMediaType.Print;// Set custom margins in millimetersrenderer.RenderingOptions.MarginTop = 50;renderer.RenderingOptions.MarginBottom = 50;// Enable background colors and imagesrenderer.RenderingOptions.PrintHtmlBackgrounds = true;// Set paper size and orientationrenderer.RenderingOptions.PaperSize = PdfPaperSize.A4;renderer.RenderingOptions.PaperOrientation = PdfPaperOrientation.Landscape;// Generate PDFs with all settings applied to HTML contentvar htmlContent = "<div style='background-color: #f0f0f0; padding: 20px;'><h1>Styled Content</h1></div>";var pdfDocument = renderer.RenderHtmlAsPdf(htmlContent);pdfDocument.SaveAs("styled-output.pdf");
using IronPdf;
using IronPdf.Rendering;
var renderer = new ChromePdfRenderer();
// Apply print-specific CSS rules
renderer.RenderingOptions.CssMediaType = PdfCssMediaType.Print;
// Set custom margins in millimeters
renderer.RenderingOptions.MarginTop = 50;
renderer.RenderingOptions.MarginBottom = 50;
// Enable background colors and images
renderer.RenderingOptions.PrintHtmlBackgrounds = true;
// Set paper size and orientation
renderer.RenderingOptions.PaperSize = PdfPaperSize.A4;
renderer.RenderingOptions.PaperOrientation = PdfPaperOrientation.Landscape;
// Generate PDFs with all settings applied to HTML content
var htmlContent = "<div style='background-color: #f0f0f0; padding: 20px;'><h1>Styled Content</h1></div>";
var pdfDocument = renderer.RenderHtmlAsPdf(htmlContent);
pdfDocument.SaveAs("styled-output.pdf");
ImportsIronPdfImportsIronPdf.RenderingDim renderer As New ChromePdfRenderer()' Apply print-specific CSS rulesrenderer.RenderingOptions.CssMediaType = PdfCssMediaType.Print' Set custom margins in millimetersrenderer.RenderingOptions.MarginTop = 50renderer.RenderingOptions.MarginBottom = 50' Enable background colors and imagesrenderer.RenderingOptions.PrintHtmlBackgrounds = True' Set paper size and orientationrenderer.RenderingOptions.PaperSize = PdfPaperSize.A4renderer.RenderingOptions.PaperOrientation = PdfPaperOrientation.Landscape' Generate PDFs with all settings applied to HTML contentDim htmlContent AsString = "<div style='background-color: #f0f0f0; padding: 20px;'><h1>Styled Content</h1></div>"Dim pdfDocument AsPdfDocument = renderer.RenderHtmlAsPdf(htmlContent)pdfDocument.SaveAs("styled-output.pdf")
Imports IronPdf
Imports IronPdf.Rendering
Dim renderer As New ChromePdfRenderer()
' Apply print-specific CSS rules
renderer.RenderingOptions.CssMediaType = PdfCssMediaType.Print
' Set custom margins in millimeters
renderer.RenderingOptions.MarginTop = 50
renderer.RenderingOptions.MarginBottom = 50
' Enable background colors and images
renderer.RenderingOptions.PrintHtmlBackgrounds = True
' Set paper size and orientation
renderer.RenderingOptions.PaperSize = PdfPaperSize.A4
renderer.RenderingOptions.PaperOrientation = PdfPaperOrientation.Landscape
' Generate PDFs with all settings applied to HTML content
Dim htmlContent As String = "<div style='background-color: #f0f0f0; padding: 20px;'><h1>Styled Content</h1></div>"
Dim pdfDocument As PdfDocument = renderer.RenderHtmlAsPdf(htmlContent)
pdfDocument.SaveAs("styled-output.pdf")
Tips: Use PdfCssMediaType for cleaner, print-optimized layouts in your rendered PDF file format. Use Screen to match exactly what users see in their browser.
Rendering pages that require authentication? See How to Render Authenticated Pages to PDF for setting HTTP headers, cookies, and login credentials with runnable examples.
How to Configure Proxy for PDF Rendering
When rendering HTML that loads external resources behind a corporate proxy, pass the proxy address as the third parameter on RenderHtmlAsPdf(). This is a method parameter, not a property on ChromePdfRenderOptions, so it's set per render call, not on the renderer instance.
For authenticated proxies, embed credentials directly in the URL using http://user:pass@host:port format. URL-encode special characters in passwords with Uri.EscapeDataString().
using IronPdf;var renderer = new ChromePdfRenderer();// Proxy is the third parameter, not a render optionvar pdf = renderer.RenderHtmlAsPdf( "<h1>Report</h1><link rel='stylesheet' href='https://cdn.example.com/styles.css'>", baseUrlOrPath: null, proxy: "http://proxy.corp.local:8080");pdf.SaveAs("proxied-report.pdf");
using IronPdf;
var renderer = new ChromePdfRenderer();
// Proxy is the third parameter, not a render option
var pdf = renderer.RenderHtmlAsPdf(
"<h1>Report</h1><link rel='stylesheet' href='https://cdn.example.com/styles.css'>",
baseUrlOrPath: null,
proxy: "http://proxy.corp.local:8080"
);
pdf.SaveAs("proxied-report.pdf");
ImportsIronPdfDim renderer As New ChromePdfRenderer()' Proxy is the third parameter, not a render optionDim pdf = renderer.RenderHtmlAsPdf( "<h1>Report</h1><link rel='stylesheet' href='https://cdn.example.com/styles.css'>", baseUrlOrPath:=Nothing, proxy:="http://proxy.corp.local:8080")pdf.SaveAs("proxied-report.pdf")
Imports IronPdf
Dim renderer As New ChromePdfRenderer()
' Proxy is the third parameter, not a render option
Dim pdf = renderer.RenderHtmlAsPdf(
"<h1>Report</h1><link rel='stylesheet' href='https://cdn.example.com/styles.css'>",
baseUrlOrPath:=Nothing,
proxy:="http://proxy.corp.local:8080"
)
pdf.SaveAs("proxied-report.pdf")
Note that RenderUrlAsPdf() does not accept a proxy parameter. To render a live URL behind a proxy, fetch the HTML first with HttpClient configured with a WebProxy, then pass it to RenderHtmlAsPdf() with the proxy parameter for asset loading.
3. How to Use Advanced PDF Generation & Security Features
Unlock enterprise-level capabilities for HTML to PDF conversion with advanced templating, async operations, and security features. These methods let you generate documents at scale, protect sensitive files, and ensure document authenticity.
How to Generate HTML Template for Batch PDF Creation
Basic Batch PDF Creation
Batch PDF creation is essential for generating multiple personalized PDF documents efficiently. For basic scenarios, the String.Format method in C# works best for simple PDF manipulation.
// Simple HTML templating with String.Formatstring htmlTemplate = String.Format("<h1>Hello {0}!</h1>", "World");// Results in HTML content: <h1>Hello World!</h1>
// Simple HTML templating with String.Format
string htmlTemplate = String.Format("<h1>Hello {0}!</h1>", "World");
// Results in HTML content: <h1>Hello World!</h1>
' Simple HTML templating with String.FormatDim htmlTemplate AsString = String.Format("<h1>Hello {0}!</h1>", "World")' Results in HTML content: <h1>Hello World!</h1>
' Simple HTML templating with String.Format
Dim htmlTemplate As String = String.Format("<h1>Hello {0}!</h1>", "World")
' Results in HTML content: <h1>Hello World!</h1>
For longer templates, use placeholder replacement in your HTML content:
using IronPdf;// Define reusable HTML template for PDF filesvar htmlTemplate = "<p>Dear [[NAME]],</p><p>Thank you for your order.</p>";// Customer names for batch PDF conversion processingvar names = new[] { "John", "James", "Jenny" };// Create personalized PDF documents for each customervar renderer = new ChromePdfRenderer();foreach (var name in names){ // Replace placeholder with actual data in HTML string var htmlInstance = htmlTemplate.Replace("[[NAME]]", name); // Generate personalized PDF document from HTML content var pdf = renderer.RenderHtmlAsPdf(htmlInstance); // Save with customer-specific filename as PDF files pdf.SaveAs($"{name}-invoice.pdf");}
using IronPdf;
// Define reusable HTML template for PDF files
var htmlTemplate = "<p>Dear [[NAME]],</p><p>Thank you for your order.</p>";
// Customer names for batch PDF conversion processing
var names = new[] { "John", "James", "Jenny" };
// Create personalized PDF documents for each customer
var renderer = new ChromePdfRenderer();
foreach (var name in names)
{
// Replace placeholder with actual data in HTML string
var htmlInstance = htmlTemplate.Replace("[[NAME]]", name);
// Generate personalized PDF document from HTML content
var pdf = renderer.RenderHtmlAsPdf(htmlInstance);
// Save with customer-specific filename as PDF files
pdf.SaveAs($"{name}-invoice.pdf");
}
ImportsIronPdf' Define reusable HTML template for PDF filesDim htmlTemplate AsString = "<p>Dear [[NAME]],</p><p>Thank you for your order.</p>"' Customer names for batch PDF conversion processingDim names AsString() = {"John", "James", "Jenny"}' Create personalized PDF documents for each customerDim renderer As New ChromePdfRenderer()For Each name In names ' Replace placeholder with actual data in HTML string Dim htmlInstance AsString = htmlTemplate.Replace("[[NAME]]", name) ' Generate personalized PDF document from HTML content Dim pdf = renderer.RenderHtmlAsPdf(htmlInstance) ' Save with customer-specific filename as PDF files pdf.SaveAs($"{name}-invoice.pdf")Next
Imports IronPdf
' Define reusable HTML template for PDF files
Dim htmlTemplate As String = "<p>Dear [[NAME]],</p><p>Thank you for your order.</p>"
' Customer names for batch PDF conversion processing
Dim names As String() = {"John", "James", "Jenny"}
' Create personalized PDF documents for each customer
Dim renderer As New ChromePdfRenderer()
For Each name In names
' Replace placeholder with actual data in HTML string
Dim htmlInstance As String = htmlTemplate.Replace("[[NAME]]", name)
' Generate personalized PDF document from HTML content
Dim pdf = renderer.RenderHtmlAsPdf(htmlInstance)
' Save with customer-specific filename as PDF files
pdf.SaveAs($"{name}-invoice.pdf")
Next
HTML to PDF Templating with Handlebars.NET
For complex templates with loops and conditionals, use Handlebars.NET to render dynamic HTML content.
# First, install Handlebars.NET for HTML to PDF templatingPM > Install-Package Handlebars.NET
# First, install Handlebars.NET for HTML to PDF templating
PM > Install-Package Handlebars.NET
SHELL
using HandlebarsDotNet;using IronPdf;// Define Handlebars template with placeholders for HTML contentvar source = @"<div class=""entry""> <h1>{{title}}</h1> <div class=""body""> {{body}} </div> </div>";// Compile template for reuse in PDF conversionvar template = Handlebars.Compile(source);// Create data object (can be database records) for HTML to PDF directlyvar data = new { title = "Monthly Report", body = "Sales increased by 15% this month."};// Merge template with data to create HTML contentvar htmlResult = template(data);// Convert templated HTML to PDF using the PDF convertervar renderer = new ChromePdfRenderer();var pdf = renderer.RenderHtmlAsPdf(htmlResult);pdf.SaveAs("monthly-report.pdf");
using HandlebarsDotNet;
using IronPdf;
// Define Handlebars template with placeholders for HTML content
var source =
@"<div class=""entry"">
<h1>{{title}}</h1>
<div class=""body"">
{{body}}
</div>
</div>";
// Compile template for reuse in PDF conversion
var template = Handlebars.Compile(source);
// Create data object (can be database records) for HTML to PDF directly
var data = new {
title = "Monthly Report",
body = "Sales increased by 15% this month."
};
// Merge template with data to create HTML content
var htmlResult = template(data);
// Convert templated HTML to PDF using the PDF converter
var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderHtmlAsPdf(htmlResult);
pdf.SaveAs("monthly-report.pdf");
ImportsHandlebarsDotNetImportsIronPdf' Define Handlebars template with placeholders for HTML contentDim source AsString = "<div class=""entry""> <h1>{{title}}</h1> <div class=""body""> {{body}} </div> </div>"' Compile template for reuse in PDF conversionDim template = Handlebars.Compile(source)' Create data object (can be database records) for HTML to PDF directlyDim data = New With { .title = "Monthly Report", .body = "Sales increased by 15% this month."}' Merge template with data to create HTML contentDim htmlResult = template(data)' Convert templated HTML to PDF using the PDF converterDim renderer = New ChromePdfRenderer()Dim pdf = renderer.RenderHtmlAsPdf(htmlResult)pdf.SaveAs("monthly-report.pdf")
Imports HandlebarsDotNet
Imports IronPdf
' Define Handlebars template with placeholders for HTML content
Dim source As String =
"<div class=""entry"">
<h1>{{title}}</h1>
<div class=""body"">
{{body}}
</div>
</div>"
' Compile template for reuse in PDF conversion
Dim template = Handlebars.Compile(source)
' Create data object (can be database records) for HTML to PDF directly
Dim data = New With {
.title = "Monthly Report",
.body = "Sales increased by 15% this month."
}
' Merge template with data to create HTML content
Dim htmlResult = template(data)
' Convert templated HTML to PDF using the PDF converter
Dim renderer = New ChromePdfRenderer()
Dim pdf = renderer.RenderHtmlAsPdf(htmlResult)
pdf.SaveAs("monthly-report.pdf")
Managing pagination in generated PDF documents ensures professional, readable layouts when you convert HTML snippets. Use CSS to control where pages break in your PDF files.
IronPDF delivers enterprise-grade performance with full async and multithreading support for your HTML to PDF conversion requirements when you need to generate PDF files at scale.
using IronPdf;using System.Collections.Generic;using System.Linq;using System.Threading.Tasks;public class PdfGenerationService{ // Async method for non-blocking PDF generation from HTML content public async Task<byte[]> GeneratePdfAsync(string html) { var renderer = new ChromePdfRenderer(); // Async HTML to PDF conversion preserves thread pool var pdf = await renderer.RenderHtmlAsPdfAsync(html); // Return PDF files as byte array for web responses return pdf.BinaryData; } // Concurrent batch PDF generation for multiple HTML strings public async TaskGenerateMultiplePdfsAsync(List<string> htmlTemplates) { var renderer = new ChromePdfRenderer(); // Create parallel conversion tasks to generate PDF documents var tasks = htmlTemplates.Select(html => renderer.RenderHtmlAsPdfAsync(html) ); // Await all PDF conversions simultaneously var pdfs = awaitTask.WhenAll(tasks); // Save generated PDF files from HTML content for (int i = 0; i < pdfs.Length; i++) { pdfs[i].SaveAs($"document-{i}.pdf"); } }}
using IronPdf;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
public class PdfGenerationService
{
// Async method for non-blocking PDF generation from HTML content
public async Task<byte[]> GeneratePdfAsync(string html)
{
var renderer = new ChromePdfRenderer();
// Async HTML to PDF conversion preserves thread pool
var pdf = await renderer.RenderHtmlAsPdfAsync(html);
// Return PDF files as byte array for web responses
return pdf.BinaryData;
}
// Concurrent batch PDF generation for multiple HTML strings
public async Task GenerateMultiplePdfsAsync(List<string> htmlTemplates)
{
var renderer = new ChromePdfRenderer();
// Create parallel conversion tasks to generate PDF documents
var tasks = htmlTemplates.Select(html =>
renderer.RenderHtmlAsPdfAsync(html)
);
// Await all PDF conversions simultaneously
var pdfs = await Task.WhenAll(tasks);
// Save generated PDF files from HTML content
for (int i = 0; i < pdfs.Length; i++)
{
pdfs[i].SaveAs($"document-{i}.pdf");
}
}
}
ImportsIronPdfImportsSystem.Collections.GenericImportsSystem.LinqImportsSystem.Threading.TasksPublic Class PdfGenerationService ' Async method for non-blocking PDF generation from HTML content PublicAsync Function GeneratePdfAsync(html AsString) AsTask(OfByte()) Dim renderer = New ChromePdfRenderer() ' Async HTML to PDF conversion preserves thread pool Dim pdf = Await renderer.RenderHtmlAsPdfAsync(html) ' Return PDF files as byte array for web responses Return pdf.BinaryData End Function ' Concurrent batch PDF generation for multiple HTML strings PublicAsync Function GenerateMultiplePdfsAsync(htmlTemplates AsList(OfString)) AsTask Dim renderer = New ChromePdfRenderer() ' Create parallel conversion tasks to generate PDF documents Dim tasks = htmlTemplates.Select(Function(html) renderer.RenderHtmlAsPdfAsync(html)) ' Await all PDF conversions simultaneously Dim pdfs = AwaitTask.WhenAll(tasks) ' Save generated PDF files from HTML content For i AsInteger = 0 To pdfs.Length - 1 pdfs(i).SaveAs($"document-{i}.pdf") Next End FunctionEnd Class
Imports IronPdf
Imports System.Collections.Generic
Imports System.Linq
Imports System.Threading.Tasks
Public Class PdfGenerationService
' Async method for non-blocking PDF generation from HTML content
Public Async Function GeneratePdfAsync(html As String) As Task(Of Byte())
Dim renderer = New ChromePdfRenderer()
' Async HTML to PDF conversion preserves thread pool
Dim pdf = Await renderer.RenderHtmlAsPdfAsync(html)
' Return PDF files as byte array for web responses
Return pdf.BinaryData
End Function
' Concurrent batch PDF generation for multiple HTML strings
Public Async Function GenerateMultiplePdfsAsync(htmlTemplates As List(Of String)) As Task
Dim renderer = New ChromePdfRenderer()
' Create parallel conversion tasks to generate PDF documents
Dim tasks = htmlTemplates.Select(Function(html) renderer.RenderHtmlAsPdfAsync(html))
' Await all PDF conversions simultaneously
Dim pdfs = Await Task.WhenAll(tasks)
' Save generated PDF files from HTML content
For i As Integer = 0 To pdfs.Length - 1
pdfs(i).SaveAs($"document-{i}.pdf")
Next
End Function
End Class
Tips: Performance optimization tips for HTML to PDF conversion
Use 64-bit systems for optimal PDF generation performance.
Ensure adequate server resources when you generate PDF documents (avoid underpowered free tiers)
Allow sufficient RenderDelay for complex JavaScript in HTML content.
Reuse ChromePdfRenderer instances when possible.
Leverage recent memory fixes for batch/async ops to reduce resource usage; test for reduced file sizes with repeated custom headers/footers.
Secure sensitive PDF documents with passwords and permissions.
using IronPdf;var renderer = new ChromePdfRenderer();// Convert HTML to PDF with securityvar pdf = renderer.RenderHtmlAsPdf("<h1>Confidential Report</h1>");// Configure security settings for PDF filespdf.SecuritySettings.UserPassword = "user123"; // Password to open PDF documentspdf.SecuritySettings.OwnerPassword = "owner456"; // Password to modify PDF files// Set granular permissions for PDF formatpdf.SecuritySettings.AllowUserCopyPasteContent = false;pdf.SecuritySettings.AllowUserAnnotations = false;pdf.SecuritySettings.AllowUserPrinting = PdfPrintSecurity.PrintLowQuality;// Apply strong encryption to PDF documentspdf.SecuritySettings.EncryptionAlgorithm = PdfEncryptionAlgorithm.AES256;pdf.SaveAs("secure-document.pdf");
using IronPdf;
var renderer = new ChromePdfRenderer();
// Convert HTML to PDF with security
var pdf = renderer.RenderHtmlAsPdf("<h1>Confidential Report</h1>");
// Configure security settings for PDF files
pdf.SecuritySettings.UserPassword = "user123"; // Password to open PDF documents
pdf.SecuritySettings.OwnerPassword = "owner456"; // Password to modify PDF files
// Set granular permissions for PDF format
pdf.SecuritySettings.AllowUserCopyPasteContent = false;
pdf.SecuritySettings.AllowUserAnnotations = false;
pdf.SecuritySettings.AllowUserPrinting = PdfPrintSecurity.PrintLowQuality;
// Apply strong encryption to PDF documents
pdf.SecuritySettings.EncryptionAlgorithm = PdfEncryptionAlgorithm.AES256;
pdf.SaveAs("secure-document.pdf");
ImportsIronPdfDim renderer As New ChromePdfRenderer()' Convert HTML to PDF with securityDim pdf = renderer.RenderHtmlAsPdf("<h1>Confidential Report</h1>")' Configure security settings for PDF filespdf.SecuritySettings.UserPassword = "user123" ' Password to open PDF documentspdf.SecuritySettings.OwnerPassword = "owner456" ' Password to modify PDF files' Set granular permissions for PDF formatpdf.SecuritySettings.AllowUserCopyPasteContent = Falsepdf.SecuritySettings.AllowUserAnnotations = Falsepdf.SecuritySettings.AllowUserPrinting = PdfPrintSecurity.PrintLowQuality' Apply strong encryption to PDF documentspdf.SecuritySettings.EncryptionAlgorithm = PdfEncryptionAlgorithm.AES256pdf.SaveAs("secure-document.pdf")
Imports IronPdf
Dim renderer As New ChromePdfRenderer()
' Convert HTML to PDF with security
Dim pdf = renderer.RenderHtmlAsPdf("<h1>Confidential Report</h1>")
' Configure security settings for PDF files
pdf.SecuritySettings.UserPassword = "user123" ' Password to open PDF documents
pdf.SecuritySettings.OwnerPassword = "owner456" ' Password to modify PDF files
' Set granular permissions for PDF format
pdf.SecuritySettings.AllowUserCopyPasteContent = False
pdf.SecuritySettings.AllowUserAnnotations = False
pdf.SecuritySettings.AllowUserPrinting = PdfPrintSecurity.PrintLowQuality
' Apply strong encryption to PDF documents
pdf.SecuritySettings.EncryptionAlgorithm = PdfEncryptionAlgorithm.AES256
pdf.SaveAs("secure-document.pdf")
using IronPdf;using IronPdf.Signing;var renderer = new ChromePdfRenderer();// Generate PDF from HTML pagevar pdf = renderer.RenderHtmlAsPdf("<h1>Contract Agreement</h1>");// Create digital signature with certificate for PDF filesvar signature = new PdfSignature("certificate.pfx", "password"){SigningContact = "legal@company.com",SigningLocation = "New York, NY",SigningReason = "Contract Approval"};// Apply signature to PDF documentspdf.Sign(signature);pdf.SaveAs("signed-contract.pdf");
using IronPdf;
using IronPdf.Signing;
var renderer = new ChromePdfRenderer();
// Generate PDF from HTML page
var pdf = renderer.RenderHtmlAsPdf("<h1>Contract Agreement</h1>");
// Create digital signature with certificate for PDF files
var signature = new PdfSignature("certificate.pfx", "password")
{
SigningContact = "legal@company.com",
SigningLocation = "New York, NY",
SigningReason = "Contract Approval"
};
// Apply signature to PDF documents
pdf.Sign(signature);
pdf.SaveAs("signed-contract.pdf");
To convert standard HTML form elements into interactive, fillable PDF form fields, enable the CreatePdfFormsFromHtml rendering option. This preserves text inputs, checkboxes, radio buttons, and dropdown menus as editable fields in the generated PDF document.
using IronPdf;var renderer = new ChromePdfRenderer();// Enable HTML form to PDF form conversionrenderer.RenderingOptions.CreatePdfFormsFromHtml = true;string htmlForm = @" <h2>Employee Onboarding Form</h2> <form> <label>Full Name:</label> <input type='text' name='fullName' value='' /><br/> <label>Department:</label> <select name='department'> <option value='engineering'>Engineering</option> <option value='marketing'>Marketing</option> <option value='sales'>Sales</option> </select><br/> <label>Agree to Terms:</label> <input type='checkbox' name='agreeTerms' /> </form>";var pdf = renderer.RenderHtmlAsPdf(htmlForm);pdf.SaveAs("onboarding-form.pdf");
using IronPdf;
var renderer = new ChromePdfRenderer();
// Enable HTML form to PDF form conversion
renderer.RenderingOptions.CreatePdfFormsFromHtml = true;
string htmlForm = @"
<h2>Employee Onboarding Form</h2>
<form>
<label>Full Name:</label>
<input type='text' name='fullName' value='' /><br/>
<label>Department:</label>
<select name='department'>
<option value='engineering'>Engineering</option>
<option value='marketing'>Marketing</option>
<option value='sales'>Sales</option>
</select><br/>
<label>Agree to Terms:</label>
<input type='checkbox' name='agreeTerms' />
</form>";
var pdf = renderer.RenderHtmlAsPdf(htmlForm);
pdf.SaveAs("onboarding-form.pdf");
ImportsIronPdfDim renderer As New ChromePdfRenderer()' Enable HTML form to PDF form conversionrenderer.RenderingOptions.CreatePdfFormsFromHtml = TrueDim htmlForm AsString = " <h2>Employee Onboarding Form</h2> <form> <label>Full Name:</label> <input type='text' name='fullName' value='' /><br/> <label>Department:</label> <select name='department'> <option value='engineering'>Engineering</option> <option value='marketing'>Marketing</option> <option value='sales'>Sales</option> </select><br/> <label>Agree to Terms:</label> <input type='checkbox' name='agreeTerms' /> </form>"Dim pdf = renderer.RenderHtmlAsPdf(htmlForm)pdf.SaveAs("onboarding-form.pdf")
Imports IronPdf
Dim renderer As New ChromePdfRenderer()
' Enable HTML form to PDF form conversion
renderer.RenderingOptions.CreatePdfFormsFromHtml = True
Dim htmlForm As String = "
<h2>Employee Onboarding Form</h2>
<form>
<label>Full Name:</label>
<input type='text' name='fullName' value='' /><br/>
<label>Department:</label>
<select name='department'>
<option value='engineering'>Engineering</option>
<option value='marketing'>Marketing</option>
<option value='sales'>Sales</option>
</select><br/>
<label>Agree to Terms:</label>
<input type='checkbox' name='agreeTerms' />
</form>"
Dim pdf = renderer.RenderHtmlAsPdf(htmlForm)
pdf.SaveAs("onboarding-form.pdf")
Warning: Each form field in your HTML must have a unique name attribute. Duplicate names will cause fields to share the same value in the generated PDF, leading to unexpected behavior when users fill out the form.
To render a specific section of a page rather than the full document, isolate the target element before rendering. The most direct approach uses the Javascript rendering option to replace the document body with the target element's content, combined with WaitFor.HtmlQuerySelector() to ensure the element exists before extraction. The snippet below preserves document.head so stylesheets and fonts carry over; without that step, CSS rules relying on ancestor selectors would be lost in the extracted PDF.
For server-side scenarios where you have access to the raw HTML, extract the target fragment with a parser like AngleSharp and pass it to RenderHtmlAsPdf(), no JavaScript execution needed.
using IronPdf;// Full page HTML containing the target elementstring fullPageHtml = @"<html><body> <header><h1>Acme Corp Invoice</h1></header> <div id='invoice-summary'> <h2>Invoice #12345</h2> <p>Total: $1,250.00</p> </div> <footer>Confidential</footer></body></html>";var renderer = new ChromePdfRenderer();renderer.RenderingOptions.EnableJavaScript = true;// Replace the body with only the target elementrenderer.RenderingOptions.Javascript = @" var el = document.querySelector('#invoice-summary'); if (el) { var head = document.head.innerHTML; document.body.innerHTML = el.outerHTML; document.head.innerHTML = head; }";// Wait for the target element before JS executesrenderer.RenderingOptions.WaitFor.HtmlQuerySelector("#invoice-summary", 10000);var pdf = renderer.RenderHtmlAsPdf(fullPageHtml);pdf.SaveAs("invoice-summary.pdf");
using IronPdf;
// Full page HTML containing the target element
string fullPageHtml = @"
<html>
<body>
<header><h1>Acme Corp Invoice</h1></header>
<div id='invoice-summary'>
<h2>Invoice #12345</h2>
<p>Total: $1,250.00</p>
</div>
<footer>Confidential</footer>
</body>
</html>";
var renderer = new ChromePdfRenderer();
renderer.RenderingOptions.EnableJavaScript = true;
// Replace the body with only the target element
renderer.RenderingOptions.Javascript = @"
var el = document.querySelector('#invoice-summary');
if (el) {
var head = document.head.innerHTML;
document.body.innerHTML = el.outerHTML;
document.head.innerHTML = head;
}
";
// Wait for the target element before JS executes
renderer.RenderingOptions.WaitFor.HtmlQuerySelector("#invoice-summary", 10000);
var pdf = renderer.RenderHtmlAsPdf(fullPageHtml);
pdf.SaveAs("invoice-summary.pdf");
ImportsIronPdf' Full page HTML containing the target elementDim fullPageHtml AsString = "<html><body> <header><h1>Acme Corp Invoice</h1></header> <div id='invoice-summary'> <h2>Invoice #12345</h2> <p>Total: $1,250.00</p> </div> <footer>Confidential</footer></body></html>"Dim renderer As New ChromePdfRenderer()renderer.RenderingOptions.EnableJavaScript = True' Replace the body with only the target elementrenderer.RenderingOptions.Javascript = " var el = document.querySelector('#invoice-summary'); if (el) { var head = document.head.innerHTML; document.body.innerHTML = el.outerHTML; document.head.innerHTML = head; }"' Wait for the target element before JS executesrenderer.RenderingOptions.WaitFor.HtmlQuerySelector("#invoice-summary", 10000)Dim pdf = renderer.RenderHtmlAsPdf(fullPageHtml)pdf.SaveAs("invoice-summary.pdf")
Imports IronPdf
' Full page HTML containing the target element
Dim fullPageHtml As String = "
<html>
<body>
<header><h1>Acme Corp Invoice</h1></header>
<div id='invoice-summary'>
<h2>Invoice #12345</h2>
<p>Total: $1,250.00</p>
</div>
<footer>Confidential</footer>
</body>
</html>"
Dim renderer As New ChromePdfRenderer()
renderer.RenderingOptions.EnableJavaScript = True
' Replace the body with only the target element
renderer.RenderingOptions.Javascript = "
var el = document.querySelector('#invoice-summary');
if (el) {
var head = document.head.innerHTML;
document.body.innerHTML = el.outerHTML;
document.head.innerHTML = head;
}
"
' Wait for the target element before JS executes
renderer.RenderingOptions.WaitFor.HtmlQuerySelector("#invoice-summary", 10000)
Dim pdf = renderer.RenderHtmlAsPdf(fullPageHtml)
pdf.SaveAs("invoice-summary.pdf")
There are three mechanisms for rendering pages that sit behind authentication: network login credentials, custom cookies, and HTTP request headers. These cover the most common authentication scenarios when converting protected web content to PDF. This enables rendering of intranet dashboards, restricted reports, or API-generated pages directly to PDF without needing to retrieve the HTML separately.
Login Credentials
Use ChromeHttpLoginCredentials for basic, digest, or NTLM authentication when converting protected URLs to PDF.
using IronPdf;var renderer = new ChromePdfRenderer();// Configure network authenticationrenderer.LoginCredentials = new ChromeHttpLoginCredentials{NetworkUsername = "user@domain.com",NetworkPassword = "securePassword",AuthenticationType = ChromeHttpLoginCredentials.AuthType.Basic};var pdf = renderer.RenderUrlAsPdf("https://intranet.company.com/reports");pdf.SaveAs("authenticated-report.pdf");
using IronPdf;
var renderer = new ChromePdfRenderer();
// Configure network authentication
renderer.LoginCredentials = new ChromeHttpLoginCredentials
{
NetworkUsername = "user@domain.com",
NetworkPassword = "securePassword",
AuthenticationType = ChromeHttpLoginCredentials.AuthType.Basic
};
var pdf = renderer.RenderUrlAsPdf("https://intranet.company.com/reports");
pdf.SaveAs("authenticated-report.pdf");
ImportsIronPdfDim renderer As New ChromePdfRenderer()' Configure network authenticationrenderer.LoginCredentials = New ChromeHttpLoginCredentialsWith { .NetworkUsername = "user@domain.com", .NetworkPassword = "securePassword", .AuthenticationType = ChromeHttpLoginCredentials.AuthType.Basic}Dim pdf = renderer.RenderUrlAsPdf("https://intranet.company.com/reports")pdf.SaveAs("authenticated-report.pdf")
Imports IronPdf
Dim renderer As New ChromePdfRenderer()
' Configure network authentication
renderer.LoginCredentials = New ChromeHttpLoginCredentials With {
.NetworkUsername = "user@domain.com",
.NetworkPassword = "securePassword",
.AuthenticationType = ChromeHttpLoginCredentials.AuthType.Basic
}
Dim pdf = renderer.RenderUrlAsPdf("https://intranet.company.com/reports")
pdf.SaveAs("authenticated-report.pdf")
Cookies and HTTP Headers
For token-based or session-based authentication, attach custom cookies and HTTP headers directly to the rendering request.
using IronPdf;var renderer = new ChromePdfRenderer();// Add session cookiesrenderer.RenderingOptions.CustomCookies["sessionId"] = "abc123token";renderer.RenderingOptions.CustomCookies["authToken"] = "bearer-xyz";// Add custom HTTP headers (e.g., API key or Bearer token)renderer.RenderingOptions.HttpRequestHeaders["Authorization"] = "Bearer eyJhbGciOi...";var pdf = renderer.RenderUrlAsPdf("https://app.example.com/dashboard");pdf.SaveAs("dashboard.pdf");
using IronPdf;
var renderer = new ChromePdfRenderer();
// Add session cookies
renderer.RenderingOptions.CustomCookies["sessionId"] = "abc123token";
renderer.RenderingOptions.CustomCookies["authToken"] = "bearer-xyz";
// Add custom HTTP headers (e.g., API key or Bearer token)
renderer.RenderingOptions.HttpRequestHeaders["Authorization"] = "Bearer eyJhbGciOi...";
var pdf = renderer.RenderUrlAsPdf("https://app.example.com/dashboard");
pdf.SaveAs("dashboard.pdf");
C#
Tips: For HTML form-based logins (POST username/password), consider using HttpClient to authenticate first, then pass the resulting cookies to the CustomCookies dictionary for rendering the protected page.
How Do I Generate PDFs from Multiple HTML Snippets?
To generate PDFs by combining HTML snippets, you can merge them. This creates multi-section reports or combines content from different sources:
var renderer = new ChromePdfRenderer();PdfDocument part1 = renderer.RenderHtmlAsPdf("<h1>Section 1</h1><p>First section content</p>");PdfDocument part2 = renderer.RenderHtmlAsPdf("<h1>Section 2</h1><p>Second section content</p>");var merged = PdfDocument.Merge(part1, part2);merged.SaveAs("Merged.pdf");// Alternative approach: copy specific pagesvar combinedDoc = new PdfDocument();combinedDoc.CopyPage(part1, 0); // Copy first pagecombinedDoc.CopyPage(part2, 0); // Copy first pagecombinedDoc.SaveAs("Combined.pdf");
var renderer = new ChromePdfRenderer();
PdfDocument part1 = renderer.RenderHtmlAsPdf("<h1>Section 1</h1><p>First section content</p>");
PdfDocument part2 = renderer.RenderHtmlAsPdf("<h1>Section 2</h1><p>Second section content</p>");
var merged = PdfDocument.Merge(part1, part2);
merged.SaveAs("Merged.pdf");
// Alternative approach: copy specific pages
var combinedDoc = new PdfDocument();
combinedDoc.CopyPage(part1, 0); // Copy first page
combinedDoc.CopyPage(part2, 0); // Copy first page
combinedDoc.SaveAs("Combined.pdf");
Dim renderer = New ChromePdfRenderer()Dim part1 AsPdfDocument = renderer.RenderHtmlAsPdf("<h1>Section 1</h1><p>First section content</p>")Dim part2 AsPdfDocument = renderer.RenderHtmlAsPdf("<h1>Section 2</h1><p>Second section content</p>")Dim merged = PdfDocument.Merge(part1, part2)merged.SaveAs("Merged.pdf")' Alternative approach: copy specific pagesDim combinedDoc = New PdfDocument()combinedDoc.CopyPage(part1, 0) ' Copy first pagecombinedDoc.CopyPage(part2, 0) ' Copy first pagecombinedDoc.SaveAs("Combined.pdf")
Dim renderer = New ChromePdfRenderer()
Dim part1 As PdfDocument = renderer.RenderHtmlAsPdf("<h1>Section 1</h1><p>First section content</p>")
Dim part2 As PdfDocument = renderer.RenderHtmlAsPdf("<h1>Section 2</h1><p>Second section content</p>")
Dim merged = PdfDocument.Merge(part1, part2)
merged.SaveAs("Merged.pdf")
' Alternative approach: copy specific pages
Dim combinedDoc = New PdfDocument()
combinedDoc.CopyPage(part1, 0) ' Copy first page
combinedDoc.CopyPage(part2, 0) ' Copy first page
combinedDoc.SaveAs("Combined.pdf")
This helps when creating multi-section reports from different HTML fragments. You can also add bookmarks to improve navigation.
How Do I Convert HTML to PDF in Web APIs?
In ASP.NET Web API, generate and return PDFs without saving to disk using MemoryStream. This pattern is ideal for Blazor applications and RESTful services:
[HttpGet("download")]public IActionResultGetPdf(){ var renderer = new ChromePdfRenderer(); string html = "<h1>Web Report</h1><p>Generated dynamically.</p>"; var pdf = renderer.RenderHtmlAsPdf(html); var bytes = pdf.BinaryData; // Optional: Add metadata pdf.MetaData.Author = "API Service"; pdf.MetaData.CreationDate = DateTime.Now; returnFile(bytes, "application/pdf", "report.pdf");}
[HttpGet("download")]
public IActionResult GetPdf()
{
var renderer = new ChromePdfRenderer();
string html = "<h1>Web Report</h1><p>Generated dynamically.</p>";
var pdf = renderer.RenderHtmlAsPdf(html);
var bytes = pdf.BinaryData;
// Optional: Add metadata
pdf.MetaData.Author = "API Service";
pdf.MetaData.CreationDate = DateTime.Now;
return File(bytes, "application/pdf", "report.pdf");
}
<HttpGet("download")>Public Function GetPdf() AsIActionResult Dim renderer = New ChromePdfRenderer() Dim html AsString = "<h1>Web Report</h1><p>Generated dynamically.</p>" Dim pdf = renderer.RenderHtmlAsPdf(html) Dim bytes = pdf.BinaryData ' Optional: Add metadata pdf.MetaData.Author = "API Service" pdf.MetaData.CreationDate = DateTime.Now ReturnFile(bytes, "application/pdf", "report.pdf")End Function
<HttpGet("download")>
Public Function GetPdf() As IActionResult
Dim renderer = New ChromePdfRenderer()
Dim html As String = "<h1>Web Report</h1><p>Generated dynamically.</p>"
Dim pdf = renderer.RenderHtmlAsPdf(html)
Dim bytes = pdf.BinaryData
' Optional: Add metadata
pdf.MetaData.Author = "API Service"
pdf.MetaData.CreationDate = DateTime.Now
Return File(bytes, "application/pdf", "report.pdf")
End Function
This pattern works great for server-side PDF generation in .NET 10 web applications. You can integrate with CSHTML views for MVC applications.
How Do You Add Headers, Watermarks, and Security?
Adding Professional Headers and Footers
Headers and footers that display page numbers, dates, or branding make multi-page documents far more readable and professional. IronPDF processes them as HTML fragments, so you can use full CSS styling including images and brand colors:
using IronPdf;var renderer = new ChromePdfRenderer();renderer.RenderingOptions.HtmlHeader = new HtmlHeaderFooter{MaxHeight = 50,HtmlFragment = "<div style='text-align:center;font-size:12px;'>Annual Report 2025 -- Confidential</div>",BaseUrl = new Uri(@"file:///C:/assets/")};renderer.RenderingOptions.HtmlFooter = new HtmlHeaderFooter{MaxHeight = 30,HtmlFragment = "<div style='text-align:center;font-size:10px;'>Page {page} of {total-pages}</div>",DrawDividerLine = true};renderer.RenderingOptions.MarginTop = 60;renderer.RenderingOptions.MarginBottom = 40;var pdf = renderer.RenderHtmlAsPdf("<h1>Report Content</h1><p>Body text here.</p>");pdf.SaveAs("report-with-headers.pdf");
using IronPdf;
var renderer = new ChromePdfRenderer();
renderer.RenderingOptions.HtmlHeader = new HtmlHeaderFooter
{
MaxHeight = 50,
HtmlFragment = "<div style='text-align:center;font-size:12px;'>Annual Report 2025 -- Confidential</div>",
BaseUrl = new Uri(@"file:///C:/assets/")
};
renderer.RenderingOptions.HtmlFooter = new HtmlHeaderFooter
{
MaxHeight = 30,
HtmlFragment = "<div style='text-align:center;font-size:10px;'>Page {page} of {total-pages}</div>",
DrawDividerLine = true
};
renderer.RenderingOptions.MarginTop = 60;
renderer.RenderingOptions.MarginBottom = 40;
var pdf = renderer.RenderHtmlAsPdf("<h1>Report Content</h1><p>Body text here.</p>");
pdf.SaveAs("report-with-headers.pdf");
ImportsIronPdfDim renderer As New ChromePdfRenderer()renderer.RenderingOptions.HtmlHeader = New HtmlHeaderFooterWith { .MaxHeight = 50, .HtmlFragment = "<div style='text-align:center;font-size:12px;'>Annual Report 2025 -- Confidential</div>", .BaseUrl = New Uri("file:///C:/assets/")}renderer.RenderingOptions.HtmlFooter = New HtmlHeaderFooterWith { .MaxHeight = 30, .HtmlFragment = "<div style='text-align:center;font-size:10px;'>Page {page} of {total-pages}</div>", .DrawDividerLine = True}renderer.RenderingOptions.MarginTop = 60renderer.RenderingOptions.MarginBottom = 40Dim pdf = renderer.RenderHtmlAsPdf("<h1>Report Content</h1><p>Body text here.</p>")pdf.SaveAs("report-with-headers.pdf")
Imports IronPdf
Dim renderer As New ChromePdfRenderer()
renderer.RenderingOptions.HtmlHeader = New HtmlHeaderFooter With {
.MaxHeight = 50,
.HtmlFragment = "<div style='text-align:center;font-size:12px;'>Annual Report 2025 -- Confidential</div>",
.BaseUrl = New Uri("file:///C:/assets/")
}
renderer.RenderingOptions.HtmlFooter = New HtmlHeaderFooter With {
.MaxHeight = 30,
.HtmlFragment = "<div style='text-align:center;font-size:10px;'>Page {page} of {total-pages}</div>",
.DrawDividerLine = True
}
renderer.RenderingOptions.MarginTop = 60
renderer.RenderingOptions.MarginBottom = 40
Dim pdf = renderer.RenderHtmlAsPdf("<h1>Report Content</h1><p>Body text here.</p>")
pdf.SaveAs("report-with-headers.pdf")
Placeholders like {page} and {total-pages} are replaced automatically at render time. Review the headers and footers tutorial for dynamic date injection, logo placement, and alternating page styles.
Applying Watermarks, Encryption, and Digital Signatures
Watermarks protect draft documents and confidential reports. Password protection and permission settings restrict who can print, copy, or edit a PDF. Digital signatures add a verifiable authenticity layer for contracts and regulated documents. You can combine all three in a single workflow:
using IronPdf;using System.Security.Cryptography.X509Certificates;var renderer = new ChromePdfRenderer();var pdf = renderer.RenderHtmlAsPdf("<h1>Contract Agreement</h1><p>Terms and conditions.</p>");// Watermarkpdf.ApplyWatermark( "<div style='font-size:72px;color:red;opacity:0.3;'>DRAFT</div>", rotation: 45, opacity: 30);// Encryption and permissionspdf.SecuritySettings.UserPassword = "user123";pdf.SecuritySettings.OwnerPassword = "owner456";pdf.SecuritySettings.AllowUserPrinting = IronPdf.Security.PdfPrintSecurity.NoPrint;pdf.SecuritySettings.AllowUserCopyPasteContent = false;// Digital signaturevar cert = X509CertificateLoader.LoadPkcs12FromFile("certificate.pfx", "password");var signature = new PdfSignature(cert){SigningContact = "Jane Smith",SigningLocation = "New York, NY",SigningReason = "Contract Approval"};pdf.Sign(signature);pdf.SaveAsRevision("signed-contract.pdf");
using IronPdf;
using System.Security.Cryptography.X509Certificates;
var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderHtmlAsPdf("<h1>Contract Agreement</h1><p>Terms and conditions.</p>");
// Watermark
pdf.ApplyWatermark(
"<div style='font-size:72px;color:red;opacity:0.3;'>DRAFT</div>",
rotation: 45,
opacity: 30
);
// Encryption and permissions
pdf.SecuritySettings.UserPassword = "user123";
pdf.SecuritySettings.OwnerPassword = "owner456";
pdf.SecuritySettings.AllowUserPrinting = IronPdf.Security.PdfPrintSecurity.NoPrint;
pdf.SecuritySettings.AllowUserCopyPasteContent = false;
// Digital signature
var cert = X509CertificateLoader.LoadPkcs12FromFile("certificate.pfx", "password");
var signature = new PdfSignature(cert)
{
SigningContact = "Jane Smith",
SigningLocation = "New York, NY",
SigningReason = "Contract Approval"
};
pdf.Sign(signature);
pdf.SaveAsRevision("signed-contract.pdf");
ImportsIronPdfImportsSystem.Security.Cryptography.X509CertificatesDim renderer As New ChromePdfRenderer()Dim pdf = renderer.RenderHtmlAsPdf("<h1>Contract Agreement</h1><p>Terms and conditions.</p>")' Watermarkpdf.ApplyWatermark( "<div style='font-size:72px;color:red;opacity:0.3;'>DRAFT</div>", rotation:=45, opacity:=30)' Encryption and permissionspdf.SecuritySettings.UserPassword = "user123"pdf.SecuritySettings.OwnerPassword = "owner456"pdf.SecuritySettings.AllowUserPrinting = IronPdf.Security.PdfPrintSecurity.NoPrintpdf.SecuritySettings.AllowUserCopyPasteContent = False' Digital signatureDim cert = X509CertificateLoader.LoadPkcs12FromFile("certificate.pfx", "password")Dim signature As New PdfSignature(cert) With { .SigningContact = "Jane Smith", .SigningLocation = "New York, NY", .SigningReason = "Contract Approval"}pdf.Sign(signature)pdf.SaveAsRevision("signed-contract.pdf")
Imports IronPdf
Imports System.Security.Cryptography.X509Certificates
Dim renderer As New ChromePdfRenderer()
Dim pdf = renderer.RenderHtmlAsPdf("<h1>Contract Agreement</h1><p>Terms and conditions.</p>")
' Watermark
pdf.ApplyWatermark(
"<div style='font-size:72px;color:red;opacity:0.3;'>DRAFT</div>",
rotation:=45,
opacity:=30
)
' Encryption and permissions
pdf.SecuritySettings.UserPassword = "user123"
pdf.SecuritySettings.OwnerPassword = "owner456"
pdf.SecuritySettings.AllowUserPrinting = IronPdf.Security.PdfPrintSecurity.NoPrint
pdf.SecuritySettings.AllowUserCopyPasteContent = False
' Digital signature
Dim cert = X509CertificateLoader.LoadPkcs12FromFile("certificate.pfx", "password")
Dim signature As New PdfSignature(cert) With {
.SigningContact = "Jane Smith",
.SigningLocation = "New York, NY",
.SigningReason = "Contract Approval"
}
pdf.Sign(signature)
pdf.SaveAsRevision("signed-contract.pdf")
When converting HTML supplied by users or external systems, validate the input before rendering. Sanitizing HTML helps prevent malicious scripts or unexpected content from being processed.
If your application loads external resources, restrict them to trusted domains whenever possible. Using HTTPS URLs for stylesheets, fonts, and images also improves reliability and security.
Testing the rendering process in your production environment is recommended because network configuration, authentication, resource availability, and the underlying operating system can affect the generated PDF; by contrast, PuppeteerSharp may require custom startup scripts for Azure App Service, which can complicate deployment compared with IronPDF.
My favorite library of this kind is IronPDF. It allows for fast and efficient manipulation of PDF files. It also has many valuable features, like exporting to PDF/A format and digitally signing PDF documents.
IronOCR means we can save $40,000 annually from manual processing, while enhancing productivity and freeing up resources for high-impact tasks. I would highly recommend it.
The IronSuite play a crucial role in our operations. These are tools that increase efficiencies across the business including creating floor plans and improving inventory management.
Deploying HTML to PDF conversion in cloud environments requires specific configuration for headless rendering, temporary file paths, and resource allocation. This section covers the most common cloud platforms and containerized deployments with IronPDF.
Platform
Min Resources
Package
AutoConfig
Temp Path
Key Gotcha
Azure App Service
B1 tier (Basic)
IronPdf.Linux
true
/tmp
Free/Shared tiers fail (no GPU, low memory)
Azure Functions (Windows)
B1 tier
IronPdf
true
/tmp
Uncheck "Run from package file"
AWS Lambda
512 MB / 60s timeout
IronPdf.Linux
true
/tmp (required)
Default filesystem is read-only
Docker (Ubuntu/Debian)
Image-dependent
IronPdf.Linux
false
Image default
Set false (Dockerfile handles deps)
How to Deploy on Azure
When deploying to Azure Functions or App Service, disable GPU acceleration and ensure your hosting tier provides enough memory for Chrome-based rendering. Add these settings at application startup, before any rendering calls.
Azure sandboxes run headless with no GPU access, and Free/Shared tiers (F1, D1) lack the resources Chrome requires. Target a B1 (Basic) tier or higher.
using IronPdf;// Azure sandboxes block GPU access, always disableIronPdf.Installation.ChromeGpuMode = IronPdf.Engines.Chrome.ChromeGpuModes.Disabled;// Required on non-GUI Linux systemsIronPdf.Installation.LinuxAndDockerDependenciesAutoConfig = true;var renderer = new ChromePdfRenderer();var pdf = renderer.RenderHtmlAsPdf("<h1>Azure PDF Report</h1>");pdf.SaveAs("azure-report.pdf");
using IronPdf;
// Azure sandboxes block GPU access, always disable
IronPdf.Installation.ChromeGpuMode = IronPdf.Engines.Chrome.ChromeGpuModes.Disabled;
// Required on non-GUI Linux systems
IronPdf.Installation.LinuxAndDockerDependenciesAutoConfig = true;
var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderHtmlAsPdf("<h1>Azure PDF Report</h1>");
pdf.SaveAs("azure-report.pdf");
ImportsIronPdf' Azure sandboxes block GPU access, always disableIronPdf.Installation.ChromeGpuMode = IronPdf.Engines.Chrome.ChromeGpuModes.Disabled' Required on non-GUI Linux systemsIronPdf.Installation.LinuxAndDockerDependenciesAutoConfig = TrueDim renderer As New ChromePdfRenderer()Dim pdf = renderer.RenderHtmlAsPdf("<h1>Azure PDF Report</h1>")pdf.SaveAs("azure-report.pdf")
Imports IronPdf
' Azure sandboxes block GPU access, always disable
IronPdf.Installation.ChromeGpuMode = IronPdf.Engines.Chrome.ChromeGpuModes.Disabled
' Required on non-GUI Linux systems
IronPdf.Installation.LinuxAndDockerDependenciesAutoConfig = True
Dim renderer As New ChromePdfRenderer()
Dim pdf = renderer.RenderHtmlAsPdf("<h1>Azure PDF Report</h1>")
pdf.SaveAs("azure-report.pdf")
Caution: Azure App Service Free and Shared tiers (F1, D1) do not have enough resources for Chrome-based PDF rendering. Use at minimum a B1 (Basic) tier or higher to avoid out-of-memory errors and process timeouts.
AWS Lambda requires Docker-based deployment for Chrome-based PDF rendering. The default Lambda filesystem is read-only, so all temp and deployment paths must point to /tmp.
Configure these settings at the top of your function handler, before any rendering calls.
using Amazon.Lambda.Core;using IronPdf;public class PdfFunction{ public stringFunctionHandler(string input, ILambdaContext context) { // Lambda's only writable directory var tmpPath = "/tmp/";IronPdf.Installation.TempFolderPath = tmpPath;IronPdf.Installation.CustomDeploymentDirectory = tmpPath;IronPdf.Installation.ChromeGpuMode = IronPdf.Engines.Chrome.ChromeGpuModes.Disabled; // Let IronPDF install Chrome dependencies on first cold startIronPdf.Installation.LinuxAndDockerDependenciesAutoConfig = true; context.Logger.LogLine("Rendering PDF..."); var renderer = new ChromePdfRenderer(); var pdf = renderer.RenderHtmlAsPdf(input); // Save to /tmp before uploading to S3 or returning var outputPath = $"{tmpPath}output.pdf"; pdf.SaveAs(outputPath); return outputPath; }}
using Amazon.Lambda.Core;
using IronPdf;
public class PdfFunction
{
public string FunctionHandler(string input, ILambdaContext context)
{
// Lambda's only writable directory
var tmpPath = "/tmp/";
IronPdf.Installation.TempFolderPath = tmpPath;
IronPdf.Installation.CustomDeploymentDirectory = tmpPath;
IronPdf.Installation.ChromeGpuMode = IronPdf.Engines.Chrome.ChromeGpuModes.Disabled;
// Let IronPDF install Chrome dependencies on first cold start
IronPdf.Installation.LinuxAndDockerDependenciesAutoConfig = true;
context.Logger.LogLine("Rendering PDF...");
var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderHtmlAsPdf(input);
// Save to /tmp before uploading to S3 or returning
var outputPath = $"{tmpPath}output.pdf";
pdf.SaveAs(outputPath);
return outputPath;
}
}
ImportsAmazon.Lambda.CoreImportsIronPdfPublic Class PdfFunction Public Function FunctionHandler(input AsString, context AsILambdaContext) AsString ' Lambda's only writable directory Dim tmpPath AsString = "/tmp/"IronPdf.Installation.TempFolderPath = tmpPathIronPdf.Installation.CustomDeploymentDirectory = tmpPathIronPdf.Installation.ChromeGpuMode = IronPdf.Engines.Chrome.ChromeGpuModes.Disabled ' Let IronPDF install Chrome dependencies on first cold startIronPdf.Installation.LinuxAndDockerDependenciesAutoConfig = True context.Logger.LogLine("Rendering PDF...") Dim renderer As New ChromePdfRenderer() Dim pdf = renderer.RenderHtmlAsPdf(input) ' Save to /tmp before uploading to S3 or returning Dim outputPath AsString = $"{tmpPath}output.pdf" pdf.SaveAs(outputPath) Return outputPath End FunctionEnd Class
Imports Amazon.Lambda.Core
Imports IronPdf
Public Class PdfFunction
Public Function FunctionHandler(input As String, context As ILambdaContext) As String
' Lambda's only writable directory
Dim tmpPath As String = "/tmp/"
IronPdf.Installation.TempFolderPath = tmpPath
IronPdf.Installation.CustomDeploymentDirectory = tmpPath
IronPdf.Installation.ChromeGpuMode = IronPdf.Engines.Chrome.ChromeGpuModes.Disabled
' Let IronPDF install Chrome dependencies on first cold start
IronPdf.Installation.LinuxAndDockerDependenciesAutoConfig = True
context.Logger.LogLine("Rendering PDF...")
Dim renderer As New ChromePdfRenderer()
Dim pdf = renderer.RenderHtmlAsPdf(input)
' Save to /tmp before uploading to S3 or returning
Dim outputPath As String = $"{tmpPath}output.pdf"
pdf.SaveAs(outputPath)
Return outputPath
End Function
End Class
Please note: Configure your Lambda function with at least 512 MB of memory and a 60-second timeout minimum. Chrome-based rendering is memory-intensive, and cold starts require additional initialization time for the embedded browser engine.
For Docker deployments, use the IronPdf.Linux NuGet package to reduce image size and avoid runtime asset downloads. This package includes pre-bundled Linux-native binaries optimized for containerized environments.
Set LinuxAndDockerDependenciesAutoConfig = false when your Dockerfile already installs Chrome's shared-library dependencies via apt-get. The runtime auto-install is redundant in that case and can cause permission errors or longer cold starts.
Platform
Package
Key Configuration
Ubuntu 22.04 / Debian
IronPdf.Linux
Default, works out of the box
Alpine Linux
IronPdf.Linux
Install chromium via apk in Dockerfile
Amazon Linux 2
IronPdf.Linux
Use LinuxAndDockerDependenciesAutoConfig = true
Windows Containers
IronPdf
No additional configuration required
A minimal multi-stage Dockerfile for an Ubuntu/Debian-based image:
FROM mcr.microsoft.com/dotnet/sdk:10.0 AS build
WORKDIR /app
COPY . .
RUN dotnet publish -c Release -o /out
FROM mcr.microsoft.com/dotnet/aspnet:10.0
# Install Chrome dependencies for PDF rendering
RUN apt-get update && apt-get install -y \
libglib2.0-0 libnss3 libatk1.0-0 libatk-bridge2.0-0 \
libcups2 libdrm2 libxkbcommon0 libxcomposite1 \
libxdamage1 libxrandr2 libgbm1 libpango-1.0-0 \
libcairo2 libasound2 libxshmfence1 && \
rm -rf /var/lib/apt/lists/*
WORKDIR /app
COPY --from=build /out .
ENTRYPOINT ["dotnet", "MyApp.dll"]
Text
using IronPdf;// Dependencies handled by Dockerfile apt-get, disable runtime installIronPdf.Installation.LinuxAndDockerDependenciesAutoConfig = false;// No GPU in containersIronPdf.Installation.ChromeGpuMode = IronPdf.Engines.Chrome.ChromeGpuModes.Disabled;var renderer = new ChromePdfRenderer();var pdf = renderer.RenderHtmlAsPdf("<h1>Dockerized PDF</h1>");pdf.SaveAs("output.pdf");
using IronPdf;
// Dependencies handled by Dockerfile apt-get, disable runtime install
IronPdf.Installation.LinuxAndDockerDependenciesAutoConfig = false;
// No GPU in containers
IronPdf.Installation.ChromeGpuMode = IronPdf.Engines.Chrome.ChromeGpuModes.Disabled;
var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderHtmlAsPdf("<h1>Dockerized PDF</h1>");
pdf.SaveAs("output.pdf");
ImportsIronPdf' Dependencies handled by Dockerfile apt-get, disable runtime installIronPdf.Installation.LinuxAndDockerDependenciesAutoConfig = False' No GPU in containersIronPdf.Installation.ChromeGpuMode = IronPdf.Engines.Chrome.ChromeGpuModes.DisabledDim renderer As New ChromePdfRenderer()Dim pdf = renderer.RenderHtmlAsPdf("<h1>Dockerized PDF</h1>")pdf.SaveAs("output.pdf")
Imports IronPdf
' Dependencies handled by Dockerfile apt-get, disable runtime install
IronPdf.Installation.LinuxAndDockerDependenciesAutoConfig = False
' No GPU in containers
IronPdf.Installation.ChromeGpuMode = IronPdf.Engines.Chrome.ChromeGpuModes.Disabled
Dim renderer As New ChromePdfRenderer()
Dim pdf = renderer.RenderHtmlAsPdf("<h1>Dockerized PDF</h1>")
pdf.SaveAs("output.pdf")
A real gotcha I came across with the Docker setup: IronPdfEngine (the Docker image) runs as a single instance, so the engine itself does not scale horizontally. The fix-around is simple. Any app using the IronPdf library, with or without IronPdfEngine, scales horizontally just by spinning up new instances, and the workload spreads across them quite easily.
How can HTML-to-PDF performance be optimized and scaled in .NET Core?
IronPDF's Chromium engine already renders quickly on modern hardware, but throughput can be multiplied by batching renders, enabling multi-threading, and trimming Headless Chrome overhead. The tips below apply equally to all .NET versions.
1. Batch renders on a background thread pool
IronPdf.License.LicenseKey = "YourLicenseKey";ChromePdfRenderer renderer = new ChromePdfRenderer();// Set rendering optionsrenderer.RenderingOptions.PaperSize = IronPdf.Rendering.PdfPaperSize.A4;renderer.RenderingOptions.PaperOrientation = IronPdf.Rendering.PdfPaperOrientation.Portrait;renderer.RenderHtmlFileAsPdf(@"testFile.html").SaveAs("GeneratedFile.pdf");
IronPdf.License.LicenseKey = "YourLicenseKey";
ChromePdfRenderer renderer = new ChromePdfRenderer();
// Set rendering options
renderer.RenderingOptions.PaperSize = IronPdf.Rendering.PdfPaperSize.A4;
renderer.RenderingOptions.PaperOrientation = IronPdf.Rendering.PdfPaperOrientation.Portrait;
renderer.RenderHtmlFileAsPdf(@"testFile.html").SaveAs("GeneratedFile.pdf");
ImportsIronPdfLicense.LicenseKey = "YourLicenseKey"Dim renderer As New ChromePdfRenderer()' Set rendering optionsrenderer.RenderingOptions.PaperSize = Rendering.PdfPaperSize.A4renderer.RenderingOptions.PaperOrientation = Rendering.PdfPaperOrientation.Portraitrenderer.RenderHtmlFileAsPdf("testFile.html").SaveAs("GeneratedFile.pdf")
Imports IronPdf
License.LicenseKey = "YourLicenseKey"
Dim renderer As New ChromePdfRenderer()
' Set rendering options
renderer.RenderingOptions.PaperSize = Rendering.PdfPaperSize.A4
renderer.RenderingOptions.PaperOrientation = Rendering.PdfPaperOrientation.Portrait
renderer.RenderHtmlFileAsPdf("testFile.html").SaveAs("GeneratedFile.pdf")
ChromePdfRenderer is thread-safe; a single instance may serve dozens of concurrent tasks without deadlocks.
Parallel.ForEach saturates every CPU core, improving throughput compared with a single-thread loop.
IronPdf.License.LicenseKey = "YourLicenseKey"
Dim pdf As PdfDocument = PdfDocument.FromFile("1.pdf")
Dim pdf2 As PdfDocument = PdfDocument.FromFile("2.pdf")
pdf.AppendPdf(pdf2)
pdf.SaveAs("appendedFile.pdf")
Live DevTools traces expose missing fonts, 404 images, and timing events without re-compiling code.
5. Reuse template PDFs instead of re-rendering
For invoice runs, create a template PDF with placeholders like [[name]] and perform a text replace instead of rebuilding complex HTML. It avoids re-rendering complex HTML and is memory-light.
IronPDF is the solution of choice for many teams when it comes to C# PDF generation thanks to its robust Chromium-powered rendering engine, intuitive APIs and frequent product enhancements. Let's compare IronPDF with other PDF converters to find the best fit for your PDF generation needs.
Free and Open-Source Alternatives
Some tools that might come into consideration:
PuppeteerSharp: an MIT-licensed .NET port of Puppeteer that drives headless Chrome.
Playwright for .NET: Microsoft's Apache-2.0 automation library, also Chromium-based.
wkhtmltopdf: a long-standing standalone HTML-to-PDF binary.
Native browser routes: print-to-PDF straight from a headless browser or OS print driver.
A distinction worth drawing first: PuppeteerSharp and Playwright are browser-automation frameworks rather than PDF libraries. They expose a print-to-PDF call on top of real Chromium, so rendering fidelity is excellent, but PDF specifics like headers and footers, encryption, signatures, and PDF/A, along with the browser's lifecycle, are left to you: shipping and updating the Chromium binary, handling concurrency and crash recovery, and building document structure by hand. Playwright adds a constraint worth knowing early: its PdfAsync runs only in headless Chromium (not Firefox or WebKit), so deployments must guarantee a headless Chrome, which matters in containers and serverless.
wkhtmltopdf sits differently again. The project was archived in 2024, and its final release (0.12.6, 2020) runs a ~2012 Qt WebKit engine receiving no further security patches, including an unpatched critical SSRF advisory (CVE-2022-35583); it remains workable for simple static documents on trusted input, but less so for public-facing output. Native browser routes need no library at all, at the cost of any .NET-native PDF API or real control over server-side automation.
For prototypes, internal tools, and zero-budget work, these are legitimate choices. The comparison below covers the commercial libraries feature by feature.
Quick Decision Matrix: IronPDF versus .NET PDF Converters
Solution
When to use
Best for
IronPDF
Converting modern websites/HTML to PDF with exact visual fidelity.
Enterprise applications requiring reliable HTML rendering engine, dynamic content, and professional support.
wkhtmltopdf
Simple HTML conversion in non-critical applications where outdated rendering is acceptable.
Basic document generation with legacy HTML/CSS.
Syncfusion
When already invested in Syncfusion ecosystem or eligible for free community license.
Organizations using multiple Syncfusion components.
Aspose.PDF
Complex PDF manipulation when HTML rendering quality is less critical.
Extensive PDF editing features beyond HTML conversion.
Real-life HTML to PDF Conversion Comparison: Rendering Reddit's Homepage
To evaluate the output PDF quality, we tested these libraries with Reddit's homepage containing dynamic web content, modern CSS, and JavaScript HTML elements. This page serves as an ideal test case for output PDF generation.
IronPDF delivers pixel-perfect results, preserving all dynamic web content, modern web fonts styling, and interactive elements exactly as displayed in Chrome, all in just a few lines of code.
Syncfusion
Syncfusion rendered PDF with most sections and styling missing, especially dynamic content. Initially blocked by Reddit's security. Achieving better results requires extensive command-line tuning, yet output remains incomplete.
Aspose.PDF
Aspose.PDF required manual HTML download first (no direct URL support). After conversion, output lacked proper formatting and missed nearly all content sections, making it unsuitable for modern web with dynamic content.
wkhtmltopdf
wkhtmltopdf completed quickly but produced a plain, static page missing critical content like live updates, dynamic elements, and interactive sections. This demonstrates wkhtmltopdf's incompatibility with modern, JavaScript-driven websites.
Conclusion on Performance and Output PDF Quality
For .NET developers needing a reliable HTML to PDF converter, IronPDF stands out with minimal code, easy-to-use APIs, and frequent product enhancements.
In a real-world test on web content, it delivered the fastest, most accurate results while Syncfusion lagged behind, Aspose required extra steps, and wkhtmltopdf missed modern styling. IronPDF offers the best balance of speed, accuracy, and simplicity for today's HTML to PDF conversion workflows.
Verified on IronPDF v2026.8.1 · .NET 10 · July 2026.
Please note: Aspose, Syncfusion, and wkhtmltopdf are trademarks of their respective owners. This site is not affiliated with or endorsed by them. All names, logos, and brands belong to their owners, and comparisons are based on publicly available information at the time of writing.
Summary
This guide covered everything needed to convert HTML to PDF in .NET: from basic string conversion to advanced features like async processing, digital signatures, and batch generation. We demonstrated three conversion methods, essential configurations, advanced features and security settings, and compared IronPDF with other libraries through real-world testing of dynamic document generation.
While competitors struggled with modern websites or required complex workarounds, IronPDF delivered flawless results with minimal code and powerful rendering engine.
Ready to streamline your PDF workflow and experience versatile PDF generation in just a few lines of code? Install IronPDF through NuGet Package Manager (or select Manage NuGet Package in Visual Studio) and convert your first HTML to PDF today.
Start your free 30-day trial for production testing without watermarks. Flexible licensing starts at $999 with transparent team pricing that scales with your needs. Once you have a license, add it at the start of your application with IronPdf.License.LicenseKey = "KEY";.
Having trouble with the following errors in HTML to PDF conversion? IronPDF engineers provide support 24/7; live chat via the widget on https://ironpdf.com/ is available 24/5.
Quick Fixes on Common Errors
Slow first render? Normal. Chrome initializes in 2-3s, then speeds up.
Cloud issues? Use at least Azure B1 or equivalent resources.
Missing assets? Set base paths or embed as base64.
Missing elements? Add RenderDelay for JavaScript execution.
Memory in rendering? Update to the latest version (v2026.8.1) for fixes in HTML to PDF, stamps, and headers/footers.
Form field issues (e.g., long textareas, checkboxes)? Fixed in v2025.7.17; ensure unique names for checkboxes.
Custom header/footer clipping or special characters corrupted? Resolved in v2025.8.8; test word-wrapping and metadata.
Common Issues and Troubleshooting
Images Don't Appear
Ensure that image URLs are accessible during rendering. If the images are stored locally, use absolute file paths or embed them directly in the HTML.
CSS Styles Are Missing
Verify that all CSS files are available and that the paths are correct. If possible, use absolute URLs for external stylesheets.
JavaScript Content Doesn't Render
If the page loads data asynchronously, configure the renderer to wait for JavaScript execution before generating the PDF.
External Fonts Are Missing
Make sure custom web fonts can be accessed during rendering. Alternatively, embed fonts directly into the HTML using @font-face.
HTML Looks Different in the PDF
Browsers and printed pages use different layouts. Each html element can render differently on paper than it does on screen, so consider creating a dedicated print stylesheet using @media print to optimize the output.
Get Help From The Engineers Who Built IronPDF, 24/7
To convert HTML to PDF in C#, you can use the IronPDF library. Install it from NuGet and use the `ChromePdfRenderer.RenderHtmlAsPdf()` method to convert HTML strings, URLs, or files to PDFs with pixel-perfect accuracy.
What is the advantage of using IronPDF for HTML to PDF conversion?
IronPDF uses a robust Chrome-based engine to provide accurate HTML to PDF conversion with support for CSS3, HTML5, and JavaScript, ensuring a high-fidelity output that matches the web content perfectly.
Can IronPDF handle JavaScript in HTML to PDF conversion?
Yes, IronPDF fully supports JavaScript and AJAX during the HTML to PDF conversion process, which is particularly useful for rendering dynamic web pages and single-page applications.
What are some common use cases for converting HTML to PDF?
Common use cases include generating invoices, reports, certificates, and archiving web content like receipts, all while utilizing existing web design language and templates.
Does IronPDF support batch processing for generating multiple PDFs?
Yes, IronPDF supports batch processing, allowing you to generate multiple PDFs efficiently using HTML templates and libraries like Handlebars.NET for dynamic content rendering.
Can I create fillable PDF forms from HTML using IronPDF?
Yes, IronPDF allows you to convert HTML forms into fillable PDF fields by enabling the `CreatePdfFormsFromHtml` rendering option. This preserves HTML form elements as interactive fields in the PDF.
Is it possible to deploy IronPDF on cloud platforms like Azure or AWS?
IronPDF can be deployed on cloud platforms such as Azure and AWS, with specific configuration settings to ensure compatibility with headless rendering environments.
How do I secure PDFs generated with IronPDF?
IronPDF provides features to secure PDFs with password protection, permissions, and advanced encryption algorithms. You can also add digital signatures to ensure document authenticity.
What makes IronPDF different from other .NET PDF libraries?
IronPDF stands out due to its use of a Chromium rendering engine that provides high-fidelity conversion of modern web elements, including complete support for JavaScript and CSS3, making it suitable for enterprise-level applications.
How can I render only specific HTML elements to a PDF using IronPDF?
You can render specific HTML elements to PDF by isolating the target element in your HTML and using JavaScript rendering options or HTML parsing libraries to extract and render only the desired content.
Jacob Mellor is Chief Technology Officer at Iron Software and a visionary engineer pioneering C# PDF technology. As the original developer behind Iron Software's core codebase, he has shaped the company's product architecture since its inception, transforming it alongside CEO Cameron Rimington into a 50+ person company serving NASA, Tesla, and global government agencies.