How to Convert Razor Views to PDFs Headlessly in C#
Convert Razor Views to PDFs in C# by using Razor.Templating.Core to transform cshtml files to HTML, then use IronPDF's RenderHtmlAsPdf method to generate PDF documents without requiring a GUI or browser window.
Headless rendering processes web content without a graphical user interface. While IronPdf.Extensions.Razor is useful, it lacks headless rendering capabilities. This guide addresses that gap.
We'll use Razor.Templating.Core to convert cshtml to HTML, then IronPDF to generate PDFs.
Transform Razor Views into PDFs with IronPDF's headless conversion. Use ChromePdfRenderer's RenderHtmlAsPdf method to render HTML from Razor Views into PDFs. This approach works seamlessly in ASP.NET Core environments.
-
1Install IronPDF with NuGet Package Manager
-
2Copy and run this code snippet.
var html = await RazorTemplateEngine.RenderAsync("Views/Template.cshtml", model); new IronPdf.ChromePdfRenderer().RenderHtmlAsPdf(html).SaveAs("output.pdf");C# -
3Deploy to test on your live environment
Start using IronPDF in your project today with a free trial
Minimal Workflow (5 steps)
- Download the C# library for converting Razor Views to PDFs in ASP.NET Core Web App
- Create a new Razor View and edit the file to display the data
- Use the
RenderAsyncmethod to convert from Razor View to HTML - Convert HTML to PDF using the
RenderHtmlAsPdfmethod - Download the sample project for a quick start
Install Razor.Templating.Core to convert Razor Views to HTML in ASP.NET Core Web Apps.
# Install the Razor.Templating.Core package using NuGet Package Manager
Install-Package Razor.Templating.Core
How Do I Set Up My ASP.NET Core Project for Razor to PDF Conversion?
You need an ASP.NET Core Web App (Model-View-Controller) project to convert Views to PDFs. Set up involves creating a project in Visual Studio, installing NuGet packages, and configuring your project structure. For similar techniques, see converting CSHTML to PDF in MVC Core or converting CSHTML to PDF using Razor Pages.
Why Do I Need Razor.Templating.Core Instead of IronPdf.Extensions.Razor?
Razor.Templating.Core provides true headless rendering - converting Razor Views to HTML without a web context or browser window. This suits background services, console applications, or UI-less environments. IronPdf.Extensions.Razor requires a web context to function.
What Project Type Works Best for Headless PDF Generation?
ASP.NET Core Web App (Model-View-Controller) projects provide the necessary Razor View infrastructure with flexible deployment options. Use this approach in background services, Azure Functions, or console applications. See deploying IronPDF to Azure for cloud-based generation.
How Do I Install the Required NuGet Packages?
Install packages using NuGet Package Manager. You need IronPdf and Razor.Templating.Core:
// Install via Package Manager Console
Install-Package IronPdf
Install-Package Razor.Templating.Core
// Or add to your .csproj file
// <PackageReference Include="IronPdf" Version="2024.x.x" />
// <PackageReference Include="Razor.Templating.Core" Version="1.x.x" />
How Do I Create and Configure a Razor View for PDF Generation?
- Right-click the "Home" folder. Choose "add" then "Add View."
- Create an empty Razor View named "Data.cshtml".

