How to Convert HTML to PDF in .NET Core

Introduction

Converting to PDFs from various formats can be challenging due to the stringent standards of the PDF format. The conversion may not yield a one-to-one match in many cases, especially when dealing with HTML and CSS styling. However, in today’s digital landscape, the ability to convert URLs and forms—including those with HTML and CSS—is essential. This is where IronPDF excels, offering intuitive features that empower developers to convert a wide range of formats to PDF with high fidelity, often in just a few lines of code.

With IronPDF, you can effortlessly convert HTML, DOCX, RTF, Markdown, and even images to PDF, ensuring the integrity of your documents is maintained. It also supports the conversion of dynamic web pages from popular frameworks like Razor, CSHTML, ASPX, and XAML, eliminating compatibility concerns and making IronPDF your comprehensive solution for all PDF conversion needs.

In addition to straightforward conversion, IronPDF offers powerful customization options. You can tailor your PDF output with custom margins, headers, and footers to include page numbers and adjust greyscale settings to reduce file size. Enhance your documents by incorporating additional features like a table of contents, automatic page breaks, and content that scales perfectly to your desired document size.

In this tutorial, we will explore these capabilities and more, providing code examples and highlighting the key features of IronPDF. Get ready to transform your PDF conversion process, allowing you to convert, customize, and optimize your PDF documents effortlessly with IronPDF.

Table of Contents

Start using IronPDF in your project today with a free trial.

First Step:
green arrow pointer
NuGet Install with NuGet

PM >  Install-Package IronPdf

Check out IronPDF on NuGet for quick installation. With over 10 million downloads, it’s transforming PDF development with C#. You can also download the DLL or Windows installer.

Versatile PDF Conversion

PDF from HTML String

To convert a PDF from a HTML string, we can use the RenderHtmlAsPdf method to transform the HTML string into a pixel-perfect PDF quickly.

:path=/static-assets/pdf/content-code-examples/how-to/html-string-to-pdf.cs
using IronPdf;

// Instantiate Renderer
var renderer = new ChromePdfRenderer();

// Create a PDF from a HTML string using C#
var pdf = renderer.RenderHtmlAsPdf("<h1>Hello World</h1>");

// Export to a file or Stream
pdf.SaveAs("output.pdf");
Imports IronPdf

' Instantiate Renderer
Private renderer = New ChromePdfRenderer()

' Create a PDF from a HTML string using C#
Private pdf = renderer.RenderHtmlAsPdf("<h1>Hello World</h1>")

' Export to a file or Stream
pdf.SaveAs("output.pdf")
$vbLabelText   $csharpLabel

For a more detailed explanation of this code snippet and to explore its additional functionality, please refer to our comprehensive how-to guide.

PDF from HTML

Easily convert a HTML file to a PDF with our RenderHtmlAsPdf method and quickly save your pixel-perfect PDF.

:path=/static-assets/pdf/content-code-examples/how-to/html-file-to-pdf.cs
using IronPdf;
using IronPdf.Engines.Chrome;
using IronPdf.Rendering;


var renderer = new ChromePdfRenderer
{
    RenderingOptions = new ChromePdfRenderOptions
    {
        CssMediaType = PdfCssMediaType.Print,
        MarginBottom = 0,
        MarginLeft = 0,
        MarginRight = 0,
        MarginTop = 0,
        Timeout = 120,
    },
};
renderer.RenderingOptions.WaitFor.RenderDelay(50);

// Create a PDF from an existing HTML file using C#
var pdf = renderer.RenderHtmlFileAsPdf("example.html");

// Export to a file or Stream
pdf.SaveAs("output.pdf");
Imports IronPdf
Imports IronPdf.Engines.Chrome
Imports IronPdf.Rendering


Private renderer = New ChromePdfRenderer With {
	.RenderingOptions = New ChromePdfRenderOptions With {
		.CssMediaType = PdfCssMediaType.Print,
		.MarginBottom = 0,
		.MarginLeft = 0,
		.MarginRight = 0,
		.MarginTop = 0,
		.Timeout = 120
	}
}
renderer.RenderingOptions.WaitFor.RenderDelay(50)

' Create a PDF from an existing HTML file using C#
Dim pdf = renderer.RenderHtmlFileAsPdf("example.html")

' Export to a file or Stream
pdf.SaveAs("output.pdf")
$vbLabelText   $csharpLabel

For a more detailed explanation of this code snippet and to explore its additional functionality, please refer to our comprehensive how-to guide.

PDF from URL

Convert the URL to PDF quickly with RenderUrlAsPdf in just a few lines. Input the URL as a parameter and save it with ease.

:path=/static-assets/pdf/content-code-examples/how-to/url-to-pdf.cs
using IronPdf;

// Instantiate Renderer
var renderer = new ChromePdfRenderer();

// Create a PDF from a URL or local file path
var pdf = renderer.RenderUrlAsPdf("https://en.wikipedia.org/wiki/Main_Page");

// Export to a file or Stream
pdf.SaveAs("url.pdf");
Imports IronPdf

