Cómo usar IronPDF con Blazor para la generación de PDF | IronPDF

IronPDF on Blazor Server App (HTML to PDF Tutorial)

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

IronPDF is supported with .NET 6 and includes project types like Blazor. Using Visual Studio, you can add IronPDF to your Blazor Server App project and use it as demonstrated in the following example:

Quickstart: Effortlessly Render PDFs in Blazor Server

Get started quickly with IronPDF in your Blazor Server applications. This example demonstrates how to render HTML content to a PDF with minimal setup. With just a few lines of code, transform your Blazor components into professional-looking PDFs. Ideal for developers looking to integrate PDF functionalities seamlessly into their Blazor projects.

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.

    IronPdf.HtmlToPdf.RenderHtmlAsPdf(htmlContent).SaveAs(outputPath);
  3. Deploy to test on your live environment

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

Create a new Blazor server project

Create a new project and select the type Blazor Server App.

Blazor Create Project Image

Install IronPDF into your Blazor project

After you have created the project, follow the next steps to install the IronPDF library from NuGet within Visual Studio.

  1. In the Solution Explorer window in Visual Studio, right-click References and choose Manage NuGet Packages.
  2. Select Browse and search for IronPdf.
  3. Select the latest version of the package, check the checkbox for your project, and click install.

Alternatively, you can use the .NET CLI to install it:

Install-Package IronPdf

Add New Razor Component

Once IronPDF is installed in your Blazor project, start by adding a new Razor Component. For this tutorial, we will name it "IronPdfComponent":

Blazor IronPDF Component Image

After that, update the code as follows:

@page "/IronPdf"
@inject IJSRuntime JS

<h3>IronPdfComponent</h3>

<EditForm Model="@_InputMsgModel" id="inputText">
  <div>
    <InputTextArea @bind-Value="@_InputMsgModel.HTML" rows="20" />
  </div>
  <div>
    <button type="button" @onclick="@SubmitHTML">Render HTML</button>
  </div>
</EditForm>
@page "/IronPdf"
@inject IJSRuntime JS

<h3>IronPdfComponent</h3>

<EditForm Model="@_InputMsgModel" id="inputText">
  <div>
    <InputTextArea @bind-Value="@_InputMsgModel.HTML" rows="20" />
  </div>
  <div>
    <button type="button" @onclick="@SubmitHTML">Render HTML</button>
  </div>
</EditForm>
HTML
@code {

    // Model to bind user input
    private InputHTMLModel _InputMsgModel = new InputHTMLModel();

    private async Task SubmitHTML()
    {
        // Set your IronPDF license key
        IronPdf.License.LicenseKey = "IRONPDF-MYLICENSE-KEY-1EF01";

        // Create a renderer to convert HTML to PDF
        var render = new IronPdf.ChromePdfRenderer();

        // Render the HTML input into a PDF document
        var doc = render.RenderHtmlAsPdf(_InputMsgModel.HTML);

        var fileName = "iron.pdf";

        // Create a stream reference for the PDF content
        using var streamRef = new DotNetStreamReference(stream: doc.Stream);

        // Invoke JavaScript function to download the PDF in the browser
        await JS.InvokeVoidAsync("SubmitHTML", fileName, streamRef);
    }

    public class InputHTMLModel
    {
        public string HTML { get; set; } = "My new message";
    }
}
@code {

    // Model to bind user input
    private InputHTMLModel _InputMsgModel = new InputHTMLModel();

    private async Task SubmitHTML()
    {
        // Set your IronPDF license key
        IronPdf.License.LicenseKey = "IRONPDF-MYLICENSE-KEY-1EF01";

        // Create a renderer to convert HTML to PDF
        var render = new IronPdf.ChromePdfRenderer();

        // Render the HTML input into a PDF document
        var doc = render.RenderHtmlAsPdf(_InputMsgModel.HTML);

        var fileName = "iron.pdf";

        // Create a stream reference for the PDF content
        using var streamRef = new DotNetStreamReference(stream: doc.Stream);

        // Invoke JavaScript function to download the PDF in the browser
        await JS.InvokeVoidAsync("SubmitHTML", fileName, streamRef);
    }

    public class InputHTMLModel
    {
        public string HTML { get; set; } = "My new message";
    }
}
code
If True Then

	' Model to bind user input
	private InputHTMLModel _InputMsgModel = New InputHTMLModel()

