How to Convert Razor Pages to PDFs in ASP.NET Core Web App

A Razor Page is a file with a .cshtml extension that combines C# and HTML to generate web content. In ASP.NET Core, Razor Pages are a simpler way to organize code for web applications, making them a good fit for simple pages that are read-only or do simple data input.

An ASP.NET Core Web App is a web application built using ASP.NET Core, a cross-platform framework for developing modern web applications.

IronPDF simplifies the process of creating PDF files from Razor Pages within an ASP.NET Core Web App project. This makes PDF generation easy and direct in ASP.NET Core Web Apps.


Nuget IconGet started making PDFs with NuGet now:

  1. Install IronPDF with NuGet

    PM > Install-Package IronPdf

  2. Copy the code

    new IronPdf.ChromePdfRenderer().RenderRazorViewToPdf(HttpContext, "Views/Home/Example.cshtml", model).SaveAs("viewReport.pdf");
  3. Deploy to test on your live environment

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

IronPDF Extension Package

The IronPdf.Extensions.Razor package is an extension of the main IronPdf package. Both the IronPdf.Extensions.Razor and IronPdf packages are needed to render Razor Pages to PDF documents in an ASP.NET Core Web App.

# Command to install IronPdf.Extensions.Razor package using NuGet Package Manager
Install-Package IronPdf.Extensions.Razor
# Command to install IronPdf.Extensions.Razor package using NuGet Package Manager
Install-Package IronPdf.Extensions.Razor
SHELL
C# NuGet Library for PDF

Install with NuGet

Install-Package IronPdf.Extensions.Razor

Render Razor Pages to PDFs

You'll need an ASP.NET Core Web App project to convert Razor pages into PDF files.

Create a Model Class

  • Create a new folder in the project and name it "Models."
  • Add a standard C# class to the folder and name it "Person." This class will serve as a model for individual data. Use the following code snippet:
:path=/static-assets/pdf/content-code-examples/how-to/cshtml-to-pdf-razor-model.cs
namespace RazorPageSample.Models
{
    public class Person
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Title { get; set; }
        public string Description { get; set; }
    }
}
Namespace RazorPageSample.Models
	Public Class Person
		Public Property Id() As Integer
		Public Property Name() As String
		Public Property Title() As String
		Public Property Description() As String
	End Class
End Namespace
$vbLabelText   $csharpLabel

Add a Razor Page

Add an empty Razor Page to the "Pages" folder and name it "persons.cshtml."

  • Modify the newly-created "Persons.cshtml" file using the code sample provided below.

The code below is for displaying the information in the browser.

@page
@using RazorPageSample.Models;
@model RazorPageSample.Pages.PersonsModel
@{
}

<table class="table">
    <tr>
        <th>Name</th>
        <th>Title</th>
        <th>Description</th>
    </tr>
    @foreach (var person in ViewData["personList"] as List<Person>)
    {
        <tr>
            <td>@person.Name</td>
            <td>@person.Title</td>
            <td>@person.Description</td>
        </tr>
    }
</table>

<form method="post">
    <button type="submit">Print</button>
</form>
@page
@using RazorPageSample.Models;
@model RazorPageSample.Pages.PersonsModel
@{
}

<table class="table">
    <tr>
        <th>Name</th>
        <th>Title</th>
        <th>Description</th>
    </tr>
    @foreach (var person in ViewData["personList"] as List<Person>)
    {
        <tr>
            <td>@person.Name</td>
            <td>@person.Title</td>
            <td>@person.Description</td>
        </tr>
    }
</table>

<form method="post">
    <button type="submit">Print</button>
</form>
HTML

Next, the code below first instantiates the ChromePdfRenderer class. Passing this to the RenderRazorToPdf method is sufficient to convert this Razor Page to a PDF document.

The user has full access to the features available in RenderingOptions. These features include the ability to apply page numbers to the generated PDF, set custom margins, and add custom text as well as HTML headers and footers.

  • Open the dropdown for the "Persons.cshtml" file to see the "Persons.cshtml.cs" file.
  • Modify the "Persons.cshtml.cs" with the code below.