' Instantiate Renderer
Private renderer = New ChromePdfRenderer()

' Create a PDF from a URL or local file path
Private pdf = renderer.RenderUrlAsPdf("https://en.wikipedia.org/wiki/Main_Page")

' Export to a file or Stream
pdf.SaveAs("url.pdf")
$vbLabelText   $csharpLabel

For a more detailed explanation of this code snippet and to explore its additional functionality, please refer to our comprehensive how-to guide.

Image To PDF

Do you have an image you want to display as a PDF? Quickly convert it with our ImageToPdfConverter class and call the ImageToPdf method.

:path=/static-assets/pdf/content-code-examples/how-to/image-to-pdf-convert-one-image.cs
using IronPdf;

string imagePath = "meetOurTeam.jpg";

// Convert an image to a PDF
PdfDocument pdf = ImageToPdfConverter.ImageToPdf(imagePath);

// Export the PDF
pdf.SaveAs("imageToPdf.pdf");
Imports IronPdf

Private imagePath As String = "meetOurTeam.jpg"

' Convert an image to a PDF
Private pdf As PdfDocument = ImageToPdfConverter.ImageToPdf(imagePath)

' Export the PDF
pdf.SaveAs("imageToPdf.pdf")
$vbLabelText   $csharpLabel

For a more detailed explanation of this code snippet and to explore its additional functionality, please refer to our comprehensive how-to guide.

Image From PDF

For the opposite to the example above, we can first convert the input into a PDF and then use the RasterizeToImageFiles method to convert the PDF into images.

:path=/static-assets/pdf/content-code-examples/how-to/rasterize-pdf-to-images-rasterize.cs
using IronPdf;

// Instantiate Renderer
ChromePdfRenderer renderer = new ChromePdfRenderer();

// Render PDF from web URL
PdfDocument pdf = renderer.RenderUrlAsPdf("https://en.wikipedia.org/wiki/Main_Page");

// Export images from PDF
pdf.RasterizeToImageFiles("wikipage_*.png");
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

For a more detailed explanation of this code snippet and to explore its additional functionality, please refer to our comprehensive how-to guide.

Convert DOCX to PDF

Have you ever needed to convert a DOCX file, such as a resume, to PDF easily? IronPDF has you covered. Simply call RenderDocxAsPDF to convert.

:path=/static-assets/pdf/content-code-examples/how-to/docx-to-pdf-from-file.cs
using IronPdf;

// Instantiate Renderer
DocxToPdfRenderer renderer = new DocxToPdfRenderer();

// Render from DOCX file
PdfDocument pdf = renderer.RenderDocxAsPdf("Modern-chronological-resume.docx");

// Save the PDF
pdf.SaveAs("pdfFromDocx.pdf");
Imports IronPdf

' Instantiate Renderer
Private renderer As New DocxToPdfRenderer()

' Render from DOCX file
Private pdf As PdfDocument = renderer.RenderDocxAsPdf("Modern-chronological-resume.docx")

' Save the PDF
pdf.SaveAs("pdfFromDocx.pdf")
$vbLabelText   $csharpLabel

For a more detailed explanation of this code snippet and to explore its additional functionality, please refer to our comprehensive how-to guide.

Convert RTF to PDF

To convert an RTF file to a PDF, we call RenderRtfFileAsPdf with the RTF file as input.

:path=/static-assets/pdf/content-code-examples/how-to/rtf-to-pdf-from-file.cs
using IronPdf;

// Instantiate Renderer
ChromePdfRenderer renderer = new ChromePdfRenderer();

// Render from RTF file
PdfDocument pdf = renderer.RenderRtfFileAsPdf("sample.rtf");

// Save the PDF
pdf.SaveAs("pdfFromRtfFile.pdf");
Imports IronPdf

' Instantiate Renderer
Private renderer As New ChromePdfRenderer()

' Render from RTF file
Private pdf As PdfDocument = renderer.RenderRtfFileAsPdf("sample.rtf")

' Save the PDF
pdf.SaveAs("pdfFromRtfFile.pdf")
$vbLabelText   $csharpLabel

For a more detailed explanation of this code snippet and to explore its additional functionality, please refer to our comprehensive how-to guide.

Convert MD to PDF

To convert an MD to a PDF, we can call the RenderMarkdownFileAsPdf method with the MD file as input.

:path=/static-assets/pdf/content-code-examples/how-to/md-to-pdf-from-file.cs
using IronPdf;

// Instantiate Renderer
ChromePdfRenderer renderer = new ChromePdfRenderer();

// Render from markdown file
PdfDocument pdf = renderer.RenderMarkdownFileAsPdf("sample.md");

// Save the PDF
pdf.SaveAs("pdfFromMarkdownFile.pdf");
Imports IronPdf

' Instantiate Renderer
Private renderer As New ChromePdfRenderer()

' Render from markdown file
Private pdf As PdfDocument = renderer.RenderMarkdownFileAsPdf("sample.md")

' Save the PDF
pdf.SaveAs("pdfFromMarkdownFile.pdf")
$vbLabelText   $csharpLabel