'INSTANT VB TODO TASK: Local functions are not converted by Instant VB:
'	private async Task SubmitHTML()
'	{
'		' Set your IronPDF license key
'		IronPdf.License.LicenseKey = "IRONPDF-MYLICENSE-KEY-1EF01";
'
'		' Create a renderer to convert HTML to PDF
'		var render = New IronPdf.ChromePdfRenderer();
'
'		' Render the HTML input into a PDF document
'		var doc = render.RenderHtmlAsPdf(_InputMsgModel.HTML);
'
'		var fileName = "iron.pdf";
'
'		' Create a stream reference for the PDF content
'		var streamRef = New DotNetStreamReference(stream: doc.Stream);
'
'		' Invoke JavaScript function to download the PDF in the browser
'		await JS.InvokeVoidAsync("SubmitHTML", fileName, streamRef);
'	}

'INSTANT VB TODO TASK: Local functions are not converted by Instant VB:
'	public class InputHTMLModel
'	{
'		public string HTML
'		{
'			get;
'			set;
'		} = "My new message";
'	}
End If
$vbLabelText   $csharpLabel

Add this JavaScript code to _layout.cshtml to allow downloading of the PDF rendered by IronPDF in the Blazor Application:

<script>
    // JavaScript function to download PDFs generated by IronPdf
    window.SubmitHTML = async (fileName, contentStreamReference) => {
        // Get the PDF content as an ArrayBuffer
        const arrayBuffer = await contentStreamReference.arrayBuffer();

        // Create a Blob from the ArrayBuffer
        const blob = new Blob([arrayBuffer]);

        // Create an object URL for the Blob
        const url = URL.createObjectURL(blob);

        // Create an anchor element to initiate the download
        const anchorElement = document.createElement("a");
        anchorElement.href = url;
        anchorElement.download = fileName ?? "download.pdf";

        // Programmatically click the anchor to start the download
        anchorElement.click();

        // Clean up by removing the anchor and revoking the object URL
        anchorElement.remove();
        URL.revokeObjectURL(url);
    };
</script>
<script>
    // JavaScript function to download PDFs generated by IronPdf
    window.SubmitHTML = async (fileName, contentStreamReference) => {
        // Get the PDF content as an ArrayBuffer
        const arrayBuffer = await contentStreamReference.arrayBuffer();

        // Create a Blob from the ArrayBuffer
        const blob = new Blob([arrayBuffer]);

        // Create an object URL for the Blob
        const url = URL.createObjectURL(blob);

        // Create an anchor element to initiate the download
        const anchorElement = document.createElement("a");
        anchorElement.href = url;
        anchorElement.download = fileName ?? "download.pdf";

        // Programmatically click the anchor to start the download
        anchorElement.click();

        // Clean up by removing the anchor and revoking the object URL
        anchorElement.remove();
        URL.revokeObjectURL(url);
    };
</script>
JAVASCRIPT

Edit the NavMenu.razor file in the Shared folder to include a navigation tab to our new Razor component. Add the following code:

<div class="nav-item px-3">
    <NavLink class="nav-link" href="IronPdf">
        <span class="oi oi-list-rich" aria-hidden="true"></span> IronPdf
    </NavLink>
</div>
<div class="nav-item px-3">
    <NavLink class="nav-link" href="IronPdf">
        <span class="oi oi-list-rich" aria-hidden="true"></span> IronPdf
    </NavLink>
