Convert HTML to PDF Report in .NET
In this post I will teach you how to convert html to pdf report in .NET. All with live working demo.

On this page
What you'll learn
Converting HTML to PDF is a common requirement in many software applications. The need arises to create PDF versions of HTML documents for archiving or printing purposes, or to generate reports, invoices, and other types of documents. In this article, we will explore different approaches to convert HTML to PDF using .NET.Why it matters
HTML is a markup language that is designed to be displayed in web browsers. However, it is not designed to be printed or saved as a document. Converting HTML to PDF allows you to preserve the original layout, formatting, and graphics of the HTML document, as well as to add features such as headers, footers, and page numbers. HTML5 combined with CSS3 gives the most powerful and flexible and dynamic layout that can used easily converted to PDF using print media query.Implementation
There are several ways to convert HTML to PDF using .NET. Some of the popular methods include:
- Using wkhtmltopdf
- Using Chrome Headless
- Using Selenium WebDriver
- Using window.print()
- Using a dedicated .NET PDF library (IronPDF)
Using wkhtmltopdf
wkhtmltopdf is a command-line tool that converts HTML to PDF using the WebKit rendering engine. To use wkhtmltopdf in .NET,
- Download and install wkhtmltopdf latest version from here.
- Use the below code.
- And call the method as HtmlToPdf("test", new string[] { "https://www.google.com" }, new string[] { "-s A5" });
- If you need to convert HTML string to PDF, the tweak the above method and replace the Arguments to Process StartInfo as $@"/C echo | set /p=""{htmlText}"" | ""{pdfHtmlToPdfExePath}"" {((options == null) ? "" : string.Join(" ", options))} - ""C:\Users\xxxx\Desktop\{outputFilename}""";
public static string HtmlToPdf(string outputFilenamePrefix, string[] urls,
string[] options = null,
string pdfHtmlToPdfExePath = @"C:\Program Files\wkhtmltopdf\bin\wkhtmltopdf.exe")
{
string urlsSeparatedBySpaces = string.Empty;
try
{
//Determine inputs
if ((urls == null) || (urls.Length == 0))
throw new Exception("No input URLs provided for HtmlToPdf");
else
urlsSeparatedBySpaces = String.Join(" ", urls); //Concatenate URLs
string outputFilename = outputFilenamePrefix + "_" + DateTime.Now.ToString("yyyy-MM-dd-hh-mm-ss-fff") + ".PDF"; // assemble destination PDF file name
var p = new System.Diagnostics.Process()
{
StartInfo =
{
FileName = pdfHtmlToPdfExePath,
Arguments = ((options == null) ? "" : string.Join(" ", options)) + " " + urlsSeparatedBySpaces + " " + outputFilename,
UseShellExecute = false, // needs to be false in order to redirect output
RedirectStandardOutput = true,
RedirectStandardError = true,
RedirectStandardInput = true, // redirect all 3, as it should be all 3 or none
WorkingDirectory = Path.Combine(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location))
}
};
p.Start();
// read the output here...
var output = p.StandardOutput.ReadToEnd();
var errorOutput = p.StandardError.ReadToEnd();
// ...then wait n milliseconds for exit (as after exit, it can't read the output)
p.WaitForExit(60000);
// read the exit code, close process
int returnCode = p.ExitCode;
p.Close();
// if 0 or 2, it worked so return path of pdf
if ((returnCode == 0) || (returnCode == 2))
return outputFilename;
else
throw new Exception(errorOutput);
}
catch (Exception exc)
{
throw new Exception("Problem generating PDF from HTML, URLs: " + urlsSeparatedBySpaces + ", outputFilename: " + outputFilenamePrefix, exc);
}
}
Drawbacks using wkhtmltopdf
- The latest build of wkhtmltopdf as of writing this article does not support latest HTML5 and CSS3. Hence if you try to export any html that as CSS GRID then the output will not be as expected.
- You need to handle concurrency issues.
Using Chrome Headless
Chrome headless is a feature of the Google Chrome browser that allows you to run Chrome in a headless environment, without a graphical user interface. This feature can be used to convert HTML to PDF by printing the HTML document to a PDF file. To use chrome headless in .NET,
- Download and install Chrome headless latest version from here.
- Use the below code.
- This will convert html file to pdf file.
- If you need to convert some url to pdf then use the following as Argument to Process StartInfo @"/C --headless --disable-gpu --run-all-compositor-stages-before-draw --print-to-pdf-no-header --print-to-pdf=""C:/Users/Abdul Rahman/Desktop/test.pdf"" ""https://www.google.com"""
var p = new System.Diagnostics.Process()
{
StartInfo =
{
FileName = "C:/Program Files (x86)/Google/Chrome/Application/chrome.exe",
Arguments = @"/C --headless --disable-gpu --run-all-compositor-stages-before-draw --print-to-pdf-no-header --print-to-pdf=""C:/Users/Abdul Rahman/Desktop/test.pdf"" ""C:/Users/Abdul Rahman/Desktop/grid.html""",
}
};
p.Start();
// ...then wait n milliseconds for exit (as after exit, it can't read the output)
p.WaitForExit(60000);
// read the exit code, close process
int returnCode = p.ExitCode;
p.Close();
Drawbacks using Chrome Headless
- This works as expected with latest HTML5 and CSS3 features. Output will be same as you view in browser but when running this via IIS you need to run the AppliactionPool of your application under LocalSystem Identity or you need to provide read/write access to IISUSRS .
Using Selenium Webdriver
Selenium WebDriver is a popular Nuget package used for automating web browsers. It can be used to open a webpage and interact with it programmatically, including printing the page. To use Selenium Webdriver in .NET,
- Install Nuget Packages Selenium.WebDriver and Selenium.WebDriver.ChromeDriver.
- Use the below code.
public async Task<byte[]> ConvertHtmlToPdf(string html)
{
var directory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonDocuments), "ApplicationName");
Directory.CreateDirectory(directory);
var filePath = Path.Combine(directory, $"{Guid.NewGuid()}.html");
await File.WriteAllTextAsync(filePath, html);
var driverOptions = new ChromeOptions();
// In headless mode, PDF writing is enabled by default (tested with driver major version 85)
driverOptions.AddArgument("headless");
using var driver = new ChromeDriver(driverOptions);
driver.Navigate().GoToUrl(filePath);
// Output a PDF of the first page in A4 size at 90% scale
var printOptions = new Dictionary<string, object>
{
{ "paperWidth", 210 / 25.4 },
{ "paperHeight", 297 / 25.4 },
{ "scale", 0.9 },
{ "pageRanges", "1" }
};
var printOutput = driver.ExecuteChromeCommandWithResult("Page.printToPDF", printOptions) as Dictionary<string, object>;
var pdf = Convert.FromBase64String(printOutput["data"] as string);
File.Delete(filePath);
return pdf;
}
Drawbacks using Selenium WebDriver
- This approach needs latest chrome browser to be installed in the server where the app runs.
- If the chrome browser version in server is updated then Selenium.WebDriver.ChromeDriver Nuget package needs to be updated. Else this will throw run time error due to version mismatch.
Advantages using Selenium WebDriver
- This just needs an Nuget installation and works as expected with latest HTML5 and CSS3 features. Output will be same as you view in browser.
Note:The above drawbacks can be overcome if we are running app in docker . All we need to do is to install chrome when building app image using Dockerfile.
Note:With this approach, please make sure to add <PublishChromeDriver>true</PublishChromeDriver> in .csproj file as shown below:
<PropertyGroup>
<TargetFramework>net5.0</TargetFramework>
<LangVersion>latest</LangVersion>
<Nullable>enable</Nullable>
<PublishChromeDriver>true</PublishChromeDriver>
</PropertyGroup>
This will publish the chrome driver when publishing the project.
Using window.print()
If the users are using your app from browser then you can rely on JavaScript and use window.print() and necessary print media css to generate PDF from the browser. For example generating invoice from browser in an inventory app.
export function printWindow() {
return window.print();
}
Drawbacks using window.print()
- In SPA like Blazor, we need to do some workaround with iframe to print sections of page.
Advantages using window.print()
- No dependency on any tools.
- PDF generated directly from HTML, CSS and JS in browser.
- Faster
- Supports all the latest CSS properties.
Using a Dedicated .NET PDF Library (IronPDF)
Another option for converting HTML to PDF in .NET is a dedicated library that includes its own rendering engine. For example, IronPDF provides a Chromium-based HTML-to-PDF API for C# applications. Unlike manually launching Chrome Headless or using Selenium WebDriver, IronPDF manages its rendering dependencies through its .NET package and does not require a separately installed Chrome browser or ChromeDriver for typical deployments.
Install IronPDF using NuGet:
Install-Package IronPdf
Generate a PDF from HTML with a custom footer:
using IronPdf;
var renderer = new ChromePdfRenderer();
renderer.RenderingOptions.HtmlFooter = new HtmlHeaderFooter
{
MaxHeight = 15,
HtmlFragment =
"<div style='text-align:center'>Page {page} of {total-pages}</div>"
};
renderer.RenderingOptions.MarginBottom = 25;
var pdf = renderer.RenderHtmlAsPdf(
"<h1>Monthly Report</h1><p>Report content</p>"
);
pdf.SaveAs("report.pdf");
Advantages:
- Modern HTML and CSS: Chromium-based rendering supports CSS Grid, Flexbox, JavaScript, and web fonts, addressing limitations of wkhtmltopdf's older rendering engine.
- Simpler browser dependency management: Developers do not need to maintain a separate ChromeDriver installation or manually launch Chrome for each PDF conversion.
- Server-side PDF generation: Reports can be generated from HTML strings, local files, or URLs without requiring users to open a browser print dialog.
- Headers, footers, and page numbers: Built-in rendering options provide reusable page numbering and custom report layouts.
- Asynchronous and concurrent rendering: IronPDF supports asynchronous rendering and multithreaded workloads, although resource usage and concurrency limits still need to be managed.
When should you use it?
For frontend printing, window.print() remains a simple free option. Selenium or Chrome Headless can also work well for backend PDF generation, especially when browser automation infrastructure already exists.
IronPDF is worth considering when an application needs server-side PDF generation, modern CSS support, built-in report formatting, and a managed .NET API without manually maintaining a separate browser and driver installation.
Sponsored: This section is sponsored by IronPDF. See the IronPDF HTML-to-PDF tutorial for additional examples.
Summary
In this article we learn't how to convert HTML to PDF in .NET. Converting HTML to PDF is a common requirement in many software applications. There are several ways to convert HTML to PDF using .NET. The most preferred approach is to use browser window.print() in front end apps and use Selenium Webdriver in backend API's.