What HTML Content Should I Add to My Razor View?
Add the HTML you want to render as PDF:
<table class="table">
<tr>
<th>Name</th>
<th>Title</th>
<th>Description</th>
</tr>
<tr>
<td>John Doe</td>
<td>Software Engineer</td>
<td>Experienced software engineer specializing in web development.</td>
</tr>
<tr>
<td>Alice Smith</td>
<td>Project Manager</td>
<td>Seasoned project manager with expertise in agile methodologies.</td>
</tr>
<tr>
<td>Michael Johnson</td>
<td>Data Analyst</td>
<td>Skilled data analyst proficient in statistical analysis and data visualization.</td>
</tr>
</table>
For complex layouts, use CSS and print styles to ensure perfect PDF rendering. IronPDF supports modern CSS3 features for sophisticated document layouts.
Why Use Tables for PDF Data Display?
Tables provide structured, organized information that translates well to printed documents. They maintain consistent formatting across platforms and are readable in PDF format. IronPDF's rendering engine handles table layouts well, preserving borders, spacing, and alignment. For advanced formatting, explore custom margins to optimize layout.
What Are Common Styling Considerations for PDF Output?
For PDF output, use print-specific CSS media queries, fixed pixel values instead of relative units, and embedded fonts for consistent rendering. IronPDF supports web fonts and icon fonts for brand consistency. Consider page breaks for multi-page documents and appropriate margins for professional appearance.
How Do I Configure Program.cs for Headless PDF Rendering?
In Program.cs, add this code. It uses RenderAsync from Razor.Templating.Core to convert Razor Views to HTML, then instantiates ChromePdfRenderer and passes the HTML to RenderHtmlAsPdf. Use RenderingOptions for custom text, headers, footers, margins, and page numbers.
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();
// Configure rendering options for professional output
renderer.RenderingOptions.PaperSize = IronPdf.PdfPaperSize.A4;
renderer.RenderingOptions.MarginTop = 25;
renderer.RenderingOptions.MarginBottom = 25;
renderer.RenderingOptions.MarginLeft = 20;
renderer.RenderingOptions.MarginRight = 20;
// 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");
});Imports IronPdf
Imports Microsoft.AspNetCore.Http
app.MapGet("/PrintPdf", Async Function() As Task(Of IResult)
' 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()
' Configure rendering options for professional output
renderer.RenderingOptions.PaperSize = IronPdf.PdfPaperSize.A4
renderer.RenderingOptions.MarginTop = 25
renderer.RenderingOptions.MarginBottom = 25
renderer.RenderingOptions.MarginLeft = 20
renderer.RenderingOptions.MarginRight = 20
' 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)What Rendering Options Can I Apply to My PDFs?
IronPDF provides extensive rendering options. Add headers and footers, set custom paper sizes, control page orientation, and add watermarks. ChromePdfRenderer offers over 50 properties to customize PDF generation.
How Do I Handle Errors During PDF Generation?
Implement error handling for robust PDF generation:
try
{
var html = await RazorTemplateEngine.RenderAsync("Views/Home/Data.cshtml");
var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderHtmlAsPdf(html, "./wwwroot");
return Results.File(pdf.BinaryData, "application/pdf", "razorViewToPdf.pdf");
}
catch (Exception ex)
{
// Log the error details
IronPdf.Logging.Logger.Log($"PDF generation failed: {ex.Message}");
return Results.Problem("Failed to generate PDF", statusCode: 500);
}Imports IronPdf
Imports System.Threading.Tasks
Try
Dim html = Await RazorTemplateEngine.RenderAsync("Views/Home/Data.cshtml")
Dim renderer As New ChromePdfRenderer()
Dim pdf = renderer.RenderHtmlAsPdf(html, "./wwwroot")
Return Results.File(pdf.BinaryData, "application/pdf", "razorViewToPdf.pdf")
Catch ex As Exception
' Log the error details
IronPdf.Logging.Logger.Log($"PDF generation failed: {ex.Message}")
Return Results.Problem("Failed to generate PDF", statusCode:=500)
End TryWhen Should I Enable Detailed Logging?
Enable detailed logging during development and troubleshooting. IronPDF's logging provides insights into rendering, helping identify HTML parsing, asset loading, or configuration problems. For production, use custom logging to integrate with your application's logging infrastructure.
The IronSuite play a crucial role in our operations. These are tools that increase efficiencies across the business including creating floor plans and improving inventory management.
Why Do I Need to Modify Asset Link Paths?
Navigate to Views > Shared > _Layout.cshtml. In link tags, change "~/" to "./" because "~/" doesn't work well with IronPDF.
What Other Path-Related Issues Should I Watch For?
Beyond the tilde (~) path issue, ensure image sources use absolute paths or proper relative references. For external resources, use base URLs to ensure assets load correctly. For Azure Blob Storage images, see embedding images from Azure Blob Storage.
How Do Static Assets Affect PDF Generation?
Static assets (CSS, JavaScript, images) impact PDF generation performance and quality. Ensure assets are accessible during rendering, use optimized images, and consider embedding critical CSS inline for faster rendering. Learn about rendering delays and timeouts for JavaScript-heavy content.
How Do I Test My Headless PDF Generation?
Run the project to generate a PDF document.
Output PDF
What Should My Final PDF Look Like?
Your PDF should maintain all Razor View formatting - table structures, fonts, colors, and layout. It should be properly sized with clean margins and professional appearance. To verify output quality, use IronPDF's rasterization features to preview pages as images.
How Can I Troubleshoot Common PDF Rendering Issues?
Common issues include missing styles, broken layouts, or incomplete content. Enable detailed logging, verify asset paths, and ensure HTML validates properly. For complex layouts, use Chrome debugging tools to preview HTML before conversion. For specific rendering problems, use WaitFor delays to ensure content loads before rendering.
Where Can I Download a Complete Working Example?
Download the complete code as a zipped Visual Studio ASP.NET Core Web App (Model-View-Controller) project.
Click here to download the project.
What Are the Prerequisites for Running the Sample Project?
You need Visual Studio 2019 or later with .NET 8.0 SDK or higher (LTS). The project requires an internet connection for NuGet package restoration. Update your IronPDF license key in Program.cs before running. For deployment, review the Windows installation guide for additional requirements.
How Do I Customize the Sample for My Use Case?
The sample provides a foundation for your specific needs. Add dynamic data models, implement caching for frequently generated PDFs, or integrate with existing authentication. For advanced scenarios, explore async PDF generation for improved performance, or implement PDF compression to reduce file sizes. Add digital signatures for document authenticity or password protection for sensitive documents.
Frequently Asked Questions
What is the main purpose of using IronPDF's headless conversion method?
IronPDF's headless conversion method is designed to transform Razor Views into PDF documents without requiring a GUI or browser window, making it ideal for background services and environments that don't support a graphical user interface.
Why is Razor.Templating.Core favored over IronPdf.Extensions.Razor for headless rendering?
Razor.Templating.Core offers true headless rendering by converting Razor Views to HTML without a web context or browser, unlike IronPdf.Extensions.Razor, which requires a web context, making it more suitable for UI-less environments.
How do you convert HTML to PDF using IronPDF?
With IronPDF, you use the ChromePdfRenderer class's RenderHtmlAsPdf method to convert HTML into PDFs, allowing for seamless integration into ASP.NET Core applications.
What are the essential NuGet packages required for Razor to PDF conversion in ASP.NET Core?
You need to install the IronPdf and Razor.Templating.Core packages using the NuGet Package Manager to facilitate Razor to PDF conversion in ASP.NET Core.
How can you implement error handling in PDF generation with IronPDF?
Error handling can be implemented using try-catch blocks in your PDF generation code to capture exceptions and log errors, ensuring robust and fail-safe PDF generation.
What customizations does IronPDF support for PDF rendering?
IronPDF supports a wide range of customizations, including headers, footers, custom paper sizes, page orientations, watermarks, and over 50 properties tailored for professional document generation.
What are the key considerations for styling HTML content for PDF rendering?
When styling HTML for PDF, focus on using print-specific CSS, fixed pixel values, and embedded fonts to ensure consistent rendering, as well as defining margins and breaks appropriately for professional output.
How can static assets impact PDF generation with IronPDF?
Static assets such as CSS, JavaScript, and images influence the quality and speed of PDF rendering. Ensuring assets are accessible and optimized is crucial for consistent performance and visual accuracy.
What should you do if asset paths cause issues in PDF rendering?
Ensure asset paths are correctly formatted, avoiding problematic paths like '~/' and using absolute or properly relative path references to guarantee that all resources load during the rendering process.
What are the prerequisites for running the sample Razor to PDF conversion project?
To run the sample project, you need Visual Studio 2019 or later with the .NET 8.0 SDK and an active internet connection for NuGet package restoration. Additionally, update your IronPDF license key in the code.

Curtis Chau holds a Bachelor’s degree in Computer Science (Carleton University) and specializes in front-end development with expertise in Node.js, TypeScript, JavaScript, and React. Passionate about crafting intuitive and aesthetically pleasing user interfaces, Curtis enjoys working with modern frameworks and creating well-structured, visually appealing manuals.