</div>
HTML

Once this has all been applied, you can run your solution, and you should see this:

Blazor IronPDF Run Page Image

Preguntas Frecuentes

¿Cómo se integra una biblioteca PDF con una aplicación Blazor Server?

IronPDF permite la generación y manipulación de PDF en aplicaciones .NET, incluidas las aplicaciones Blazor Server. Se puede integrar usando Visual Studio y NuGet para la conversión de HTML a PDF.

¿Cómo instalo una biblioteca PDF en un proyecto Blazor?

Para instalar IronPDF en un proyecto Blazor, navegue al Explorador de Soluciones en Visual Studio, haga clic derecho en 'References', seleccione 'Manage NuGet Packages', busque 'IronPdf' e instálelo. Alternativamente, use la CLI de .NET con dotnet add package IronPdf.

¿Cuáles son los pasos para crear una nueva aplicación Blazor Server para una biblioteca PDF?

Para crear una nueva aplicación Blazor Server, abra Visual Studio, cree un nuevo proyecto y seleccione la plantilla de aplicación Blazor Server. Después de configurar su proyecto, integre IronPDF para manejar la generación de PDF.

¿Cómo puedo renderizar HTML a PDF en una aplicación Blazor usando una biblioteca PDF?

Después de instalar IronPDF, añada un nuevo Componente Razor, inyecte IJSRuntime y use IronPdf.ChromePdfRenderer para renderizar la entrada HTML en un documento PDF. Implemente funciones JavaScript en _layout.cshtml para descargar el PDF generado.

¿Cómo veo PDFs en una aplicación Blazor del lado del servidor?

Para ver PDFs en una aplicación Blazor del lado del servidor, convierta páginas web por URL en documentos PDF usando IronPDF, luego renderice estos PDFs en el navegador web del cliente.

¿Cuál es el papel de JavaScript en la descarga de PDFs en una aplicación Blazor?

JavaScript se utiliza para crear una función que descarga los PDFs generados por IronPDF. Convierte el contenido del PDF a un Blob y hace clic programáticamente en un elemento de anclaje para iniciar la descarga, asegurando que el PDF se guarde en el dispositivo del usuario.

¿Cómo agrego una pestaña de navegación para el componente PDF en una aplicación Blazor?

Para agregar una pestaña de navegación para el componente PDF, edite el archivo NavMenu.razor en la carpeta Shared e incluya un elemento NavLink que dirija a la ruta del PDF.

¿Qué es un Componente Razor en el contexto de Blazor y una biblioteca PDF?

Un Componente Razor en Blazor es una pieza reutilizable de UI definida en archivos .razor. En el contexto de IronPDF, se utiliza para manejar la interfaz de usuario y la lógica para convertir la entrada HTML en un PDF.

¿Cómo puedo solucionar problemas con la generación de PDF en Blazor?

Si encuentra problemas con la generación de PDF en Blazor, verifique que IronPDF esté instalado correctamente y que su entrada HTML sea válida. Asegúrese de que las funciones JavaScript estén configuradas correctamente para manejar las descargas de archivos.

¿Puedo convertir páginas web enteras a PDFs en aplicaciones Blazor?

Sí, IronPDF le permite convertir páginas web enteras a PDFs en aplicaciones Blazor utilizando la función de conversión de URL a PDF.

¿IronPDF es compatible con .NET 10 al crear aplicaciones Blazor?

Sí. IronPDF es totalmente compatible con .NET 10, con compatibilidad con su entorno de ejecución, ASP.NET Core y funciones de Blazor. Funciona de inmediato en proyectos .NET 10, beneficiándose de mejoras de rendimiento y funciones de lenguaje mejoradas. ([ironpdf.com](https://ironpdf.com/?utm_source=openai))

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
¿Listo para empezar?
Nuget Descargas 16,154,058 | Versión: 2025.11 recién lanzado