For a more detailed explanation of this code snippet and to explore its additional functionality, please refer to our comprehensive how-to guide.

Convert XML to PDF

Althought converting XML to PDF can be pretty challenging, IronPDF still rises to the challenge and helps convert XML to PDF in a few steps. We start with an XLST template and then convert the XML to PDF via HTML through XLST transformations. Here's a shortened version of the code snippet to help you get started.

// XSLT template that defines the transformation from XML to HTML
string xslt = @"<?xml version='1.0' encoding='UTF-8'?>
<xsl:stylesheet version='1.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform'>
<xsl:template match='/'>
<html>
<style>
td{
  text-align: center;
  padding: 20px;
  border: 1px solid #CDE7F0;
}
th{
  color: white;
  padding: 20px;
}
</style>
<body style='font-family: Arial, Helvetica Neue, Helvetica, sans-serif;'>
  <table style='border-collapse: collapse;'>
    <thead>
      <tr>
        <th colspan='3'>
          <img style='margin: auto;' src='https://ironsoftware.com/img/svgs/ironsoftware-logo-black.svg'/>
        </th>
      </tr>
    </thead>
    <tbody>
      <tr bgcolor='#9acd32'>
        <th bgcolor='#32ab90'>Title</th>
        <th bgcolor='#f49400'>Feature</th>
        <th bgcolor='#2a95d5'>Compatible</th>
      </tr>
      <xsl:for-each select='catalog/cd'>
      <tr>
        <td style='font-weight: bold;'><xsl:value-of select='title'/></td>
        <td style='background-color: #eff8fb; color: #2a95d5; font-weight: bold;'><xsl:value-of select='feature'/></td>
        <td><xsl:value-of select='compatible'/></td>
      </tr>
      </xsl:for-each>
    </tbody>
  </table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
";

// XML data to transform
string xml = @"<?xml version='1.0' encoding='UTF-8'?>
<catalog>
  <cd>
    <title>IronPDF</title>
    <feature>Generate, format and manipulate PDFs</feature>
    <compatible>Microsoft Windows, Linux (Debian, CentOS, Ubuntu), MacOS, Docker (Windows, Linux, Azure), Azure (VPS, Webapps, Websites, Functions), AWS</compatible>
  </cd>
  <cd>
    <title>IronOCR</title>
    <feature>OCR engine, input, result</feature>
    <compatible>Microsoft Windows, Linux, MacOS, Docker, Azure, AWS</compatible>
  </cd>
  <cd>
    <title>IronBarcode</title>
    <feature>Format, read and write Barcode</feature>
    <compatible>Microsoft Windows, Linux, MacOS, Docker, Azure, AWS</compatible>
  </cd>
</catalog>
";

// Create an instance of XslCompiledTransform
XslCompiledTransform transform = new XslCompiledTransform();

// Load the XSLT from a string
using (XmlReader reader = XmlReader.Create(new StringReader(xslt)))
{
    transform.Load(reader);
}

// Transform the XML to HTML
StringWriter results = new StringWriter();
using (XmlReader reader = XmlReader.Create(new StringReader(xml)))
{
    transform.Transform(reader, null, results);
}

// Create a renderer for converting HTML to PDF
IronPdf.ChromePdfRenderer renderer = new IronPdf.ChromePdfRenderer();
// Options, headers, and footers may be set here if needed
// Render our XML as a PDF via XSLT transformation
renderer.RenderHtmlAsPdf(results.ToString()).SaveAs("Final.pdf");
// XSLT template that defines the transformation from XML to HTML
string xslt = @"<?xml version='1.0' encoding='UTF-8'?>
<xsl:stylesheet version='1.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform'>
<xsl:template match='/'>
<html>
<style>
td{
  text-align: center;
  padding: 20px;
  border: 1px solid #CDE7F0;
}
th{
  color: white;
  padding: 20px;
}
</style>
<body style='font-family: Arial, Helvetica Neue, Helvetica, sans-serif;'>
  <table style='border-collapse: collapse;'>
    <thead>
      <tr>
        <th colspan='3'>
          <img style='margin: auto;' src='https://ironsoftware.com/img/svgs/ironsoftware-logo-black.svg'/>
        </th>
      </tr>
    </thead>
    <tbody>
      <tr bgcolor='#9acd32'>
        <th bgcolor='#32ab90'>Title</th>
        <th bgcolor='#f49400'>Feature</th>
        <th bgcolor='#2a95d5'>Compatible</th>
      </tr>
      <xsl:for-each select='catalog/cd'>
      <tr>
        <td style='font-weight: bold;'><xsl:value-of select='title'/></td>
        <td style='background-color: #eff8fb; color: #2a95d5; font-weight: bold;'><xsl:value-of select='feature'/></td>
        <td><xsl:value-of select='compatible'/></td>
      </tr>
      </xsl:for-each>
    </tbody>
  </table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
";