using IronPdf.Razor;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using RazorPageSample.Models;

namespace RazorPageSample.Pages
{
    public class PersonsModel : PageModel
    {
        [BindProperty(SupportsGet = true)]
        public List<Person> Persons { get; set; }

        // Handle GET request to load initial data
        public void OnGet()
        {
            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;
        }

        // Handle POST request to convert Razor page to PDF
        public IActionResult OnPost()
        {
            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);

            // Return the generated PDF file with appropriate content headers
            Response.Headers.Add("Content-Disposition", "inline");
            return File(pdf.BinaryData, "application/pdf", "razorPageToPdf.pdf");

            // Optionally view the output PDF in browser (uncomment below line if needed)
            // return File(pdf.BinaryData, "application/pdf");
        }
    }
}
using IronPdf.Razor;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using RazorPageSample.Models;

namespace RazorPageSample.Pages
{
    public class PersonsModel : PageModel
    {
        [BindProperty(SupportsGet = true)]
        public List<Person> Persons { get; set; }

        // Handle GET request to load initial data
        public void OnGet()
        {
            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;
        }

        // Handle POST request to convert Razor page to PDF
        public IActionResult OnPost()
        {
            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);

            // Return the generated PDF file with appropriate content headers
            Response.Headers.Add("Content-Disposition", "inline");
            return File(pdf.BinaryData, "application/pdf", "razorPageToPdf.pdf");

            // Optionally view the output PDF in browser (uncomment below line if needed)
            // return File(pdf.BinaryData, "application/pdf");
        }
    }
}
Imports IronPdf.Razor
Imports Microsoft.AspNetCore.Mvc
Imports Microsoft.AspNetCore.Mvc.RazorPages
Imports RazorPageSample.Models

Namespace RazorPageSample.Pages
	Public Class PersonsModel
		Inherits PageModel

		<BindProperty(SupportsGet := True)>
		Public Property Persons() As List(Of Person)

		' Handle GET request to load initial data
		Public Sub OnGet()
			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
		End Sub

		' Handle POST request to convert Razor page to PDF
		Public Function OnPost() 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)

			' Return the generated PDF file with appropriate content headers
			Response.Headers.Add("Content-Disposition", "inline")
			Return File(pdf.BinaryData, "application/pdf", "razorPageToPdf.pdf")

			' Optionally view the output PDF in browser (uncomment below line if needed)
			' return File(pdf.BinaryData, "application/pdf");
		End Function
	End Class
End Namespace
$vbLabelText   $csharpLabel

The RenderRazorToPdf method returns a PdfDocument object that can undergo additional processing and editing. You can export the PDF as PDFA or PDFUA, apply a digital signature to the rendered PDF document, or merge and split PDF documents. The method also allows you to rotate pages, add annotations or bookmarks, and stamp custom watermarks onto your PDF.

Add a Section to the Top Navigation Bar

  • Navigate to the Pages folder -> Shared folder -> _Layout.cshtml. Place the "Person" navigation item after "Home".

Make sure the value for the asp-page attribute matches exactly with our file name, which in this case is "Persons".

<header>
    <nav class="navbar navbar-expand-sm navbar-toggleable-sm navbar-light bg-white border-bottom box-shadow mb-3">
        <div class="container">
            <a class="navbar-brand" asp-area="" asp-page="/Index">RazorPageSample</a>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target=".navbar-collapse" aria-controls="navbarSupportedContent"
                    aria-expanded="false" aria-label="Toggle navigation">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="navbar-collapse collapse d-sm-inline-flex justify-content-between">
                <ul class="navbar-nav flex-grow-1">
                    <li class="nav-item">
                        <a class="nav-link text-dark" asp-area="" asp-page="/Index">Home</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link text-dark" asp-area="" asp-page="/Persons">Person</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link text-dark" asp-area="" asp-page="/Privacy">Privacy</a>
                    </li>
                </ul>
            </div>
        </div>
    </nav>
