USING IRON SUITE

HTML to PDF C# - A Complete Guide with IronPDF

Introduction

In today’s digital age, converting HTML to PDF is a common requirement for developers. Whether it’s generating reports, invoices, legal documents, or archiving web content, producing consistent, professional PDFs can be challenging.

Traditionally, this process required manual handling of PDF structures, complex layout calculations, and extensive coding, making it time-consuming and error-prone. Modern .NET developers need a reliable solution that simplifies PDF generation while maintaining accuracy and flexibility. Beyond this, finding a library that offers full JavaScript and CSS support can make all the difference in the quality of your rendered PDF documents. This is where the library we'll be looking at today, IronPDF, comes in.

In the sections below, we’ll explore how to convert HTML to PDF in C# using IronPDF, a library that streamlines the process and integrates seamlessly with .NET applications. By the end of this guide, you will be able do seamless HTML to PDF conversion within your .NET projects.

How to convert HTML to PDF C#

  1. Create a new Visual Studio project.
  2. Add IronPDF library from the NuGet package manager.
  3. Convert HTML strings to a PDF file.
  4. Add Headers and Footers.
  5. Include External Stylesheets and Scripts.

Introduction to IronPDF

IronPDF is a .NET library that allows developers to convert HTML to PDF with ease. It supports a wide range of features, including CSS, JavaScript, and embedded images, so your PDFs can look exactly like your HTML web pages. This ensures a seamless transition between formats, making IronPDF particularly useful for web applications that generate dynamic PDF documents on the fly.

The library allows developers to integrate PDF functionality directly into C# or VB.NET applications, without manually managing PDF structures. IronPDF is fully compatible with .NET Framework, .NET Core, and modern .NET versions, and it supports both Windows and Linux environments. Leveraging a Chrome-based rendering engine, IronPDF converts HTML pages (including complex CSS, JavaScript, and images) into well-structured, high-quality PDF documents - often in just a few lines of code. It is ideal for generating reports, invoices, eBooks, or any type of document that needs to be presented in PDF format.

Beyond its PDF conversion capabilities, IronPDF provides a wide range of options for manipulating PDF documents, including editing, form handling, encryption, headers/footers, and more, making it a versatile tool for modern PDF workflows.

Key Features of IronPDF

  1. HTML to PDF Conversion

    • HTML Rendering: IronPDF can convert HTML files, content, or entire web pages (including HTML documents with CSS, images, and JavaScript) directly into a PDF document. This is ideal for using dynamic web content in PDF creation.
    • Support for Modern HTML/CSS: IronPDF handles modern HTML5, CSS3, and JavaScript, ensuring that your web-based content is rendered accurately as a PDF. This preserves the layout, fonts, and interactive HTML elements. It can even directly convert HTML content such as HTML forms into easy-to share and fill out PDF forms.
    • Advanced Rendering: It uses Chrome’s rendering engine (via Chromium) for accurate, high-quality PDF generation, making it more reliable than many other HTML-to-PDF libraries.
    • Website URL to PDF: IronPDF can take a string URL of the website as input and convert it to PDF.
  2. Custom Headers and Footers

    • IronPDF allows developers to add custom headers and footers to PDF documents, which can include dynamic content such as page numbers, document title, or custom text.
    • Headers and footers can be added to individual pages, or as consistent elements across the entire document.
  3. Support for JavaScript in PDFs

    • IronPDF enables JavaScript execution within the HTML content before PDF generation. This allows for dynamic content rendering, such as form calculations or interactivity in the generated PDFs.
    • JavaScript is useful when creating PDFs from dynamic web pages or generating reports that require client-side logic.
  4. Edit Existing PDFs

    • IronPDF provides the ability to edit existing PDFs. You can modify your PDF page sizes, text, images, and add annotations to existing PDF files. This feature is useful for watermarking documents, adding signatures, or updating content within PDF files.
    • Text extraction and modification allow you to manipulate content within a PDF document programmatically.
  5. Merge and Split PDFs

    • IronPDF allows you to merge multiple PDF files into a single document or split a large PDF into smaller files. This is ideal for workflows where documents need to be combined or broken down into more manageable parts.
  6. Support for Interactive Forms

    • You can create, fill, and manipulate PDF forms using IronPDF. It provides full support for interactive forms (like text fields, checkboxes, and radio buttons) and allows you to pre-fill forms with data.
    • IronPDF also allows for extracting form data from existing PDFs, making it easy to read and process the form data programmatically.
  7. Page Manipulation

    • IronPDF offers various methods for manipulating individual pages within a PDF document, such as rotating pages, deleting pages, or reordering them. This helps in customizing the structure of the final document.
    • You can also add new pages to an existing PDF, or remove unwanted pages.
  8. Security and Encryption

    • IronPDF allows you to apply password protection and encryption to PDFs, ensuring that your documents are secure. You can set user permissions, such as preventing printing, copying, or editing the PDF.
    • Digital signatures can also be added to PDFs to verify authenticity, providing a layer of security for sensitive documents.
  9. Watermarking and Branding

    • Adding watermarks to PDF documents is easy with IronPDF. You can overlay text or images as watermarks onto pages, providing protection against unauthorized copying or distributing of your documents.
    • This feature is often used for branding, where the logo or text needs to appear consistently across all pages of a document.
  10. Text and Image Extraction

    • IronPDF allows for text and image extraction from PDF documents, enabling developers to extract data for processing or reuse.
    • This is helpful for scenarios where you need to analyze the contents of a PDF, extract information from forms, or retrieve images for further use.
  11. Unicode and Multi-language Support

    • IronPDF has robust Unicode support, meaning it can handle international characters and fonts, making it ideal for generating PDFs in multiple languages.
    • It supports languages such as Chinese, Arabic, Russian, and more, allowing for the creation of multilingual PDF documents.
  12. Optimized for Performance

    • IronPDF is optimized for performance, capable of handling large PDF documents and high volumes of requests. The library ensures that even when working with large datasets or images, PDF generation remains fast and efficient.
  13. API and Developer-Friendly Tools

    • IronPDF comes with a comprehensive and easy-to-use API. Developers can quickly get started by using simple method calls to perform complex tasks.
    • The API is well-documented, making it easy to integrate IronPDF into any C# or .NET application.
  14. Cross-Platform Support
    • IronPDF is cross-platform compatible, meaning it can be used on Windows, Mac, Linux, and other development environments, allowing you to generate and manipulate PDFs across different operating systems.

