Skip to footer content
USING IRONPDF

How to Convert HTML to PDF Using IronPDF

IronPDF is a .NET HTML to PDF converter that uses Chrome's rendering engine to transform HTML strings, files, and web pages into high-quality PDF documents with accurate CSS rendering and JavaScript execution support.

Converting HTML to PDF is a persistent challenge in .NET development. You need a library that handles modern CSS layouts, executes JavaScript properly, and produces quality documents -- all while remaining straightforward to integrate. IronPDF addresses these challenges with Chrome-based rendering, letting you convert HTML files, strings, and web pages with browser-quality fidelity. The library runs on .NET 10 and targets Windows, Linux, macOS, and Azure without requiring separate rendering engines per platform.

This article explains how to implement professional PDF generation, from basic conversions to advanced features like digital signatures and password protection. You will work through installation, configuration, core conversion methods, and deployment considerations. Each section includes working C# code using top-level statements, compatible with .NET 10 projects.

IronPDF C# PDF Library homepage banner showing key features including HTML to PDF conversion, PDF editing capabilities, flexible deployment options, and free trial offer

How Do You Choose the Right HTML to PDF Library for .NET?

Choosing a PDF library affects rendering quality, maintenance costs, and long-term compatibility. The fundamental question is whether the library keeps pace with the modern web. CSS grids, flexbox, JavaScript-rendered content, and web fonts are standard today -- a library that cannot handle them reliably forces you into preprocessing workarounds that slow development and introduce fragility at the point where your HTML templates evolve.

IronPDF uses the same Blink engine powering Google Chrome. Your PDFs render exactly as they appear in Chrome's print preview -- no missing styles, no broken grid layouts, no dropped custom fonts. This consistency eliminates the manual style debugging that typically accompanies other PDF libraries. You can compare Chrome rendering capabilities against older alternatives to evaluate rendering fidelity for your specific document types.

Modern web applications rely on sophisticated CSS and JavaScript. IronPDF provides native support for CSS3, including flexbox, grid systems, transforms, and animations. The engine processes JavaScript before capturing output, ensuring dynamically generated content appears correctly in the final PDF. Whether you are converting static HTML files or pages that rely on client-side rendering, the library captures the final computed state -- not an intermediate snapshot.

The ChromePdfRenderer class exposes intelligent defaults while providing fine-grained control through its RenderingOptions property. The integration path is shorter than alternatives like QuestPDF or Syncfusion, both of which require more configuration boilerplate to produce a first output document.

When considering long-term maintenance, Chrome-based rendering means the library benefits from ongoing browser improvements without requiring manual engine updates on your part. Older WebKit-based libraries have fixed feature sets that do not grow with the web platform, which creates compatibility debt as your front-end templates adopt new CSS properties or JavaScript patterns. For teams already familiar with HTML and CSS, there is no new language or layout model to learn -- you design your document in the same way you would design a web page, then render it as a PDF.

Feature overview dashboard showing four main PDF capabilities: Create PDFs, Convert PDFs, Edit PDFs, and Sign and Secure PDFs, with detailed feature lists under each category.

How Do You Install and Configure the Library?

Installing via NuGet

Setting up IronPDF takes a few minutes. Use the Package Manager Console in Visual Studio or the .NET CLI:

Install-Package IronPdf
Install-Package IronPdf
SHELL
dotnet add package IronPdf
dotnet add package IronPdf
SHELL

These commands download the package and its dependencies, configuring project references automatically. The package includes platform-specific binaries resolved at runtime, so you do not need to manage native libraries separately. For containerized environments, review Docker deployment and advanced installation options.

Configuring the License Key and Global Settings

Configure the license key and global settings in Program.cs before calling any IronPDF methods. Using .NET 10 top-level statements:

using IronPdf;

IronPdf.License.LicenseKey = Environment.GetEnvironmentVariable("IRONPDF_LICENSE_KEY")!;
IronPdf.Installation.ChromeGpuMode = IronPdf.Engines.Chrome.ChromeGpuModes.Disabled;
IronPdf.Installation.TempFolderPath = @"C:\Temp\IronPdf";
IronPdf.Installation.LinuxAndDockerDependenciesAutoConfig = true;
IronPdf.Logging.LoggingMode = IronPdf.Logging.PdfLoggingModes.All;

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.Run();
using IronPdf;

