How to Convert CSHTML to PDF Using Razor Headlessly in C# | IronPDF

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.

Quickstart: Convert Razor Views to PDF in Seconds

Transform Razor Views into PDFs with IronPDF's headless conversion. Use IronPdf.HtmlToPdf.StaticRender.RenderHtmlAsPdf to render HTML from Razor Views into PDFs. This approach works seamlessly in ASP.NET Core environments.

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 html = await RazorTemplateEngine.RenderAsync("Views/Template.cshtml", model); 
    new IronPdf.ChromePdfRenderer().RenderHtmlAsPdf(html).SaveAs("output.pdf");
  3. Deploy to test on your live environment

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

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
# Install the Razor.Templating.Core package using NuGet Package Manager
Install-Package Razor.Templating.Core
SHELL

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" />
// 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" />
$vbLabelText   $csharpLabel

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".

 related to How Do I Create and Configure a Razor View for PDF Generation?

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>
<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>
HTML

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

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

When 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.

Navigate to Views > Shared > "_Layout.cshtml". In link tags, change "~/" to "./" because "~/" doesn't work well with IronPDF.

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.

Visual Studio showing running ASP.NET Core MVC app with Program.cs open and successful debug output

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 6.0 SDK or higher. The project requires 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

How do I convert Razor Views to PDF without a GUI in C#?

Use Razor.Templating.Core to convert cshtml files to HTML, then use IronPDF's RenderHtmlAsPdf method to generate PDFs headlessly. This two-step process allows you to transform Razor Views into PDF documents without requiring a graphical user interface or browser window.

What's the quickest way to render a Razor view to PDF headlessly?

The fastest approach is using two lines of code: first convert your Razor view to HTML with RazorTemplateEngine.RenderAsync, then use IronPDF's ChromePdfRenderer().RenderHtmlAsPdf(html).SaveAs() method to create and save the PDF file.

Why should I use Razor.Templating.Core instead of IronPdf.Extensions.Razor?

Razor.Templating.Core provides true headless rendering capabilities, allowing you to convert Razor Views to HTML without a web context or browser window. While IronPdf.Extensions.Razor is useful, it requires a web context to function, making Razor.Templating.Core better suited for background services and console applications.

What type of ASP.NET Core project do I need for headless PDF generation?

Use an ASP.NET Core Web App (Model-View-Controller) project, which provides the necessary Razor View infrastructure with flexible deployment options. This setup works well with IronPDF for background services, Azure Functions, or console applications.

How do I install the required packages for Razor to PDF conversion?

Install Razor.Templating.Core using NuGet Package Manager with the command 'Install-Package Razor.Templating.Core'. You'll also need IronPDF installed in your project to handle the HTML to PDF conversion step.

Can I use this headless PDF generation approach in cloud environments?

Yes, IronPDF's headless Razor to PDF conversion works excellently in cloud environments including Azure Functions, AWS Lambda, and containerized applications, making it ideal for scalable document generation services.

Curtis Chau
Technical Writer

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.

...

Read More
Ready to Get Started?
Nuget Downloads 17,012,929 | Version: 2025.12 just released