Use Cases of IronPDF

  1. Invoice Generation

    • Many businesses use IronPDF to generate professional invoices from dynamic data. HTML templates with embedded CSS styling are rendered into PDF invoices that are then sent to customers.
  2. Reports and Data Analysis

    • IronPDF is great for creating detailed reports from data sources. You can generate customized reports by combining data with HTML templates, adding graphs, and rendering them as PDFs for sharing or printing.
  3. Legal and Contract Documents

    • Legal firms use IronPDF to generate contracts, legal agreements, and other document types. The ability to add digital signatures and secure the documents with encryption makes it especially suitable for legal workflows.
  4. Educational Materials

    • Educational institutions use IronPDF to create and distribute PDFs such as certificates, class materials, and lecture notes that are styled consistently and professionally.
  5. Forms and Surveys
    • IronPDF's ability to handle forms is valuable for generating surveys, questionnaires, or any other type of interactive form. Data can be pre-filled, and form responses can be extracted and processed.

Step 1: Create a new Visual Studio project

To get started, open Visual Studio and create a new project as below:

HTML to PDF C# - A Complete Guide with IronPDF: Figure 1

Select create console application:

HTML to PDF C# - A Complete Guide with IronPDF: Figure 2

Provide project name and location:

HTML to PDF C# - A Complete Guide with IronPDF: Figure 3

Select .NET version:

HTML to PDF C# - A Complete Guide with IronPDF: Figure 4

click the "Create" button to complete the project creation:

Step 2: Add IronPDF library from NuGet package manager

Before you can start converting HTML to PDF, you'll need to install the IronPDF library. You can do this using NuGet Package Manager in Visual Studio or by running the following command in the Package Manager Console:

Also, IronPDF can be installed using Visual Studio Package Manager.

HTML to PDF C# - A Complete Guide with IronPDF: Figure 5

Step 3: Converting HTML string to PDF file

Below is code for an HTML to PDF converter application. Here, an HTML string is used as input and converted to a PDF. You can convert an HTML file to a PDF using the same steps, with an additional step to read the content from the HTML file.

using IronPdf;

class Program
{
    static void Main()
    {
        // Specify license key
        IronPdf.License.LicenseKey = "Your Key";

        // Create a new ChromePdfRenderer object
        var Renderer = new ChromePdfRenderer();

        // Define the HTML string to be converted
        string htmlContent = "<html><body><h1>IronPDF: An Awesome PDF Generation Library</h1></body></html>";

        // Convert HTML string to a PDF document
        var document = Renderer.RenderHtmlAsPdf(htmlContent);

        // Save the PDF document to a file
        document.SaveAs("html2Pdf.pdf");
    }
}
using IronPdf;

