Cómo generar archivos PDF en .NET Core

How to Convert HTML to PDF in .NET Core

This article was translated from English: Does it need improvement?
Translated
View the article in English

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.

Quickstart: Convert HTML to PDF with IronPDF

Get started with IronPDF to convert HTML to PDF effortlessly in .NET Core. With just a single line of code, you can render pixel-perfect PDFs from HTML strings using IronPDF's powerful API. This guide will show you how to quickly integrate IronPDF into your project, enabling seamless PDF generation with minimal setup. Whether you're converting HTML, URLs, or Razor views, IronPDF simplifies the process, making it accessible for developers of all levels. Start converting today and explore advanced features when you're ready.

Nuget IconGet started making PDFs with NuGet now:

  1. Install IronPDF with NuGet Package Manager

    PM > Install-Package IronPdf

  2. Copy and run this code snippet.

    var pdf = new IronPdf.ChromePdfRenderer().RenderHtmlAsPdf("<h1>Hello, PDF!</h1>");
  3. Deploy to test on your live environment

    Start using IronPDF in your project today with a free trial
    arrow pointer

Table of Contents

Comience a usar IronPDF en su proyecto hoy con una prueba gratuita.

Primer Paso:
green arrow pointer
NuGet Instalar con NuGet

PM >  Install-Package IronPdf

Echa un vistazo a IronPDF en NuGet para una instalación rápida. Con más de 10 millones de descargas, está transformando el desarrollo de PDF con C#. También puede descargar el DLL o el instalador de Windows.

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.

Preguntas Frecuentes

¿Cómo convierto HTML a PDF en .NET Core?

Para convertir HTML a PDF en .NET Core, utiliza la biblioteca IronPDF. Primero, instala el paquete a través de NuGet. Luego, crea una instancia de ChromePdfRenderer y utiliza el método RenderHtmlAsPdf para convertir cadenas HTML al formato PDF.

¿Cómo puedo convertir una URL en vivo a un documento PDF?

Puedes convertir una URL en vivo a un documento PDF usando IronPDF instalando la biblioteca desde NuGet, creando una instancia de ChromePdfRenderer y llamando al método RenderUrlAsPdf con la URL de la página web que deseas convertir.

¿Cuáles son los pasos para convertir vistas Razor a PDF?

Para convertir vistas Razor a PDF, renderiza la vista en una cadena HTML y luego pásala al método RenderHtmlAsPdf de IronPDF. Esto permite crear PDFs dinámicos desde vistas MVC con vinculación de datos completa.

¿Pueden modificarse los archivos PDF existentes?

Sí, los archivos PDF existentes pueden modificarse usando IronPDF. Usa PdfDocument.FromFile para cargar un PDF, y luego aplica modificaciones como unir, agregar encabezados/pies de página o alterar configuraciones de seguridad.

¿Qué opciones están disponibles para renderizar PDFs?

IronPDF proporciona varias opciones de renderizado a través de ChromePdfRenderOptions. Puedes personalizar el tamaño del papel, la orientación, los márgenes y más, asegurando que tus PDFs cumplan con requisitos específicos de diseño y estilo.

¿Cómo pueden desplegarse PDFs en un entorno Docker?

Despliega PDFs en un entorno Docker configurando las dependencias de Linux dentro de tu Dockerfile. Usa IronPdf.Installation.LinuxAndDockerDependenciesAutoConfig de IronPDF para gestionar automáticamente las dependencias en aplicaciones contenedorizadas.

¿Es posible añadir firmas digitales a archivos PDF?

Sí, se pueden añadir firmas digitales a archivos PDF utilizando la clase PdfSignature. Al utilizar el método Sign y un archivo de certificado, puedes garantizar la autenticidad e integridad del documento.

¿Qué características de seguridad ofrece IronPDF para PDFs?

IronPDF ofrece robustas características de seguridad incluyendo protección con contraseña, cifrado y control de acceso. Establece estas características a través de la propiedad SecuritySettings para gestionar permisos de visualización, impresión y edición.

¿Cómo pueden extraerse texto e imágenes de documentos PDF?

Texto e imágenes pueden extraerse de documentos PDF utilizando los métodos ExtractAllText y ExtractAllImages de IronPDF. Estos permiten procesar datos de documentos enteros o páginas específicas.

¿Cómo aplico marcas de agua a los archivos PDF?

Las marcas de agua pueden aplicarse a archivos PDF usando la propiedad Watermark de IronPDF con objetos HtmlStamp. Para necesidades más avanzadas, la clase HtmlStamper soporta estampados basados en HTML con estilos personalizables.

¿IronPDF es compatible con .NET 10 y cómo lo uso en un proyecto .NET 10?

Sí, IronPDF es totalmente compatible con .NET 10 gracias a su compatibilidad multiplataforma con versiones modernas de .NET. Para usarlo en un proyecto .NET 10, instale el paquete NuGet IronPdf , haga referencia a él en el archivo de proyecto que tenga como destino net10.0 y, a continuación, utilice clases como ChromePdfRenderer y métodos como RenderHtmlAsPdf tal como lo haría en versiones anteriores de .NET. Disfrute de un mejor rendimiento, uso de memoria y mejoras en el tiempo de ejecución inherentes a .NET 10 al renderizar o manipular archivos PDF.

Jacob Mellor, Director de Tecnología @ Team Iron
Director de Tecnología

Jacob Mellor es Director de Tecnología en Iron Software y un ingeniero visionario que lidera la tecnología PDF en C#. Como el desarrollador original detrás de la base de código central de Iron Software, ha moldeado la arquitectura de productos de la compañía desde ...

Leer más
Revisado por
Jeff Fritz
Jeffrey T. Fritz
Gerente Principal de Programas - Equipo de la Comunidad .NET
Jeff también es Gerente Principal de Programas para los equipos de .NET y Visual Studio. Es el productor ejecutivo de la serie de conferencias virtuales .NET Conf y anfitrión de 'Fritz and Friends', una transmisión en vivo para desarrolladores que se emite dos veces a la semana donde habla sobre tecnología y escribe código junto con la audiencia. Jeff escribe talleres, presentaciones, y planifica contenido para los eventos de desarrolladores más importantes de Microsoft, incluyendo Microsoft Build, Microsoft Ignite, .NET Conf y la Cumbre de Microsoft MVP.
¿Listo para empezar?
Nuget Descargas 16,133,208 | Versión: 2025.11 recién lanzado