How to Convert Razor to PDF in Blazor Server

A Razor component is a user interface element, such as a page, dialog, or data entry form, built using C# and Razor syntax. It serves as a reusable piece of UI.

Blazor Server is a web framework that allows you to build interactive web UIs using C# instead of JavaScript. In this framework, the logic for components runs on the server.

IronPDF enables you to generate PDF documents from Razor components in a Blazor Server project or application. This makes the creation of PDF files/pages straightforward in Blazor Server.

IronPDF Extension Package

The IronPdf.Extensions.Blazor package is an extension of the main IronPdf package. Both the IronPdf.Extensions.Blazor and IronPdf packages are needed to render Razor components to PDF documents in a Blazor Server App.

Install-Package IronPdf.Extensions.Blazor
C# NuGet Library for PDF

Install with NuGet

Install-Package IronPdf.Extensions.Blazor

Render Razor Components to PDFs

A Blazor Server App project is required to convert Razor components to PDFs.

Add a Model Class

Add a standard C# class and name it PersonInfo. This class will serve as the model for storing person information. Insert the following code:

:path=/static-assets/pdf/content-code-examples/how-to/razor-to-pdf-blazor-server-model.cs
namespace BlazorSample.Data
{
    public class PersonInfo
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Title { get; set; }
        public string Description { get; set; }
    }
}
Namespace BlazorSample.Data
	Public Class PersonInfo
		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 Component

Use the RenderRazorComponentToPdf method to convert Razor components into PDFs. Access this method by instantiating the ChromePdfRenderer class. The method returns a PdfDocument object, which allows you to either export the PDF document or modify it further.

The returned PdfDocument can undergo additional modifications, such as conversion to PDF/A or PDF/UA formats. You can also merge or split the PDF document, rotate its pages, and add annotations or bookmarks. Custom watermarks can also be stamped onto your PDF.

Add a Razor component and name it Person.razor. Input the following code:

@page "/Person"
@using BlazorSample.Data;
@using IronPdf;
@using IronPdf.Extensions.Blazor;

<h3>Person</h3>

@code {
    // A parameter to receive a list of persons from the parent component.
    [Parameter]
    public IEnumerable<PersonInfo> persons { get; set; }

    // Dictionary to hold parameters that will be passed to the PDF renderer.
    public Dictionary<string, object> Parameters { get; set; } = new Dictionary<string, object>();

    protected override async Task OnInitializedAsync()
    {
        // Initialize the persons list with some sample data.
        persons = new List<PersonInfo>
        {
            new PersonInfo { Name = "Alice", Title = "Mrs.", Description = "Software Engineer" },
            new PersonInfo { Name = "Bob", Title = "Mr.", Description = "Software Engineer" },
            new PersonInfo { Name = "Charlie", Title = "Mr.", Description = "Software Engineer" }
        };
    }

    private async void PrintToPdf()
    {
        ChromePdfRenderer renderer = new ChromePdfRenderer();

        // Apply text footer to the PDF pages.
        renderer.RenderingOptions.TextFooter = new TextHeaderFooter()
        {
            LeftText = "{date} - {time}",
            DrawDividerLine = true,
            RightText = "Page {page} of {total-pages}",
            Font = IronSoftware.Drawing.FontTypes.Arial,
            FontSize = 11
        };

        Parameters.Add("persons", persons);

        // Render Razor component to PDF and save it.
        PdfDocument pdf = renderer.RenderRazorComponentToPdf<Person>(Parameters);
        File.WriteAllBytes("razorComponentToPdf.pdf", pdf.BinaryData);
    }
}

<table class="table">
    <tr>
        <th>Name</th>
        <th>Title</th>
        <th>Description</th>
    </tr>
    @foreach (var person in persons)
    {
        <tr>
            <td>@person.Name</td>
            <td>@person.Title</td>
            <td>@person.Description</td>
        </tr>
    }
</table>

<button class="btn btn-primary" @onclick="PrintToPdf">Print to Pdf</button>

Moreover, using this method to generate a PDF grants you complete access to all features in RenderingOptions. This includes the ability to insert text, as well as HTML headers and footers. Additionally, you can add page numbers and adjust the page dimensions and layout to your liking.

Add a Section to the Left Menu

  • Navigate to the "Shared folder" and open NavMenu.razor.
  • Add the section that will open our Razor component, Person. Our Person component will be the second option.
<div class="@NavMenuCssClass" @onclick="ToggleNavMenu">
    <nav class="flex-column">
        <div class="nav-item px-3">
            <NavLink class="nav-link" href="" Match="NavLinkMatch.All">
                <span class="oi oi-home" aria-hidden="true"></span> Home
            </NavLink>
        </div>
        <div class="nav-item px-3">
            <NavLink class="nav-link" href="Person">
                <span class="oi oi-list-rich" aria-hidden="true"></span> Person
            </NavLink>
        </div>
        <div class="nav-item px-3">
            <NavLink class="nav-link" href="counter">
                <span class="oi oi-plus" aria-hidden="true"></span> Counter
            </NavLink>
        </div>
        <div class="nav-item px-3">
            <NavLink class="nav-link" href="fetchdata">
                <span class="oi oi-list-rich" aria-hidden="true"></span> Fetch data
            </NavLink>
        </div>
    </nav>
</div>

Run the Project

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

Execute Blazor Server Project

Download Blazor Server App Project

You can download the complete code for this guide. It comes as a zipped file that you can open in Visual Studio as a Blazor Server App project.

Download the Blazor Sample Project for Razor to PDF Conversion

Ready to see what else you can do? Check out our tutorial page here: Convert PDFs

Frequently Asked Questions

How can you convert Razor components to PDF in a Blazor Server project?

You can use the `RenderRazorComponentToPdf` method from IronPDF to convert Razor components to PDF documents in a Blazor Server project.

What are the key steps to set up PDF generation from Razor components?

The key steps include downloading the IronPDF library from NuGet, adding a model class for data, creating a Razor component, and using the `RenderRazorComponentToPdf` method for conversion.

Why do you need the IronPdf.Extensions.Blazor package?

The IronPdf.Extensions.Blazor package is necessary for rendering Razor components to PDF documents in a Blazor Server application.

How do you install IronPdf.Extensions.Blazor in a Blazor Server project?

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

What functionality does the `RenderRazorComponentToPdf` method provide?

The `RenderRazorComponentToPdf` method converts Razor components into PDF documents, allowing for further modifications like adding annotations or bookmarks.

What options are available for customizing PDF documents in Blazor Server?

Customization options include inserting text, adding HTML headers and footers, page numbers, and adjusting page dimensions using RenderingOptions in IronPDF.

How can you integrate a Razor component into a Blazor Server App's left menu?

To add a Razor component to the left menu, navigate to the Shared folder, open NavMenu.razor, and add a section with a NavLink to your component.

Where can you find a sample project for converting Razor components to PDF?

A complete sample project code can be downloaded as a zipped file from the IronPDF website and opened in Visual Studio as a Blazor Server App project.

What is the role of a model class in Razor component PDF conversion?

A model class, such as `PersonInfo`, holds the data to be displayed in the Razor component and is crucial for dynamic content generation in PDFs.

What are the benefits of using Razor components in Blazor Server?

Razor components allow for reusable UI elements built with C# and Razor syntax, enabling interactive web UIs with server-side logic.

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.