class Program
{
    static void Main()
    {
        // Specify license key
        IronPdf.License.LicenseKey = "Your Key";

        // Create a new ChromePdfRenderer object
        var Renderer = new ChromePdfRenderer();

        // Define the HTML string to be converted
        string htmlContent = "<html><body><h1>IronPDF: An Awesome PDF Generation Library</h1></body></html>";

        // Convert HTML string to a PDF document
        var document = Renderer.RenderHtmlAsPdf(htmlContent);

        // Save the PDF document to a file
        document.SaveAs("html2Pdf.pdf");
    }
}
Imports IronPdf

Friend Class Program
	Shared Sub Main()
		' Specify license key
		IronPdf.License.LicenseKey = "Your Key"

		' Create a new ChromePdfRenderer object
		Dim Renderer = New ChromePdfRenderer()

		' Define the HTML string to be converted
		Dim htmlContent As String = "<html><body><h1>IronPDF: An Awesome PDF Generation Library</h1></body></html>"

		' Convert HTML string to a PDF document
		Dim document = Renderer.RenderHtmlAsPdf(htmlContent)

		' Save the PDF document to a file
		document.SaveAs("html2Pdf.pdf")
	End Sub
End Class
$vbLabelText   $csharpLabel

Code snippet Explanation

  • License Key Setup:
    • The program begins by setting the IronPDF license key to enable full functionality of the library.
  • Creating the Renderer:
    • An instance of ChromePdfRenderer is created. This is the component responsible for rendering the HTML into a PDF document. It essentially acts as a bridge between the HTML content and the generated PDF.
  • HTML Content:
    • A string variable htmlContent is defined, which contains the HTML code you want to convert into a PDF. In this case, it’s a simple HTML structure with a heading.
  • HTML to PDF Conversion:
    • The Renderer.RenderHtmlAsPdf() method is called with the HTML string to generate a PDF document. This method processes the HTML content and converts it into a PDF format.
  • Saving the PDF:
    • The generated PDF document is saved to a file with the name "html2Pdf.pdf" using the SaveAs() method. This stores the newly created PDF on the disk.

Output PDF

HTML to PDF C# - A Complete Guide with IronPDF: Figure 6

Step 4: Adding Headers and Footers

using IronPdf;

class Program
{
    static void Main()
    {
        IronPdf.License.LicenseKey = "your key";

        // Create a new ChromePdfRenderer object
        var Renderer = new ChromePdfRenderer();

        // Define HTML content
        string htmlContent = "<html><body><h1>IronPDF: An Awesome PDF Generation Library</h1><h1>Report</h1><p>This is a sample report.</p></body></html>";

        // Define header and footer HTML
        string headerHtml = "<div style='text-align: right;'>Page {page} of {total-pages}</div>";
        string footerHtml = "<div style='text-align: center;'>Confidential</div>";

        // Convert the HTML content to a PDF document
        var pdfDocument = Renderer.RenderHtmlAsPdf(htmlContent);

        // Add headers and footers to the PDF document
        pdfDocument.AddHtmlHeadersAndFooters(new ChromePdfRenderOptions
        {
            HtmlHeader= new HtmlHeaderFooter() { HtmlFragment=headerHtml },
            HtmlFooter = new HtmlHeaderFooter() { HtmlFragment=footerHtml }
        });

        // Save the PDF document to a file
        pdfDocument.SaveAs("report.pdf");
    }
}
using IronPdf;

class Program
{
    static void Main()
    {
        IronPdf.License.LicenseKey = "your key";

        // Create a new ChromePdfRenderer object
        var Renderer = new ChromePdfRenderer();

        // Define HTML content
        string htmlContent = "<html><body><h1>IronPDF: An Awesome PDF Generation Library</h1><h1>Report</h1><p>This is a sample report.</p></body></html>";

        // Define header and footer HTML
        string headerHtml = "<div style='text-align: right;'>Page {page} of {total-pages}</div>";
        string footerHtml = "<div style='text-align: center;'>Confidential</div>";

        // Convert the HTML content to a PDF document
        var pdfDocument = Renderer.RenderHtmlAsPdf(htmlContent);

        // Add headers and footers to the PDF document
        pdfDocument.AddHtmlHeadersAndFooters(new ChromePdfRenderOptions
        {
            HtmlHeader= new HtmlHeaderFooter() { HtmlFragment=headerHtml },
            HtmlFooter = new HtmlHeaderFooter() { HtmlFragment=footerHtml }
        });

        // Save the PDF document to a file
        pdfDocument.SaveAs("report.pdf");
    }
}
Imports IronPdf

