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.


Convert Razor view to PDF in one fluent line!

new IronPdf.ChromePdfRenderer().RenderRazorViewToPdf(HttpContext, "Views/Home/Example.cshtml", model).SaveAs("viewReport.pdf");
Install with NuGet
green arrow pointer

PM >  Install-Package IronPdf


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 is a Razor Page in ASP.NET Core?

A Razor Page is a file with a .cshtml extension that combines C# and HTML to generate web content. They are used in ASP.NET Core for organizing code for web applications, particularly for simple pages that are either read-only or require simple data input.

How can you convert Razor Pages to PDFs in an ASP.NET Core project?

You can use IronPDF to simplify the process of creating PDF files from Razor Pages within an ASP.NET Core Web App project, making PDF generation easy and direct.

What packages are needed to render Razor Pages to PDF documents?

To render Razor Pages to PDF documents, you need both the IronPdf and IronPdf.Extensions.Razor packages.

How do you install the necessary package for rendering Razor Pages to PDFs?

You can install the IronPdf.Extensions.Razor package using the NuGet Package Manager with the command: Install-Package IronPdf.Extensions.Razor.

What is the purpose of creating a model class like 'Person' in the project?

The model class 'Person' is used to define the data structure for individuals in the application, with properties for name, title, and description. This class serves as a model for the data displayed on the Razor Page.

How do you render a Razor Page to a PDF document?

To render a Razor Page to a PDF document, you use the ChromePdfRenderer class and the RenderRazorToPdf method provided by IronPDF, which converts the Razor Page into a PDF document.

Can you customize the PDF output when converting Razor Pages?

Yes, using IronPDF, you have full access to features available in RenderingOptions, such as applying page numbers, setting custom margins, and adding custom text or HTML headers and footers.

What additional features can be applied to the generated PDF document?

With IronPDF, you can export the PDF as PDFA or PDFUA, apply a digital signature, merge and split PDF documents, rotate pages, add annotations or bookmarks, and stamp custom watermarks onto your PDF.

How can you download the complete ASP.NET Core Web App project for this guide?

The complete code for this guide can be downloaded as a zipped file from the provided link, which you can open in Visual Studio as an ASP.NET Core Web App project.

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