USING IRON SUITE

HTML to PDF C# - A Complete Guide with IronPDF

April 9, 2025
Share:

Introduction

In today's digital age, the need to convert HTML to PDF files is more important than ever. Whether you're generating reports, invoices, or simply archiving web content, converting HTML to PDF is a practical solution. IronPDF is a powerful library that simplifies this process, making it easy for developers to create high-quality PDF documents from HTML content

How to convert HTML to PDF C#

  1. Create a new Visual Studio project.
  2. Add IronPDF library from the NuGet package manager.
  3. Converting HTML strings to PDF file.
  4. Adding Headers and Footers.
  5. Including 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 even embedded images. With IronPDF, you can create PDFs that look exactly like your HTML web pages, ensuring a seamless transition between formats. This library is particularly useful for web applications that need to generate dynamic PDF documents on the fly.

IronPDF allows developers to seamlessly integrate PDF functionality into .NET applications without needing to manually manage PDF file structures. IronPDF leverages the Chrome-based rendering engine to convert an HTML pages (including complex CSS, JavaScript, and images) into well-structured PDF documents. It can be used for generating reports, invoices, eBooks, or any type of document that needs to be presented in PDF format.

IronPDF is versatile, offering functionality that not only renders PDFs but also provides a wide range of PDF manipulation options like editing, form handling, encryption, and more.

Key Features of IronPDF

  1. HTML to PDF Conversion

    • HTML Rendering: IronPDF can convert HTML documents or web pages (including HTML with CSS, images, and JavaScript) directly into a PDF document. This is ideal for generating PDFs from dynamic web content.

    • Support for Modern HTML/CSS: IronPDF handles modern HTML5, CSS3, and JavaScript, ensuring that your web-based content is rendered accurately as a PDF, preserving the layout, fonts, and interactive elements.

    • 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 string url of the website as input and convert 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 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.
    1. 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.
    1. 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.
    1. 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.
    1. 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.
    1. Cross-Platform Support
    • IronPDF is cross-platform compatible, meaning it can be used on both Windows and Linux environments, allowing you to generate and manipulate PDFs across different operating systems.

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 Add from PixabayUpload

or drag and drop an image here

Add image alt text

Select create console application.

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

or drag and drop an image here

Add image alt text

Provide project name and location.

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

or drag and drop an image here

Add image alt text

Select .NET version

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

or drag and drop an image here

Add image alt text

click "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:

Install-Package IronPdf
Install-Package IronPdf
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'Install-Package IronPdf
$vbLabelText   $csharpLabel

Also, IronPDF can be installed using Visual Studio Package Manager

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

or drag and drop an image here

Add image alt text

Step 3: Converting HTML string to PDF file

Below is code for HTML to PDF converter application. Here, HTML code or HTML elements represented in string format is used as input and converted to PDF. Convert HTML file to PDF using the same steps, with an additional step to read the content from the HTML file.

class Program
{
    static void Main()
    {
        // Specify license key
        IronPdf.License.LicenseKey = "Your Key";
        // Create a new HtmlToPdf object
        var Renderer = new ChromePdfRenderer();
        // Define the HTML string to be converted, can use html document
        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");
    }
}
class Program
{
    static void Main()
    {
        // Specify license key
        IronPdf.License.LicenseKey = "Your Key";
        // Create a new HtmlToPdf object
        var Renderer = new ChromePdfRenderer();
        // Define the HTML string to be converted, can use html document
        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");
    }
}
Friend Class Program
	Shared Sub Main()
		' Specify license key
		IronPdf.License.LicenseKey = "Your Key"
		' Create a new HtmlToPdf object
		Dim Renderer = New ChromePdfRenderer()
		' Define the HTML string to be converted, can use html document
		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 Add from PixabayUpload

or drag and drop an image here

Add image alt text

Step 4: Adding Headers and Footers

