How to Convert HTML to PDF in C# .NET Core
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.
Get started making PDFs with NuGet now:
Install IronPDF with NuGet Package Manager
Copy and run this code snippet.
var pdf = new IronPdf.ChromePdfRenderer().RenderHtmlAsPdf("<h1>Hello, PDF!</h1>");Deploy to test on your live environment
Table of Contents
- Versatile PDF Conversion
- Dynamic Web Page to PDFs
- Web Accessibility
- Tailored PDF Conversion
- Refine PDF Layout
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.csusing 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");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.csusing 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");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.csusing 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");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.csusing IronPdf;
string imagePath = "meetOurTeam.jpg";
// Convert an image to a PDF
PdfDocument pdf = ImageToPdfConverter.ImageToPdf(imagePath);
// Export the PDF
pdf.SaveAs("imageToPdf.pdf");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.csusing 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");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 the RenderDocxAsPDF method to convert.
:path=/static-assets/pdf/content-code-examples/how-to/docx-to-pdf-from-file.csusing 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");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 the RenderRtfFileAsPdf method with the RTF file as input.
:path=/static-assets/pdf/content-code-examples/how-to/rtf-to-pdf-from-file.csusing IronPdf;
// Instantiate Renderer
ChromePdfRenderer renderer = new ChromePdfRenderer();
// Render from RTF file
PdfDocument pdf = renderer.RenderRtfFileAsPdf("sample.rtf");
// Save the PDF
pdf.SaveAs("pdfFromRtfFile.pdf");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.csusing IronPdf;
// Instantiate Renderer
ChromePdfRenderer renderer = new ChromePdfRenderer();
// Render from markdown file
PdfDocument pdf = renderer.RenderMarkdownFileAsPdf("sample.md");
// Save the PDF
pdf.SaveAs("pdfFromMarkdownFile.pdf");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>
";
[...]
// 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>
";
[...]
// 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");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.csusing 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");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.csusing 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);
}
}
}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.csusing 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");
}
}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.csusing IronPdf;
ChromePdfRenderer renderer = new ChromePdfRenderer();
renderer.RenderHtmlFileAsPdf("report.html").SaveAs("report.pdf");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";
}
}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);
}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");
}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);
}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);
}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");
});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.csusing 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");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.csusing 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);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.csusing 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");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.csusing 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");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.csChromePdfRenderer renderer = new ChromePdfRenderer();
renderer.RenderingOptions.MarginTop = 40;
renderer.RenderingOptions.MarginLeft = 20;
renderer.RenderingOptions.MarginRight = 20;
renderer.RenderingOptions.MarginBottom = 40;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.csusing 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");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.csusing 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");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.csusing 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");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.csusing 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");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 in .NET Core?
To convert HTML to PDF in .NET Core, use the IronPDF library. First, install the package via NuGet. Then, create an instance of ChromePdfRenderer and utilize the RenderHtmlAsPdf method to convert HTML strings into PDF format.
How can I convert a live URL to a PDF document?
You can convert a live URL to a PDF document using IronPDF by installing the library from NuGet, creating a ChromePdfRenderer instance, and calling the RenderUrlAsPdf method with the webpage URL you want to convert.
What are the steps for converting Razor views to PDF?
To convert Razor views to PDF, render the view into an HTML string and then pass it to IronPDF's RenderHtmlAsPdf method. This allows for creating dynamic PDFs from MVC views with full data binding.
Can existing PDF files be modified?
Yes, existing PDF files can be modified using IronPDF. Use PdfDocument.FromFile to load a PDF, and then apply modifications such as merging, adding headers/footers, or altering security settings.
What options are available for rendering PDFs?
IronPDF provides various rendering options through ChromePdfRenderOptions. You can customize paper size, orientation, margins, and more, ensuring your PDFs meet specific layout and style requirements.
How can PDFs be deployed in a Docker environment?
Deploy PDFs in a Docker environment by configuring Linux dependencies within your Dockerfile. Use IronPDF's IronPdf.Installation.LinuxAndDockerDependenciesAutoConfig for handling dependencies automatically in containerized applications.
Is it possible to add digital signatures to PDF files?
Yes, digital signatures can be added to PDF files using the PdfSignature class. By utilizing the Sign method and a certificate file, you can ensure document authenticity and integrity.
What security features does IronPDF offer for PDFs?
IronPDF offers robust security features including password protection, encryption, and access control. Set these features via the SecuritySettings property to manage permissions for viewing, printing, and editing.
How can text and images be extracted from PDF documents?
Text and images can be extracted from PDF documents using IronPDF's ExtractAllText and ExtractAllImages methods. These allow for processing data from entire documents or specific pages.
How do I apply watermarks to PDF files?
Watermarks can be applied to PDF files by using IronPDF's Watermark property with HtmlStamp objects. For more advanced needs, the HtmlStamper class supports HTML-based stamps with customizable styles.
Is IronPDF compatible with .NET 10, and how do I use it in a .NET 10 project?
Yes—IronPDF fully supports .NET 10 as part of its cross-platform, modern .NET version support. To use it in a .NET 10 project, install the IronPdf NuGet package, reference it in your project file targeting net10.0, and then use classes like ChromePdfRenderer and methods like RenderHtmlAsPdf just as you would in earlier .NET versions. You benefit from improved performance, memory usage, and runtime enhancements inherent to .NET 10 when rendering or manipulating PDFs.