</header>
<header>
    <nav class="navbar navbar-expand-sm navbar-toggleable-sm navbar-light bg-white border-bottom box-shadow mb-3">
        <div class="container">
            <a class="navbar-brand" asp-area="" asp-page="/Index">RazorPageSample</a>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target=".navbar-collapse" aria-controls="navbarSupportedContent"
                    aria-expanded="false" aria-label="Toggle navigation">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="navbar-collapse collapse d-sm-inline-flex justify-content-between">
                <ul class="navbar-nav flex-grow-1">
                    <li class="nav-item">
                        <a class="nav-link text-dark" asp-area="" asp-page="/Index">Home</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link text-dark" asp-area="" asp-page="/Persons">Person</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link text-dark" asp-area="" asp-page="/Privacy">Privacy</a>
                    </li>
                </ul>
            </div>
        </div>
    </nav>
</header>
HTML

Run the Project

This will show you how to run the project and generate a PDF document.

Execute ASP.NET Core Web App Project

Download ASP.NET Core Web App Project

You can download the complete code for this guide as a zipped file, which you can open in Visual Studio as an ASP.NET Core Web App project.

Download the RazorPageSample.zip ASP.NET Core Web App Project

Frequently Asked Questions

What are Razor Pages in ASP.NET Core used for?

Razor Pages are used in ASP.NET Core to organize code for web applications, allowing developers to combine C# and HTML efficiently for creating web content.

How do you convert Razor Pages to PDF documents in C#?

You can convert Razor Pages to PDF documents in C# using IronPDF's RenderRazorToPdf method, which leverages the ChromePdfRenderer class to generate PDFs from CSHTML files.

Which NuGet packages are essential for rendering Razor Pages to PDFs?

The essential NuGet packages for rendering Razor Pages to PDFs are IronPdf and IronPdf.Extensions.Razor.

How can you install the necessary packages for PDF conversion in ASP.NET Core?

You can install the necessary packages for PDF conversion by using the NuGet Package Manager with the command: Install-Package IronPdf.Extensions.Razor.

What role does a model class play in converting Razor Pages to PDFs?

A model class, such as 'Person', defines the data structure for the application, helping organize the information displayed on the Razor Page that will be converted to a PDF.

What method is used to render Razor Pages to PDF documents?

The RenderRazorToPdf method is used to render Razor Pages to PDF documents, utilizing IronPDF's ChromePdfRenderer class.

Can you enhance the PDF output when converting Razor Pages?

Yes, IronPDF allows you to enhance the PDF output with features such as page numbers, custom margins, and HTML headers and footers using RenderingOptions.

What are some advanced features available when generating PDFs with IronPDF?

Advanced features with IronPDF include exporting as PDFA or PDFUA, adding digital signatures, merging or splitting PDFs, rotating pages, and applying custom watermarks.

Where can you find the complete ASP.NET Core Web App project for practicing Razor Page to PDF conversion?

The complete ASP.NET Core Web App project for practicing Razor Page to PDF conversion can be downloaded as a zipped file from the provided link, ready for use in Visual Studio.

Chaknith Bin
Software Engineer
Chaknith works on IronXL and IronBarcode. He has deep expertise in C# and .NET, helping improve the software and support customers. His insights from user interactions contribute to better products, documentation, and overall experience.
Reviewed by
Jeff Fritz
Jeffrey T. Fritz
Principal Program Manager - .NET Community Team
Jeff is also a Principal Program Manager for the .NET and Visual Studio teams. He is the executive producer of the .NET Conf virtual conference series and hosts 'Fritz and Friends' a live stream for developers that airs twice weekly where he talks tech and writes code together with viewers. Jeff writes workshops, presentations, and plans content for the largest Microsoft developer events including Microsoft Build, Microsoft Ignite, .NET Conf, and the Microsoft MVP Summit