Cómo convertir páginas Razor a PDFs en ASP .NET Core Web App

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

This article was translated from English: Does it need improvement?
Translated
View the article in English

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.

Quickstart: Convert Razor Pages to PDF in Seconds

Leverage the power of IronPDF to quickly convert your Razor Pages into high-quality PDFs in an ASP.NET Core application. By using the RenderRazorToPdf method, you can seamlessly transform CSHTML files into PDF documents, optimizing your workflow and enhancing document distribution. This guide will walk you through the simple steps needed to achieve this in minutes, ensuring a smooth and efficient process for developers.

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.

    // Install-Package IronPdf.Extensions.Razor
    var pdf = new IronPdf.ChromePdfRenderer().RenderRazorToPdf("Views/Home/Index.cshtml");
  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

Preguntas Frecuentes

¿Para qué se usan las páginas Razor en ASP.NET Core?

Las páginas Razor se usan en ASP.NET Core para organizar el código de aplicaciones web, permitiendo a los desarrolladores combinar C# y HTML de manera eficiente para crear contenido web.

¿Cómo se convierten las páginas Razor a documentos PDF en C#?

Puedes convertir páginas Razor a documentos PDF en C# usando el método RenderRazorToPdf de IronPDF, que utiliza la clase ChromePdfRenderer para generar PDFs desde archivos CSHTML.

¿Qué paquetes NuGet son esenciales para renderizar páginas Razor a PDFs?

Los paquetes NuGet esenciales para renderizar páginas Razor a PDFs son IronPdf e IronPdf.Extensions.Razor.

¿Cómo puedes instalar los paquetes necesarios para la conversión a PDF en ASP.NET Core?

Puedes instalar los paquetes necesarios para la conversión a PDF utilizando el Administrador de Paquetes NuGet con el comando: Install-Package IronPdf.Extensions.Razor.

¿Qué papel juega una clase de modelo en la conversión de páginas Razor a PDFs?

Una clase de modelo, como 'Person', define la estructura de datos para la aplicación, ayudando a organizar la información que se muestra en la página Razor que será convertida a PDF.

¿Qué método se usa para renderizar páginas Razor a documentos PDF?

El método RenderRazorToPdf se usa para renderizar páginas Razor a documentos PDF, utilizando la clase ChromePdfRenderer de IronPDF.

¿Puedes mejorar la salida de PDF al convertir páginas Razor?

Sí, IronPDF te permite mejorar la salida de PDF con características como números de página, márgenes personalizados y encabezados y pies de página HTML usando RenderingOptions.

¿Cuáles son algunas características avanzadas disponibles al generar PDFs con IronPDF?

Las características avanzadas con IronPDF incluyen exportación como PDFA o PDFUA, añadir firmas digitales, fusionar o dividir PDFs, rotar páginas y aplicar marcas de agua personalizadas.

¿Dónde puedes encontrar el proyecto completo de la aplicación web ASP.NET Core para practicar la conversión de página Razor a PDF?

El proyecto completo de la aplicación web ASP.NET Core para practicar la conversión de página Razor a PDF se puede descargar como un archivo comprimido desde el enlace proporcionado, listo para usar en Visual Studio.

¿IronPDF es compatible con .NET 10 al convertir vistas CSHTML o Razor a PDF?

Sí. IronPDF es totalmente compatible con .NET 10 para convertir vistas CSHTML/Razor a PDF. Sus proyectos pueden ejecutarse en .NET 10 sin necesidad de configuración adicional: funciones como RenderRazorToPdf , ChromePdfRenderer y la generación asincrónica de PDF funcionan correctamente.

Curtis Chau
Escritor Técnico

Curtis Chau tiene una licenciatura en Ciencias de la Computación (Carleton University) y se especializa en el desarrollo front-end con experiencia en Node.js, TypeScript, JavaScript y React. Apasionado por crear interfaces de usuario intuitivas y estéticamente agradables, disfruta trabajando con frameworks modernos y creando manuales bien ...

Leer más
Revisado por
Jeff Fritz
Jeffrey T. Fritz
Gerente Principal de Programas - Equipo de la Comunidad .NET
Jeff también es Gerente Principal de Programas para los equipos de .NET y Visual Studio. Es el productor ejecutivo de la serie de conferencias virtuales .NET Conf y anfitrión de 'Fritz and Friends', una transmisión en vivo para desarrolladores que se emite dos veces a la semana donde habla sobre tecnología y escribe código junto con la audiencia. Jeff escribe talleres, presentaciones, y planifica contenido para los eventos de desarrolladores más importantes de Microsoft, incluyendo Microsoft Build, Microsoft Ignite, .NET Conf y la Cumbre de Microsoft MVP.
¿Listo para empezar?
Nuget Descargas 16,154,058 | Versión: 2025.11 recién lanzado