// XML data to transform
string xml = @"<?xml version='1.0' encoding='UTF-8'?>
<catalog>
  <cd>
    <title>IronPDF</title>
    <feature>Generate, format and manipulate PDFs</feature>
    <compatible>Microsoft Windows, Linux (Debian, CentOS, Ubuntu), MacOS, Docker (Windows, Linux, Azure), Azure (VPS, Webapps, Websites, Functions), AWS</compatible>
  </cd>
  <cd>
    <title>IronOCR</title>
    <feature>OCR engine, input, result</feature>
    <compatible>Microsoft Windows, Linux, MacOS, Docker, Azure, AWS</compatible>
  </cd>
  <cd>
    <title>IronBarcode</title>
    <feature>Format, read and write Barcode</feature>
    <compatible>Microsoft Windows, Linux, MacOS, Docker, Azure, AWS</compatible>
  </cd>
</catalog>
";

// Create an instance of XslCompiledTransform
XslCompiledTransform transform = new XslCompiledTransform();

// Load the XSLT from a string
using (XmlReader reader = XmlReader.Create(new StringReader(xslt)))
{
    transform.Load(reader);
}

// Transform the XML to HTML
StringWriter results = new StringWriter();
using (XmlReader reader = XmlReader.Create(new StringReader(xml)))
{
    transform.Transform(reader, null, results);
}

// Create a renderer for converting HTML to PDF
IronPdf.ChromePdfRenderer renderer = new IronPdf.ChromePdfRenderer();
// Options, headers, and footers may be set here if needed
// Render our XML as a PDF via XSLT transformation
renderer.RenderHtmlAsPdf(results.ToString()).SaveAs("Final.pdf");
' XSLT template that defines the transformation from XML to HTML
Dim xslt As String = "<?xml version='1.0' encoding='UTF-8'?>
<xsl:stylesheet version='1.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform'>
<xsl:template match='/'>
<html>
<style>
td{
  text-align: center;
  padding: 20px;
  border: 1px solid #CDE7F0;
}
th{
  color: white;
  padding: 20px;
}
</style>
<body style='font-family: Arial, Helvetica Neue, Helvetica, sans-serif;'>
  <table style='border-collapse: collapse;'>
    <thead>
      <tr>
        <th colspan='3'>
          <img style='margin: auto;' src='https://ironsoftware.com/img/svgs/ironsoftware-logo-black.svg'/>
        </th>
      </tr>
    </thead>
    <tbody>
      <tr bgcolor='#9acd32'>
        <th bgcolor='#32ab90'>Title</th>
        <th bgcolor='#f49400'>Feature</th>
        <th bgcolor='#2a95d5'>Compatible</th>
      </tr>
      <xsl:for-each select='catalog/cd'>
      <tr>
        <td style='font-weight: bold;'><xsl:value-of select='title'/></td>
        <td style='background-color: #eff8fb; color: #2a95d5; font-weight: bold;'><xsl:value-of select='feature'/></td>
        <td><xsl:value-of select='compatible'/></td>
      </tr>
      </xsl:for-each>
    </tbody>
  </table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
"

' XML data to transform
Dim xml As String = "<?xml version='1.0' encoding='UTF-8'?>
<catalog>
  <cd>
    <title>IronPDF</title>
    <feature>Generate, format and manipulate PDFs</feature>
    <compatible>Microsoft Windows, Linux (Debian, CentOS, Ubuntu), MacOS, Docker (Windows, Linux, Azure), Azure (VPS, Webapps, Websites, Functions), AWS</compatible>
  </cd>
  <cd>
    <title>IronOCR</title>
    <feature>OCR engine, input, result</feature>
    <compatible>Microsoft Windows, Linux, MacOS, Docker, Azure, AWS</compatible>
  </cd>
  <cd>
    <title>IronBarcode</title>
    <feature>Format, read and write Barcode</feature>
    <compatible>Microsoft Windows, Linux, MacOS, Docker, Azure, AWS</compatible>
  </cd>
</catalog>
"

' Create an instance of XslCompiledTransform
Dim transform As New XslCompiledTransform()

' Load the XSLT from a string
Using reader As XmlReader = XmlReader.Create(New StringReader(xslt))
	transform.Load(reader)
End Using

' Transform the XML to HTML
Dim results As New StringWriter()
Using reader As XmlReader = XmlReader.Create(New StringReader(xml))
	transform.Transform(reader, Nothing, results)
End Using

' Create a renderer for converting HTML to PDF
Dim renderer As New IronPdf.ChromePdfRenderer()
' Options, headers, and footers may be set here if needed
' Render our XML as a PDF via XSLT transformation
renderer.RenderHtmlAsPdf(results.ToString()).SaveAs("Final.pdf")
$vbLabelText   $csharpLabel

For a more detailed explanation of this code snippet and to explore its additional functionality, please refer to our comprehensive how-to guide.

PDF to HTML

In addition to converting various formats to PDFs, IronPDF also supports the opposite operation of converting PDFs into HTML. Here's a quick code snippet to demonstrate the functionality.

:path=/static-assets/pdf/content-code-examples/how-to/pdf-to-html.cs
using IronPdf;
using System;

