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

In this video tutorial, viewers learn how to convert Razor views to PDF files in an ASP.NET MVC Core project using Iron PDF. The tutorial begins by ensuring that necessary NuGet packages, such as Iron PDF and Razor.Templating.Doc, are installed. The process starts with adding a new Razor view within the project's views folder, creating a data.cshtml file, and populating it with HTML content, such as tables displaying names and descriptions.

The next step involves editing the Program.cs file to set up an endpoint that handles the PDF generation process. This involves configuring Iron PDF with a license key for full functionality and enabling logging for debugging purposes. The Razor Template Engine's RenderAsync method is used to convert the Razor view to an HTML string, followed by instantiating a Chrome PDF Renderer to handle the conversion from HTML to PDF.

Below is a sample code snippet to illustrate this process:

using IronPdf;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Razor.Templating.Core;
using System.Threading.Tasks;

var builder = WebApplication.CreateBuilder(args);

// Add Razor.Templating
builder.Services.AddRazorTemplating();

var app = builder.Build();

if (app.Environment.IsDevelopment())
{
    app.UseDeveloperExceptionPage();
}

// Set up the endpoint
app.MapGet("/printPDF", async context =>
{
    // License key for IronPDF
    IronPdf.License.LicenseKey = "YOUR_LICENSE_KEY_HERE";

    // Render the Razor view to an HTML string
    var htmlContent = await RazorTemplateEngine.RenderAsync("Views/data.cshtml", null);

    // Configure IronPDF with Chrome PDF Renderer
    var renderer = new ChromePdfRenderer();

    // Enable logging for diagnostics
    renderer.RenderingOptions.Debug = true;

    // Convert HTML to PDF
    var pdf = await renderer.RenderHtmlAsPdfAsync(htmlContent);

    // Create a file response
    var pdfBytes = pdf.BinaryData;
    context.Response.ContentType = "application/pdf";
    await context.Response.Body.WriteAsync(pdfBytes, 0, pdfBytes.Length);
    context.Response.Headers.Add("Content-Disposition", "attachment; filename=GeneratedDocument.pdf");
});

app.Run();
using IronPdf;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Razor.Templating.Core;
using System.Threading.Tasks;

var builder = WebApplication.CreateBuilder(args);

// Add Razor.Templating
builder.Services.AddRazorTemplating();

var app = builder.Build();

if (app.Environment.IsDevelopment())
{
    app.UseDeveloperExceptionPage();
}

// Set up the endpoint
app.MapGet("/printPDF", async context =>
{
    // License key for IronPDF
    IronPdf.License.LicenseKey = "YOUR_LICENSE_KEY_HERE";

    // Render the Razor view to an HTML string
    var htmlContent = await RazorTemplateEngine.RenderAsync("Views/data.cshtml", null);

    // Configure IronPDF with Chrome PDF Renderer
    var renderer = new ChromePdfRenderer();

    // Enable logging for diagnostics
    renderer.RenderingOptions.Debug = true;

    // Convert HTML to PDF
    var pdf = await renderer.RenderHtmlAsPdfAsync(htmlContent);

    // Create a file response
    var pdfBytes = pdf.BinaryData;
    context.Response.ContentType = "application/pdf";
    await context.Response.Body.WriteAsync(pdfBytes, 0, pdfBytes.Length);
    context.Response.Headers.Add("Content-Disposition", "attachment; filename=GeneratedDocument.pdf");
});

app.Run();
Imports IronPdf
Imports Microsoft.AspNetCore.Builder
Imports Microsoft.AspNetCore.Hosting
Imports Microsoft.Extensions.DependencyInjection
Imports Microsoft.Extensions.Hosting
Imports Razor.Templating.Core
Imports System.Threading.Tasks

Private builder = WebApplication.CreateBuilder(args)

' Add Razor.Templating
builder.Services.AddRazorTemplating()

Dim app = builder.Build()

If app.Environment.IsDevelopment() Then
	app.UseDeveloperExceptionPage()
End If

' Set up the endpoint
app.MapGet("/printPDF", Async Function(context)
	' License key for IronPDF
	IronPdf.License.LicenseKey = "YOUR_LICENSE_KEY_HERE"

	' Render the Razor view to an HTML string
	Dim htmlContent = Await RazorTemplateEngine.RenderAsync("Views/data.cshtml", Nothing)

	' Configure IronPDF with Chrome PDF Renderer
	Dim renderer = New ChromePdfRenderer()

	' Enable logging for diagnostics
	renderer.RenderingOptions.Debug = True

	' Convert HTML to PDF
	Dim pdf = Await renderer.RenderHtmlAsPdfAsync(htmlContent)

	' Create a file response
	Dim pdfBytes = pdf.BinaryData
	context.Response.ContentType = "application/pdf"
	Await context.Response.Body.WriteAsync(pdfBytes, 0, pdfBytes.Length)
	context.Response.Headers.Add("Content-Disposition", "attachment; filename=GeneratedDocument.pdf")
End Function)

app.Run()
$vbLabelText   $csharpLabel
  1. License Setup: Replace "YOUR_LICENSE_KEY_HERE" with your actual Iron PDF license key.
  2. HTML Conversion: The RenderAsync method converts the Razor view (data.cshtml) into HTML.
  3. PDF Generation: The ChromePdfRenderer creates a PDF from the HTML string. Debug mode is enabled for logging detailed information during processing.
  4. File Response: The generated PDF is sent as a file download in the HTTP response.

A crucial step is to modify the layout.cshtml file to replace the tilde (~) symbol with a dot (.) in <link> tags for compatibility with Iron PDF.

Finally, the tutorial demonstrates accessing the /printPDF endpoint to download the generated PDF, effectively rendering the Razor view's content. The video concludes by encouraging viewers to engage with the content through likes and subscriptions, and suggesting a trial of the software with a link provided in the description.

Further Reading: How to Convert Razor Views to PDFs Headlessly

Chipego
Software Engineer
Chipego has a natural skill for listening that helps him to comprehend customer issues, and offer intelligent solutions. He joined the Iron Software team in 2023, after studying a Bachelor of Science in Information Technology. IronPDF and IronOCR are the two products Chipego has been focusing on, but his knowledge of all products is growing daily, as he finds new ways to support customers. He enjoys how collaborative life is at Iron Software, with team members from across the company bringing their varied experience to contribute to effective, innovative solutions. When Chipego is away from his desk, he can often be found enjoying a good book or playing football.
< PREVIOUS
How to Convert Razor Pages to PDFs in ASP .NET Core Web App
NEXT >
How to Convert Views to PDFs in ASPNET