IronPdf.License.LicenseKey = Environment.GetEnvironmentVariable("IRONPDF_LICENSE_KEY")!;
IronPdf.Installation.ChromeGpuMode = IronPdf.Engines.Chrome.ChromeGpuModes.Disabled;
IronPdf.Installation.TempFolderPath = @"C:\Temp\IronPdf";
IronPdf.Installation.LinuxAndDockerDependenciesAutoConfig = true;
IronPdf.Logging.LoggingMode = IronPdf.Logging.PdfLoggingModes.All;

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.Run();
$vbLabelText   $csharpLabel

Storing the key in an environment variable keeps it out of source control. The free 30-day trial provides full functionality for evaluation. See the license documentation for all configuration options including runtime key switching for multi-tenant scenarios.

How Do You Convert HTML Strings to PDF?

Performing a Basic Conversion

The RenderHtmlAsPdf method accepts an HTML string and returns a PdfDocument object you can save, stream, or manipulate further. This is the primary entry point for generating invoices, reports, and letters from server-side templates:

using IronPdf;

var renderer = new ChromePdfRenderer();

renderer.RenderingOptions.MarginTop = 50;
renderer.RenderingOptions.MarginBottom = 50;
renderer.RenderingOptions.MarginLeft = 20;
renderer.RenderingOptions.MarginRight = 20;

var pdf = renderer.RenderHtmlAsPdf("<h1>Invoice #12345</h1><p>Total: $99.99</p>");
pdf.SaveAs("invoice.pdf");

// Get binary data for an HTTP response or cloud storage
byte[] pdfBytes = pdf.BinaryData;
using IronPdf;

var renderer = new ChromePdfRenderer();

renderer.RenderingOptions.MarginTop = 50;
renderer.RenderingOptions.MarginBottom = 50;
renderer.RenderingOptions.MarginLeft = 20;
renderer.RenderingOptions.MarginRight = 20;

var pdf = renderer.RenderHtmlAsPdf("<h1>Invoice #12345</h1><p>Total: $99.99</p>");
pdf.SaveAs("invoice.pdf");

// Get binary data for an HTTP response or cloud storage
byte[] pdfBytes = pdf.BinaryData;
$vbLabelText   $csharpLabel

The result contains selectable text for accessibility compliance. Explore custom margins and paper size options to tailor output dimensions to your design.

PDF viewer showing a simple invoice with number 12345 and total amount $99.99 displayed at 100% zoom

Applying CSS Styles, Web Fonts, and External Assets

You can embed full stylesheets directly in the HTML string. IronPDF processes @import rules and font references before rendering. When your HTML references relative paths -- local stylesheets, images, or scripts -- provide a base path as a second argument so the engine can resolve them:

using IronPdf;