PdfDocument pdf = PdfDocument.FromFile("sample.pdf");

// Convert PDF to HTML string
string html = pdf.ToHtmlString();
Console.WriteLine(html);

// Convert PDF to HTML file
pdf.SaveAsHtml("myHtml.html");
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

For a more detailed explanation of this code snippet and to explore its additional functionality, please refer to our comprehensive how-to guide.

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.

:path=/static-assets/pdf/content-code-examples/how-to/aspx-to-pdf-2.cs
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);
        }
    }
}
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
$vbLabelText   $csharpLabel

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.

:path=/static-assets/pdf/content-code-examples/how-to/xaml-to-pdf-maui-mainpage-xaml-cs.cs
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");
    }
}
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
$vbLabelText   $csharpLabel

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.

:path=/static-assets/pdf/content-code-examples/how-to/csharp-pdf-reports-render-html-file.cs
using IronPdf;

ChromePdfRenderer renderer = new ChromePdfRenderer();

renderer.RenderHtmlFileAsPdf("report.html").SaveAs("report.pdf");
Imports IronPdf

Private renderer As New ChromePdfRenderer()

renderer.RenderHtmlFileAsPdf("report.html").SaveAs("report.pdf")
$vbLabelText   $csharpLabel

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

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 pages. Making the creation of PDF files and pages much more streamlined.

[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 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() As IEnumerable(Of PersonInfo)
Public Property Parameters() As 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
$vbLabelText   $csharpLabel

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

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
        return File(pdf.BinaryData, "application/pdf", "viewToPdfMVCCore.pdf");
    }
    return View(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);
}
Public Async Function Persons() As Task(Of IActionResult)
'INSTANT VB NOTE: The local variable persons was renamed since Visual Basic will not allow local variables with the same name as their enclosing function or property:
	Dim persons_Conflict = 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_Conflict)
		Response.Headers.Add("Content-Disposition", "inline")

		' Output PDF document
		Return File(pdf.BinaryData, "application/pdf", "viewToPdfMVCCore.pdf")
	End If
	Return View(persons_Conflict)
End Function
$vbLabelText   $csharpLabel

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 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 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() As ActionResult
'INSTANT VB NOTE: The local variable persons was renamed since Visual Basic will not allow local variables with the same name as their enclosing function or property:
	Dim persons_Conflict = 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_Conflict)
		Response.Headers.Add("Content-Disposition", "inline")

		' View the PDF
		Return File(pdf.BinaryData, "application/pdf")
	End If
	Return View(persons_Conflict)