Friend Class Program
	Shared Sub Main()
		IronPdf.License.LicenseKey = "your key"

		' Create a new ChromePdfRenderer object
		Dim Renderer = New ChromePdfRenderer()

		' Define HTML content
		Dim htmlContent As String = "<html><body><h1>IronPDF: An Awesome PDF Generation Library</h1><h1>Report</h1><p>This is a sample report.</p></body></html>"

		' Define header and footer HTML
		Dim headerHtml As String = "<div style='text-align: right;'>Page {page} of {total-pages}</div>"
		Dim footerHtml As String = "<div style='text-align: center;'>Confidential</div>"

		' Convert the HTML content to a PDF document
		Dim pdfDocument = Renderer.RenderHtmlAsPdf(htmlContent)

		' Add headers and footers to the PDF document
		pdfDocument.AddHtmlHeadersAndFooters(New ChromePdfRenderOptions With {
			.HtmlHeader= New HtmlHeaderFooter() With {.HtmlFragment=headerHtml},
			.HtmlFooter = New HtmlHeaderFooter() With {.HtmlFragment=footerHtml}
		})

		' Save the PDF document to a file
		pdfDocument.SaveAs("report.pdf")
	End Sub
End Class
$vbLabelText   $csharpLabel

Code snippet Explanation

  1. License Key Setup:
    • The IronPdf.License.LicenseKey is set with your unique IronPDF license key to enable the library's full functionality.
  2. Create the PDF Renderer:
    • An instance of ChromePdfRenderer is created, which will be used to render HTML content into a PDF format. This is part of IronPDF's rendering engine.
  3. Define HTML Content:
    • A simple HTML string is created that includes a title, a report header, and a sample report paragraph.
  4. Define Header and Footer HTML:
    • In the above code, we have specified custom header and footer HTML strings:
      • The header includes page numbers formatted as "Page {page} of {total-pages}" aligned to the right.
      • The footer includes the text "Confidential" aligned to the center of each page.
  5. HTML to PDF Conversion:
    • The RenderHtmlAsPdf() method is called to convert the HTML content into a PDF document.
  6. Adding Headers and Footers:
    • The AddHtmlHeadersAndFooters() method is called on the pdfDocument object. This method adds the previously defined header and footer to the generated PDF. The ChromePdfRenderOptions is used to pass the header and footer settings.
  7. Saving the PDF:
    • Finally, the SaveAs() method is used to save the generated PDF to a file named "report.pdf" on the disk.

Output PDF

HTML to PDF C# - A Complete Guide with IronPDF: Figure 7

Step 5: Including External Stylesheets and Scripts

using IronPdf;

class Program
{
    static void Main()
    {
        IronPdf.License.LicenseKey = "your key";

        // Create a new ChromePdfRenderer object
        var Renderer = new ChromePdfRenderer();

        // Define the HTML content with links to external CSS and JS files
        string htmlContent = @"
            <html>
            <head>
                <link rel='stylesheet' type='text/css' href='styles.css'>
                <script src='script.js'></script>
            </head>
            <body>
                <h1>IronPDF: An Awesome PDF Generation Library</h1>
                <h1>Styled Content</h1>
                <p id='dynamic-text'>This content is styled using an external CSS file and JavaScript.</p>
            </body>
            </html>";

        // Convert HTML content to a PDF document
        var pdfDocument = Renderer.RenderHtmlAsPdf(htmlContent);

        // Save the PDF document to a file
        pdfDocument.SaveAs("awesomeIronPDF_styled_content.pdf");
    }
}
using IronPdf;

class Program
{
    static void Main()
    {
        IronPdf.License.LicenseKey = "your key";

        // Create a new ChromePdfRenderer object
        var Renderer = new ChromePdfRenderer();

        // Define the HTML content with links to external CSS and JS files
        string htmlContent = @"
            <html>
            <head>
                <link rel='stylesheet' type='text/css' href='styles.css'>
                <script src='script.js'></script>
            </head>
            <body>
                <h1>IronPDF: An Awesome PDF Generation Library</h1>
                <h1>Styled Content</h1>
                <p id='dynamic-text'>This content is styled using an external CSS file and JavaScript.</p>
            </body>
            </html>";

        // Convert HTML content to a PDF document
        var pdfDocument = Renderer.RenderHtmlAsPdf(htmlContent);

        // Save the PDF document to a file
        pdfDocument.SaveAs("awesomeIronPDF_styled_content.pdf");
    }
}
Imports IronPdf