var styledHtml = $@"
    <style>
        body {{ font-family: Arial, sans-serif; margin: 40px; line-height: 1.6; }}
        .header {{ color: #2563eb; border-bottom: 2px solid #e5e7eb; padding-bottom: 10px; }}
        .amount {{ font-size: 24px; font-weight: bold; color: #059669; }}
    </style>
    <div class='header'>
        <h1>Professional Invoice</h1>
        <p>Invoice Date: {DateTime.Now:MMMM dd, yyyy}</p>
    </div>
    <p class='amount'>$1,234.56</p>";

var renderer = new ChromePdfRenderer();
renderer.RenderingOptions.EnableJavaScript = true;
renderer.RenderingOptions.WaitFor.RenderDelay(500);

// Provide a base path if the HTML references local assets
var pdf = renderer.RenderHtmlAsPdf(styledHtml, @"C:\assets\");
pdf.SaveAs("styled-invoice.pdf");
using IronPdf;

var styledHtml = $@"
    <style>
        body {{ font-family: Arial, sans-serif; margin: 40px; line-height: 1.6; }}
        .header {{ color: #2563eb; border-bottom: 2px solid #e5e7eb; padding-bottom: 10px; }}
        .amount {{ font-size: 24px; font-weight: bold; color: #059669; }}
    </style>
    <div class='header'>
        <h1>Professional Invoice</h1>
        <p>Invoice Date: {DateTime.Now:MMMM dd, yyyy}</p>
    </div>
    <p class='amount'>$1,234.56</p>";

var renderer = new ChromePdfRenderer();
renderer.RenderingOptions.EnableJavaScript = true;
renderer.RenderingOptions.WaitFor.RenderDelay(500);

// Provide a base path if the HTML references local assets
var pdf = renderer.RenderHtmlAsPdf(styledHtml, @"C:\assets\");
pdf.SaveAs("styled-invoice.pdf");
$vbLabelText   $csharpLabel

CSS renders exactly as in Chrome. Explore rendering options and web font support for Google Fonts and self-hosted typeface integration.

PDF viewer displaying IronPDF for .NET logo on a white background, showing page 1 of 1 at 100% zoom

How Do You Convert HTML Files and Live URLs to PDF?

Converting Local Files and Web Pages

The RenderHtmlFileAsPdf method reads a local file and automatically resolves all linked assets relative to the file's directory. The RenderUrlAsPdf method captures public or authenticated web pages, executing JavaScript and waiting for content to load before rendering:

using IronPdf;

// Convert a local HTML file
var renderer = new ChromePdfRenderer();
renderer.RenderingOptions.PaperSize = PdfPaperSize.A4;
renderer.RenderingOptions.PrintHtmlBackgrounds = true;

var filePdf = renderer.RenderHtmlFileAsPdf("complex-report.html");
filePdf.MetaData.Title = "Monthly Sales Report";
filePdf.SaveAs("report-output.pdf");

// Convert a live URL with authentication
var secureRenderer = new ChromePdfRenderer();
secureRenderer.LoginCredentials = new ChromeHttpLoginCredentials
{
    Username = "user@example.com",
    Password = "secure-password"
};
secureRenderer.RenderingOptions.WaitFor.NetworkIdle(500);

var urlPdf = secureRenderer.RenderUrlAsPdf("https://app.example.com/dashboard");
urlPdf.SaveAs("dashboard-snapshot.pdf");
using IronPdf;

// Convert a local HTML file
var renderer = new ChromePdfRenderer();
renderer.RenderingOptions.PaperSize = PdfPaperSize.A4;
renderer.RenderingOptions.PrintHtmlBackgrounds = true;

var filePdf = renderer.RenderHtmlFileAsPdf("complex-report.html");
filePdf.MetaData.Title = "Monthly Sales Report";
filePdf.SaveAs("report-output.pdf");

// Convert a live URL with authentication
var secureRenderer = new ChromePdfRenderer();
secureRenderer.LoginCredentials = new ChromeHttpLoginCredentials
{
    Username = "user@example.com",
    Password = "secure-password"
};
secureRenderer.RenderingOptions.WaitFor.NetworkIdle(500);

var urlPdf = secureRenderer.RenderUrlAsPdf("https://app.example.com/dashboard");
urlPdf.SaveAs("dashboard-snapshot.pdf");
$vbLabelText   $csharpLabel

For publicly accessible pages, skip the LoginCredentials setup entirely. Learn about authentication and cookie management for session-based sites. To capture responsive layouts correctly, configure viewport width with renderer.RenderingOptions.ViewPortWidth and review the viewport documentation.

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");
$vbLabelText   $csharpLabel

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>");

// 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");
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");
$vbLabelText   $csharpLabel

Learn about watermarking techniques, PDF security settings, and certificate-based signing including HSM integration for hardware security modules.

How Do You Deploy Across Windows, Linux, and Azure?

IronPDF supports Windows, Linux, and macOS with platform-specific binaries included in the NuGet package. Output is identical across platforms, so you can develop on Windows and deploy to Linux containers without changing your rendering code. The package auto-detects the runtime environment and loads the correct native components. This cross-platform consistency simplifies CI/CD pipelines -- you do not need separate rendering configurations per environment.

On Azure App Service, store the license key in Application Settings and reference it via Environment.GetEnvironmentVariable. This approach keeps credentials out of your repository and allows key rotation without a code deployment. See the complete Azure deployment guide for hosting-specific settings, and the IIS deployment guide for traditional Windows server hosting.

For Linux and Docker environments, the Chrome rendering engine requires additional system dependencies. Add them to your Dockerfile:

FROM mcr.microsoft.com/dotnet/aspnet:10.0
RUN apt-get update && apt-get install -y \
    libgdiplus libnss3 libatk1.0-0 libatk-bridge2.0-0 libcups2 \
    && apt-get clean
WORKDIR /app
COPY . .
ENTRYPOINT ["dotnet", "MyApp.dll"]

When LinuxAndDockerDependenciesAutoConfig is set to true, IronPDF handles dependency resolution automatically on first run. See the Linux deployment guide and Docker integration guide for complete dependency lists. For serverless workloads, the Azure Functions guide covers memory and timeout configuration.

How Do You Explore the Full Feature Set?

Beyond HTML conversion, IronPDF covers the complete PDF workflow. The table below summarizes key capability areas:

IronPDF Capability Areas
CategoryFeaturesDocumentation
Document CreationHeaders, footers, fillable forms, backgroundsForms guide
SecurityDigital signatures, encryption, sanitizationSigning guide
Document ManagementMerge, split, compression, PDF/A complianceMerge guide
Content ManipulationStamping, JavaScript execution, async operationsStamp guide

For a complete method reference, see the API documentation and the code examples library, which includes working C# projects for each feature area. The tutorials section provides guided walkthroughs for common scenarios like invoice generation, report automation, and document archiving.

What Are the Next Steps for Getting Started?

IronPDF turns HTML to PDF conversion into a three-step workflow: install the package from NuGet, configure your license key, and call RenderHtmlAsPdf. The Chrome engine ensures accurate rendering, while the API design keeps integration straightforward even for complex multi-page documents with custom headers, watermarks, and digital signatures.

The free 30-day trial provides full access with no feature restrictions. When you are ready to move to production, flexible licensing scales from individual developers to enterprise teams with volume requirements. You can also review the Microsoft .NET documentation for background context on document generation patterns in the ecosystem, and the official PDF specification for deeper understanding of the format's capabilities and constraints.

IronPDF licensing page showing four perpetual license tiers (Lite, Plus, Professional, and Unlimited) with pricing and features for different team sizes.

Explore the changelog to see recent additions and plan which features match your project requirements.

Frequently Asked Questions

What is IronPDF used for?

IronPDF is used to convert HTML to PDF in .NET applications. It handles modern CSS, JavaScript, and produces high-quality PDF documents.

How does IronPDF handle complex HTML layouts?

IronPDF uses a Chrome-based rendering engine to accurately process complex HTML layouts, ensuring the PDF output matches what you see in your browser.

Can IronPDF execute JavaScript during PDF conversion?

Yes, IronPDF can execute JavaScript, which is crucial for rendering dynamic content accurately in the PDF output.

Is IronPDF easy to implement in .NET applications?

IronPDF is designed to be simple to implement and deploy, making it accessible for developers working with .NET.

What types of HTML sources can IronPDF convert to PDF?

IronPDF can convert HTML files, HTML strings, and entire web pages to PDF format.

Does IronPDF maintain the quality of the original HTML in the PDF?

Yes, IronPDF produces high-quality PDF documents with the same fidelity as the original HTML content.

What makes IronPDF different from other PDF converters?

IronPDF provides a seamless conversion experience with its Chrome-based rendering engine, ensuring compatibility with modern web standards.

Curtis Chau
Technical Writer

Curtis Chau holds a Bachelor’s degree in Computer Science (Carleton University) and specializes in front-end development with expertise in Node.js, TypeScript, JavaScript, and React. Passionate about crafting intuitive and aesthetically pleasing user interfaces, Curtis enjoys working with modern frameworks and creating well-structured, visually appealing manuals.

...

Read More