End Function
$vbLabelText   $csharpLabel

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 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");
});
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");
});
app.MapGet("/PrintPdf", Async Function()
	' 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)
$vbLabelText   $csharpLabel

For a more detailed explanation of this code snippet and to explore its additional functionality, please refer to our comprehensive how-to guide.

Web Accessibility

TLS Website & System Logins

IronPDF offers an easy solution for converting web pages that require authentication. With its rendering options, users can bypass the username and password using the ChromeHttpLoginCredntials property.

:path=/static-assets/pdf/content-code-examples/how-to/logins-username-password.cs
using IronPdf;
using System;

ChromePdfRenderer renderer = new ChromePdfRenderer
{
    // setting login credentials to bypass basic authentication
    LoginCredentials = new ChromeHttpLoginCredentials()
    {
        NetworkUsername = "testUser",
        NetworkPassword = "testPassword"
    }
};

var uri = new Uri("http://localhost:51169/Invoice");

// Render web URL to PDF
PdfDocument pdf = renderer.RenderUrlAsPdf(uri);

// Export PDF
pdf.SaveAs("UrlToPdfExample.Pdf");
Imports IronPdf
Imports System

Private renderer As New ChromePdfRenderer With {
	.LoginCredentials = New ChromeHttpLoginCredentials() With {
		.NetworkUsername = "testUser",
		.NetworkPassword = "testPassword"
	}
}

Private uri = New Uri("http://localhost:51169/Invoice")

' Render web URL to PDF
Private pdf As PdfDocument = renderer.RenderUrlAsPdf(uri)

' Export PDF
pdf.SaveAs("UrlToPdfExample.Pdf")
$vbLabelText   $csharpLabel

For a more detailed explanation of this code snippet and to explore its additional functionality, please refer to our comprehensive how-to guide.

Cookies

Apply cookies to the additional login request to ensure your session is saved! This will make it easier to render additional resources within the locked domain, all within IronPDF.

:path=/static-assets/pdf/content-code-examples/how-to/cookies-apply-cookies.cs
using IronPdf;

// Instantiate ChromePdfRenderer
ChromePdfRenderer renderer = new ChromePdfRenderer();

renderer.RenderingOptions.RequestContext = IronPdf.Rendering.RequestContexts.Global;

ChromeHttpLoginCredentials credentials = new ChromeHttpLoginCredentials() {
    NetworkUsername = "testUser",
    NetworkPassword = "testPassword"
};

string uri = "http://localhost:51169/Invoice";

// Apply cookies
renderer.ApplyCookies(uri, credentials);
Imports IronPdf

' Instantiate ChromePdfRenderer
Private renderer As New ChromePdfRenderer()

renderer.RenderingOptions.RequestContext = IronPdf.Rendering.RequestContexts.Global

Dim credentials As New ChromeHttpLoginCredentials() With {
	.NetworkUsername = "testUser",
	.NetworkPassword = "testPassword"
}

Dim uri As String = "http://localhost:51169/Invoice"

' Apply cookies
renderer.ApplyCookies(uri, credentials)
$vbLabelText   $csharpLabel

For a more detailed explanation of this code snippet and to explore its additional functionality, please refer to our comprehensive how-to guide.

HTTP Request Header

Aside from cookies, IronPDF also allows users to customize their HTTP request header with authorization tokens and other common-related fields.

:path=/static-assets/pdf/content-code-examples/how-to/http-request-header.cs
using IronPdf;
using System.Collections.Generic;

var renderer = new ChromePdfRenderer();
renderer.RenderingOptions.HttpRequestHeaders = new Dictionary<string, string>
{
    { "Authorization", "Bearer test-token-123" }
};

// Render PDF from authenticated page
var pdf = renderer.RenderUrlAsPdf("https://httpbin.org/bearer");
pdf.SaveAs("output.pdf");
Imports IronPdf
Imports System.Collections.Generic

Private renderer = New ChromePdfRenderer()
renderer.RenderingOptions.HttpRequestHeaders = New Dictionary(Of String, String) From {
	{"Authorization", "Bearer test-token-123"}
}

' Render PDF from authenticated page
Dim pdf = renderer.RenderUrlAsPdf("https://httpbin.org/bearer")
pdf.SaveAs("output.pdf")
$vbLabelText   $csharpLabel

For a more detailed explanation of this code snippet and to explore its additional functionality, please refer to our comprehensive how-to guide.

Tailored Your PDF Conversion

Rendering Options

IronPDF allows users to customize the appearance and format of their generated PDFs. The ChromePdfRender class that is used to convert various inputs into PDFs also includes the RenderingOptions property, letting users control how the output looks.

:path=/static-assets/pdf/content-code-examples/how-to/rendering-options-render.cs
using IronPdf;

// Instantiate a ChromePdfRenderer object, which uses a headless version of the Chrome browser
// to render HTML/CSS as a PDF document.
ChromePdfRenderer renderer = new ChromePdfRenderer();

// Configure rendering options
// Enable printing of HTML backgrounds to ensure all styles are visible.
renderer.RenderingOptions.PrintHtmlBackgrounds = true;

// Set HTML header content using HtmlHeaderFooter.
renderer.RenderingOptions.HtmlHeader = new HtmlHeaderFooter
{
    // HTML fragment to add a header at the top of every page in the PDF.
    HtmlFragment = "<h1>Header Content</h1>"
};

// Set a custom paper size for the PDF in millimeters (width and height).
renderer.RenderingOptions.SetCustomPaperSizeinMilimeters(150, 150);

// Set the top margin to zero to start the content from the very top of the page.
renderer.RenderingOptions.MarginTop = 0;

// Define a Markdown string that will be rendered as a PDF.
// Markdown text allows basic formatting like bold and italic styles.
string md = "This is some **bold** and *italic* text.";

// Render the Markdown string to a PDF document.
// The library will convert Markdown syntax into equivalent HTML before rendering it as a PDF.
PdfDocument pdf = renderer.RenderMarkdownStringAsPdf(md);

// Save the generated PDF to a file named "renderingOptions.pdf."
pdf.SaveAs("renderingOptions.pdf");
Imports IronPdf

' Instantiate a ChromePdfRenderer object, which uses a headless version of the Chrome browser
' to render HTML/CSS as a PDF document.
Private renderer As New ChromePdfRenderer()

' Configure rendering options
' Enable printing of HTML backgrounds to ensure all styles are visible.
renderer.RenderingOptions.PrintHtmlBackgrounds = True

' Set HTML header content using HtmlHeaderFooter.
renderer.RenderingOptions.HtmlHeader = New HtmlHeaderFooter With {.HtmlFragment = "<h1>Header Content</h1>"}

' Set a custom paper size for the PDF in millimeters (width and height).
renderer.RenderingOptions.SetCustomPaperSizeinMilimeters(150, 150)

' Set the top margin to zero to start the content from the very top of the page.
renderer.RenderingOptions.MarginTop = 0

' Define a Markdown string that will be rendered as a PDF.
' Markdown text allows basic formatting like bold and italic styles.
Dim md As String = "This is some **bold** and *italic* text."

' Render the Markdown string to a PDF document.
' The library will convert Markdown syntax into equivalent HTML before rendering it as a PDF.
Dim pdf As PdfDocument = renderer.RenderMarkdownStringAsPdf(md)

' Save the generated PDF to a file named "renderingOptions.pdf."
pdf.SaveAs("renderingOptions.pdf")
$vbLabelText   $csharpLabel

For a more detailed explanation of this code snippet and to explore its additional functionality, please refer to our comprehensive how-to guide.

Set Custom Margin

You can further tailor the appearance of your output PDF by adjusting the margins, allowing you to control the layout and spacing precisely.

:path=/static-assets/pdf/content-code-examples/how-to/custom-margins-set-margins.cs
ChromePdfRenderer renderer = new ChromePdfRenderer();

renderer.RenderingOptions.MarginTop = 40;
renderer.RenderingOptions.MarginLeft = 20;
renderer.RenderingOptions.MarginRight = 20;
renderer.RenderingOptions.MarginBottom = 40;
Dim renderer As New ChromePdfRenderer()

renderer.RenderingOptions.MarginTop = 40
renderer.RenderingOptions.MarginLeft = 20
renderer.RenderingOptions.MarginRight = 20
renderer.RenderingOptions.MarginBottom = 40
$vbLabelText   $csharpLabel

For a more detailed explanation of this code snippet and to explore its additional functionality, please refer to our comprehensive how-to guide.

Grayscale

To generate a grayscale PDF, we set the GrayScale property within RenderingOptions to true.

:path=/static-assets/pdf/content-code-examples/how-to/color-grayscale-grayscale.cs
using IronPdf;

ChromePdfRenderer renderer = new ChromePdfRenderer();

// Set GrayScale to true
renderer.RenderingOptions.GrayScale = true;

PdfDocument pdf = renderer.RenderUrlAsPdf("https://ironsoftware.com/");
pdf.CopyPage(0).SaveAs("test.pdf");
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

For a more detailed explanation of this code snippet and to explore its additional functionality, please refer to our comprehensive how-to guide.

Refine Your PDF Layout

Add a Table of Contents

Create a dynamic table of contents with IronPDF to help readers easily navigate your document. IronPDF automatically handles the table of contents with hyperlinks to headers such as h1 and h2. Along with that you can also customize the styling of the table of contents with HTML and CSS styling.

:path=/static-assets/pdf/content-code-examples/how-to/table-of-contents.cs
using IronPdf;

// Instantiate Renderer
ChromePdfRenderer renderer = new ChromePdfRenderer();

// Configure render options
renderer.RenderingOptions = new ChromePdfRenderOptions
{
    // Enable table of content feature
    TableOfContents = TableOfContentsTypes.WithPageNumbers,
};

PdfDocument pdf = renderer.RenderHtmlFileAsPdf("tableOfContent.html");

pdf.SaveAs("tableOfContents.pdf");
Imports IronPdf

' Instantiate Renderer
Private renderer As New ChromePdfRenderer()

' Configure render options
renderer.RenderingOptions = New ChromePdfRenderOptions With {.TableOfContents = TableOfContentsTypes.WithPageNumbers}

Dim pdf As PdfDocument = renderer.RenderHtmlFileAsPdf("tableOfContent.html")

pdf.SaveAs("tableOfContents.pdf")
$vbLabelText   $csharpLabel

For a more detailed explanation of this code snippet and to explore its additional functionality, please refer to our comprehensive how-to guide.

Page Break

Add page breaks between sections to clearly separate content and improve the readability of your document. With IronPDF, simply use the HTML div style= page-break-after to achieve that effect.

:path=/static-assets/pdf/content-code-examples/how-to/html-to-pdf-page-breaks-page-break.cs
using IronPdf;

const string html = @"
  <table style='border: 1px solid #000000'>
    <tr>
      <th>Company</th>
      <th>Product</th>
    </tr>
    <tr>
      <td>Iron Software</td>
      <td>IronPDF</td>
    </tr>
    <tr>
      <td>Iron Software</td>
      <td>IronOCR</td>
    </tr>
  </table>

  <div style='page-break-after: always;'> </div>

  <img src='https://ironpdf.com/img/products/ironpdf-logo-text-dotnet.svg'>";

var renderer = new ChromePdfRenderer();

var pdf = renderer.RenderHtmlAsPdf(html);
pdf.SaveAs("Page_Break.pdf");
Imports IronPdf

Private Const html As String = "
  <table style='border: 1px solid #000000'>
    <tr>
      <th>Company</th>
      <th>Product</th>
    </tr>
    <tr>
      <td>Iron Software</td>
      <td>IronPDF</td>
    </tr>
    <tr>
      <td>Iron Software</td>
      <td>IronOCR</td>
    </tr>
  </table>

  <div style='page-break-after: always;'> </div>

  <img src='https://ironpdf.com/img/products/ironpdf-logo-text-dotnet.svg'>"

Private renderer = New ChromePdfRenderer()

Private pdf = renderer.RenderHtmlAsPdf(html)
pdf.SaveAs("Page_Break.pdf")
$vbLabelText   $csharpLabel

For a more detailed explanation of this code snippet and to explore its additional functionality, please refer to our comprehensive how-to guide.

Fit to Page & Zoom

Need help deciding the dimensions of the content to fit a specified paper size? IronPDF has you covered with the UseChromeDefault, which mimics how Google Chrome's print preview scales content to fit the page.

:path=/static-assets/pdf/content-code-examples/how-to/viewport-zoom-default-chrome.cs
using IronPdf;

ChromePdfRenderer renderer = new ChromePdfRenderer();

// Chrome default rendering
renderer.RenderingOptions.PaperFit.UseChromeDefaultRendering();

// Render web URL to PDF
PdfDocument pdf = renderer.RenderUrlAsPdf("https://en.wikipedia.org/wiki/Main_Page");

pdf.SaveAs("chromeDefault.pdf");
Imports IronPdf

Private renderer As New ChromePdfRenderer()

' Chrome default rendering
renderer.RenderingOptions.PaperFit.UseChromeDefaultRendering()

' Render web URL to PDF
Dim pdf As PdfDocument = renderer.RenderUrlAsPdf("https://en.wikipedia.org/wiki/Main_Page")

pdf.SaveAs("chromeDefault.pdf")
$vbLabelText   $csharpLabel

For a more detailed explanation of this code snippet and to explore its additional functionality, please refer to our comprehensive how-to guide.

Conclusion

The examples above showcase the impressive capabilities and standout features you can unlock while converting various formats to PDFs using IronPDF.

If you would like to request a feature or have general questions about IronPDF or licensing, please contact our support team. We will be more than happy to assist you.

Frequently Asked Questions

How do I convert HTML to PDF using .NET Core?

You can convert HTML to PDF in .NET Core using IronPDF library. Install the library from NuGet, create a ChromePdfRenderer instance, and use methods like RenderHtmlAsPdf to convert HTML strings or RenderUrlAsPdf to convert web pages into PDF documents.

What are the steps to convert a website URL to PDF?

To convert a website URL to PDF with IronPDF: 1) Install the IronPDF NuGet package, 2) Create a ChromePdfRenderer instance, 3) Use the RenderUrlAsPdf method with the target URL, and 4) Save the resulting PdfDocument using the SaveAs method.