class Program
{
    static void Main()
    {
        IronPdf.License.LicenseKey = "your code";
        // Create a new HtmlToPdf object
        var Renderer = new ChromePdfRenderer();
        string htmlContent = "<html><body><h1>IronPDF: An Awesome PDF Generation Library</h1><h1>Report</h1><p>This is a sample report.</p></body></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 with headers and footers
        var pdfDocument = Renderer.RenderHtmlAsPdf(htmlContent);
        pdfDocument.AddHtmlHeadersAndFooters(new ChromePdfRenderOptions
        {
            HtmlHeader= new HtmlHeaderFooter() { HtmlFragment=headerHtml },
            HtmlFooter = new HtmlHeaderFooter() { HtmlFragment=footerHtml }
        });
        pdfDocument.SaveAs("report.pdf");
    }
}
class Program
{
    static void Main()
    {
        IronPdf.License.LicenseKey = "your code";
        // Create a new HtmlToPdf object
        var Renderer = new ChromePdfRenderer();
        string htmlContent = "<html><body><h1>IronPDF: An Awesome PDF Generation Library</h1><h1>Report</h1><p>This is a sample report.</p></body></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 with headers and footers
        var pdfDocument = Renderer.RenderHtmlAsPdf(htmlContent);
        pdfDocument.AddHtmlHeadersAndFooters(new ChromePdfRenderOptions
        {
            HtmlHeader= new HtmlHeaderFooter() { HtmlFragment=headerHtml },
            HtmlFooter = new HtmlHeaderFooter() { HtmlFragment=footerHtml }
        });
        pdfDocument.SaveAs("report.pdf");
    }
}
Friend Class Program
	Shared Sub Main()
		IronPdf.License.LicenseKey = "your code"
		' Create a new HtmlToPdf object
		Dim Renderer = New ChromePdfRenderer()
		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>"
		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 with headers and footers
		Dim pdfDocument = Renderer.RenderHtmlAsPdf(htmlContent)
		pdfDocument.AddHtmlHeadersAndFooters(New ChromePdfRenderOptions With {
			.HtmlHeader= New HtmlHeaderFooter() With {.HtmlFragment=headerHtml},
			.HtmlFooter = New HtmlHeaderFooter() With {.HtmlFragment=footerHtml}
		})
		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 (

      IronPDF: An Awesome PDF Generation Library), a report header (

      Report), and a sample report paragraph.

  4. Define Header and Footer HTML:

    • Custom header and footer HTML strings are specified:

      • 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 Add from PixabayUpload

or drag and drop an image here

Add image alt text

Step 5: Including External Stylesheets and Scripts

class Program
{
    static void Main()
    {
        IronPdf.License.LicenseKey = "your key";        
        // 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>";
        var pdfDocument = Renderer.RenderHtmlAsPdf(htmlContent);
        pdfDocument.SaveAs("awesomeIronPDF_styled_content.pdf");
    }
}
class Program
{
    static void Main()
    {
        IronPdf.License.LicenseKey = "your key";        
        // 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>";
        var pdfDocument = Renderer.RenderHtmlAsPdf(htmlContent);
        pdfDocument.SaveAs("awesomeIronPDF_styled_content.pdf");
    }
}
Friend Class Program
	Shared Sub Main()
		IronPdf.License.LicenseKey = "your key"
		' 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>"
		Dim pdfDocument = Renderer.RenderHtmlAsPdf(htmlContent)
		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;
}
/* styles.css */
body {
    font-family: Arial, sans-serif;
    margin: 20px;
}
h1 {
    color: #007BFF;
}
p {
    font-size: 14px;
    line-height: 1.6;
}
' styles.css 
body
If True Then
	font-family: Arial, sans-serif
	margin:
	20px
End If
h1
If True Then
	color:
	#007BFF;
End If
p
If True Then
	font-size: 14px
	line-height: 1.6
End If
$vbLabelText   $csharpLabel

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.";
});
' script.js
document.addEventListener( 'DOMContentLoaded', @function() { var dynamicText = document.getElementById('dynamic-text'); dynamicText.textContent = "This content has been modified by JavaScript."; });
$vbLabelText   $csharpLabel

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 (

      IronPDF: An Awesome PDF Generation Library), a subheading (

      Styled Content), and a paragraph (

      ) 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 Add from PixabayUpload

or drag and drop an image here

Add image alt text

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.

License Information (Trail available)

IronPDF. Place it before using IronPDF library like 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.

< PREVIOUS
C# Create PDF - A Complete Guide to Using IronPDF
NEXT >
HTML to PDF in C# for .NET Developers (The Ultimate Guide)