Friend Class Program
	Shared Sub Main()
		IronPdf.License.LicenseKey = "your key"

		' Create a new ChromePdfRenderer object
		Dim Renderer = New ChromePdfRenderer()

		' Define the HTML content with links to external CSS and JS files
		Dim htmlContent As String = "
            <html>
            <head>
                <link rel='stylesheet' type='text/css' href='styles.css'>
                <script src='script.js'></script>
            </head>
            <body>
                <h1>IronPDF: An Awesome PDF Generation Library</h1>
                <h1>Styled Content</h1>
                <p id='dynamic-text'>This content is styled using an external CSS file and JavaScript.</p>
            </body>
            </html>"

		' Convert HTML content to a PDF document
		Dim pdfDocument = Renderer.RenderHtmlAsPdf(htmlContent)

		' Save the PDF document to a file
		pdfDocument.SaveAs("awesomeIronPDF_styled_content.pdf")
	End Sub
End Class
$vbLabelText   $csharpLabel

style.css

/* styles.css */
body {
    font-family: Arial, sans-serif;
    margin: 20px;
}

h1 {
    color: #007BFF;
}

p {
    font-size: 14px;
    line-height: 1.6;
}

script.js

// script.js
document.addEventListener('DOMContentLoaded', function() {
    var dynamicText = document.getElementById('dynamic-text');
    dynamicText.textContent = "This content has been modified by JavaScript.";
});
// script.js
document.addEventListener('DOMContentLoaded', function() {
    var dynamicText = document.getElementById('dynamic-text');
    dynamicText.textContent = "This content has been modified by JavaScript.";
});
JAVASCRIPT

Code Explanation

This code demonstrates how to use IronPDF in C# to generate a PDF from HTML content that includes links to external CSS and JavaScript files. It shows how to create a PDF with styled content and dynamic behavior (via JavaScript).

  1. License Key Setup:

    • The IronPdf.License.LicenseKey is set to your unique IronPDF license key, allowing access to full features of the IronPDF library.
  2. Define HTML Content with External Resources:

    • The HTML string is defined with:
      • A link to an external CSS file (styles.css) to style the content.
      • A link to an external JavaScript file (script.js) that can add dynamic functionality to the content.
    • The HTML content includes a heading (<h1>), a subheading, and a paragraph (<p>) with an ID dynamic-text that is styled by the external CSS and potentially modified by the JavaScript.
  3. Rendering HTML to PDF:

    • The Renderer.RenderHtmlAsPdf() method is called to convert the HTML content, including the linked CSS and JavaScript, into a PDF document. Note that IronPDF can handle external resources like CSS and JavaScript if the resources are accessible, such as when the files are hosted locally or remotely.
  4. Saving the PDF:
    • The generated PDF document is saved to a file named "awesomeIronPDF_styled_content.pdf" using the SaveAs() method.

Notes

  • External CSS and JS Files: To ensure the links work, the styles.css and script.js files should be accessible in the environment where the code runs. If the files are local, make sure they are in the correct directory or provide the full path to the files.
  • JavaScript in PDFs: IronPDF can render content that uses JavaScript for page behavior. However, it is important to note that JavaScript may not execute as expected in a static PDF file, as PDFs are not inherently dynamic like web pages. IronPDF primarily uses JavaScript to render content before the PDF is generated, so dynamic content manipulation via JavaScript may not work after the PDF is created.

Output PDF

HTML to PDF C# - A Complete Guide with IronPDF: Figure 8

License Information (Trial Available)

To get started with IronPDF, you can access a trial license. Include it at the beginning of your code as shown below:

IronPdf.License.LicenseKey = "your key";
IronPdf.License.LicenseKey = "your key";
IronPdf.License.LicenseKey = "your key"
$vbLabelText   $csharpLabel

Conclusion

IronPDF is a powerful and versatile library that makes converting HTML to PDF a breeze. Whether you need to generate simple documents or complex reports with dynamic content, IronPDF has you covered. With its easy-to-use API and support for advanced features like headers, footers, and external resources, IronPDF is an invaluable tool for developers looking to create high-quality PDF documents from HTML content. Give it a try in your next project and experience the convenience of effortless HTML to PDF conversion.