How can I convert MVC views to PDF documents?

Convert MVC views to PDF by rendering the view to an HTML string using controller extensions, then passing that HTML to IronPDF's RenderHtmlAsPdf method. This approach enables generating dynamic PDFs from Razor views with model data binding.

Can I work with existing PDF documents?

Yes, IronPDF can open, edit, and manipulate existing PDFs. Use PdfDocument.FromFile to load documents, then perform operations like merging with AppendPdf, adding headers/footers with AddTextHeaders, or applying security settings.

What PDF rendering options are available?

IronPDF offers extensive rendering options through ChromePdfRenderOptions including paper size, orientation, margins, headers, footers, JavaScript execution, CSS media types, custom fonts, and page layout controls for professional document formatting.

How do I deploy PDF applications with Docker?

Deploy IronPDF applications in Docker by configuring Linux dependencies in your Dockerfile, setting appropriate user permissions, and enabling IronPdf.Installation.LinuxAndDockerDependenciesAutoConfig for automatic dependency management in containerized environments.

How can I add digital signatures to PDFs?

Add digital signatures using the PdfSignature class with certificate files (.pfx format). Use the Sign method on PdfDocument objects to apply cryptographic signatures for document authenticity and tamper detection.

What security features are available for PDF files?

IronPDF provides comprehensive security including password protection, user permission controls, encryption settings, and access restrictions. Configure these through the SecuritySettings property to control printing, copying, and editing permissions.

Can I extract text and images from PDFs?

Yes, IronPDF can extract content using ExtractAllText and ExtractAllImages methods for entire documents, or ExtractTextFromPage and ExtractImagesFromPage for specific pages, enabling data processing and content analysis workflows.

How do I add watermarks to PDF documents?

Add watermarks using the Watermark property with HtmlStamp objects for simple text overlays, or use the HtmlStamper class for advanced stamping with HTML content, custom positioning, rotation, and transparency effects.

Jacob Mellor, Chief Technology Officer @ Team Iron
Chief Technology Officer

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.

Jacob holds a First-Class Honours Bachelor of Engineering (BEng) in Civil Engineering from the University of Manchester (1998–2001). After opening his first software business in London in 1999 and creating his first .NET components in 2005, he specialized in solving complex problems across the Microsoft ecosystem.

His flagship IronPDF & IronSuite .NET libraries have achieved over 30 million NuGet installations globally, with his foundational code continuing to power developer tools used worldwide. With 25 years of commercial experience and 41 years of coding expertise, Jacob remains focused on driving innovation in enterprise-grade C#, Java, and Python PDF technologies while mentoring the next generation of technical leaders.

Reviewed by
Jeff Fritz
Jeffrey T. Fritz
Principal Program Manager - .NET Community Team
Jeff is also a Principal Program Manager for the .NET and Visual Studio teams. He is the executive producer of the .NET Conf virtual conference series and hosts 'Fritz and Friends' a live stream for developers that airs twice weekly where he talks tech and writes code together with viewers. Jeff writes workshops, presentations, and plans content for the largest Microsoft developer events including Microsoft Build, Microsoft Ignite, .NET Conf, and the Microsoft MVP Summit