Saltar al pie de página
USANDO IRONPDF

Cómo mostrar un PDF en Blazor (Guía)

Introducción

La funcionalidad de visualización de PDF en Blazor en aplicaciones web modernas requiere un componente de visor de PDF robusto que vaya más allá de las capacidades básicas del navegador. Para los desarrolladores de .NET que construyen aplicaciones Blazor, IronPDF proporciona una poderosa solución de visor de PDF que se integra perfectamente con tu app de Blazor Server. Esto te permite mostrar documentos PDF con alto rendimiento y rica funcionalidad sin depender de herramientas de navegador de terceros.

En este tutorial, exploraremos cómo implementar un visor de PDF en Blazor usando IronPDF, creando un componente de visor de PDF que pueda abrir archivos PDF, manejar contenido PDF y proporcionar a los usuarios una interfaz intuitiva para visualizar PDFs en computadoras de escritorio y teléfonos móviles.

Cómo empezar a visualizar archivos PDF con IronPDF

Antes de implementar tu visor de PDF en Blazor, necesitarás instalar IronPDF. Agrégalo a tu app de Blazor Server a través de NuGet:

Install-Package IronPdf

A continuación, crea una nueva aplicación Blazor y asegúrate de tener instalada la última versión de .NET Core. Almacena tus archivos PDF en la carpeta wwwroot para facilitar el acceso, o prepárate para cargarlos desde otras fuentes, como matrices de bytes o URLs.

Crear su primer componente visor de PDF Blazor

Vamos a construir un componente básico de visor de PDF en Blazor que pueda mostrar documentos PDF. Primero, crea un nuevo componente Razor:

@page "/pdfviewer"
@rendermode InteractiveServer
@using IronPdf
@inject IJSRuntime JSRuntime
@inject Microsoft.AspNetCore.Hosting.IWebHostEnvironment WebHostEnvironment
<h3>PDF Viewer Component</h3>
<div>
    <button @onclick="LoadPdfDocument">Open File</button>
    <div id="pdfContainer">
        @if (!string.IsNullOrEmpty(pdfUrl))
        {
            <iframe src="@pdfUrl" style="width:100%; height:600px;"></iframe>
        }
    </div>
</div>
@code {
    private string pdfUrl = "";
    private byte[] pdfData;
    private async Task LoadPdfDocument()
    {
        // Load PDF from file
        var pdfDocument = PdfDocument.FromFile("wwwroot/sample.pdf");
        pdfData = pdfDocument.BinaryData;
        // Create object URL for display
        pdfUrl = await CreateObjectUrl(pdfData);
    }
    private async Task<string> CreateObjectUrl(byte[] data)
    {
        var base64 = Convert.ToBase64String(data);
        return $"data:application/pdf;base64,{base64}";
    }
}
@page "/pdfviewer"
@rendermode InteractiveServer
@using IronPdf
@inject IJSRuntime JSRuntime
@inject Microsoft.AspNetCore.Hosting.IWebHostEnvironment WebHostEnvironment
<h3>PDF Viewer Component</h3>
<div>
    <button @onclick="LoadPdfDocument">Open File</button>
    <div id="pdfContainer">
        @if (!string.IsNullOrEmpty(pdfUrl))
        {
            <iframe src="@pdfUrl" style="width:100%; height:600px;"></iframe>
        }
    </div>
</div>
@code {
    private string pdfUrl = "";
    private byte[] pdfData;
    private async Task LoadPdfDocument()
    {
        // Load PDF from file
        var pdfDocument = PdfDocument.FromFile("wwwroot/sample.pdf");
        pdfData = pdfDocument.BinaryData;
        // Create object URL for display
        pdfUrl = await CreateObjectUrl(pdfData);
    }
    private async Task<string> CreateObjectUrl(byte[] data)
    {
        var base64 = Convert.ToBase64String(data);
        return $"data:application/pdf;base64,{base64}";
    }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

Este código crea un simple componente de visor de PDF que carga un documento PDF y lo muestra utilizando un iframe. El método LoadPdfDocument lee archivos PDF desde la misma ruta (carpeta wwwroot) y los convierte en una matriz de bytes. El método CreateObjectUrl luego transforma esta matriz de bytes en una URL de datos que el iframe puede mostrar, permitiendo así a los usuarios visualizar fácilmente el documento PDF cargado.

Resultado

Cómo Mostrar un PDF en Blazor (Guía): Figura 1

Implementación de la interoperabilidad de JavaScript para una visualización mejorada

Para un mejor control sobre la visualización del contenido PDF, podemos utilizar funciones de JavaScript para manejar la funcionalidad del visor de PDF:

@page "/pdf-jsinterop"
@rendermode InteractiveServer
@using IronPdf
@inject IJSRuntime JSRuntime
@inject Microsoft.AspNetCore.Hosting.IWebHostEnvironment WebHostEnvironment
<h3>IronPDF JavaScript Interop Viewer</h3>
<p>Displays PDF using JavaScript's Blob/ObjectURL capabilities.</p>
@if (!string.IsNullOrEmpty(ErrorMessage))
{
    <div class="alert alert-danger">Error: @ErrorMessage</div>
}
<div id="@documentId" style="border: 1px solid #ccc; width: 100%; min-height: 600px;">
    Loading PDF...
</div>
@code {
    private string documentId = Guid.NewGuid().ToString();
    private string ErrorMessage = string.Empty;
    private bool pdfLoaded = false;
    // Hold the reference to the loaded JavaScript module
    private IJSObjectReference? jsModule;
    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender && !pdfLoaded)
        {
            try
            {
                // 1. Asynchronously load the JavaScript file as a module
                // This guarantees the script is loaded before the next line executes.
                jsModule = await JSRuntime.InvokeAsync<IJSObjectReference>("import",
                    "./pdfViewerInterop.js");
                await LoadPdfWithJavaScript();
                pdfLoaded = true;
            }
            catch (Exception ex)
            {
                ErrorMessage = $"Failed to load JS module or execute: {ex.Message}";
            }
            finally
            {
                StateHasChanged();
            }
        }
    }
    private async Task LoadPdfWithJavaScript()
    {
        if (jsModule is null) return; // Should never happen if the module loads successfully
        try
        {
            var pdfPath = Path.Combine(WebHostEnvironment.WebRootPath, "sample.pdf");
            if (!File.Exists(pdfPath))
            {
                ErrorMessage = $"File not found: {pdfPath}";
                return;
            }
            var pdf = PdfDocument.FromFile(pdfPath);
            var stream = new MemoryStream(pdf.BinaryData);
            // 2. Invoke the function using the module reference
            // Note: We only pass the function name here.
            await jsModule.InvokeVoidAsync("displayPdf",
                documentId, stream.ToArray());
        }
        catch (Exception ex)
        {
            ErrorMessage = $"Failed to load PDF or invoke JS: {ex.Message}";
        }
    }
    // IMPORTANT: Dispose of the module when the component is removed
    public async ValueTask DisposeAsync()
    {
        if (jsModule is not null)
        {
            await jsModule.DisposeAsync();
        }
    }
}
@page "/pdf-jsinterop"
@rendermode InteractiveServer
@using IronPdf
@inject IJSRuntime JSRuntime
@inject Microsoft.AspNetCore.Hosting.IWebHostEnvironment WebHostEnvironment
<h3>IronPDF JavaScript Interop Viewer</h3>
<p>Displays PDF using JavaScript's Blob/ObjectURL capabilities.</p>
@if (!string.IsNullOrEmpty(ErrorMessage))
{
    <div class="alert alert-danger">Error: @ErrorMessage</div>
}
<div id="@documentId" style="border: 1px solid #ccc; width: 100%; min-height: 600px;">
    Loading PDF...
</div>
@code {
    private string documentId = Guid.NewGuid().ToString();
    private string ErrorMessage = string.Empty;
    private bool pdfLoaded = false;
    // Hold the reference to the loaded JavaScript module
    private IJSObjectReference? jsModule;
    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender && !pdfLoaded)
        {
            try
            {
                // 1. Asynchronously load the JavaScript file as a module
                // This guarantees the script is loaded before the next line executes.
                jsModule = await JSRuntime.InvokeAsync<IJSObjectReference>("import",
                    "./pdfViewerInterop.js");
                await LoadPdfWithJavaScript();
                pdfLoaded = true;
            }
            catch (Exception ex)
            {
                ErrorMessage = $"Failed to load JS module or execute: {ex.Message}";
            }
            finally
            {
                StateHasChanged();
            }
        }
    }
    private async Task LoadPdfWithJavaScript()
    {
        if (jsModule is null) return; // Should never happen if the module loads successfully
        try
        {
            var pdfPath = Path.Combine(WebHostEnvironment.WebRootPath, "sample.pdf");
            if (!File.Exists(pdfPath))
            {
                ErrorMessage = $"File not found: {pdfPath}";
                return;
            }
            var pdf = PdfDocument.FromFile(pdfPath);
            var stream = new MemoryStream(pdf.BinaryData);
            // 2. Invoke the function using the module reference
            // Note: We only pass the function name here.
            await jsModule.InvokeVoidAsync("displayPdf",
                documentId, stream.ToArray());
        }
        catch (Exception ex)
        {
            ErrorMessage = $"Failed to load PDF or invoke JS: {ex.Message}";
        }
    }
    // IMPORTANT: Dispose of the module when the component is removed
    public async ValueTask DisposeAsync()
    {
        if (jsModule is not null)
        {
            await jsModule.DisposeAsync();
        }
    }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

Agrega esta función de JavaScript a tu archivo JavaScript en la carpeta wwwroot:

export function displayPdf(elementId, data) {
    // 1. Create a Blob from the byte array data
    const blob = new Blob([new Uint8Array(data)],
        { type: 'application/pdf' });
    // 2. Create a temporary URL for the Blob
    const url = URL.createObjectURL(blob);
    // 3. Find the container element
    const container = document.getElementById(elementId);
    if (!container) return;
    // 4. Clear any previous content
    container.innerHTML = '';
    // 5. Create and configure the iframe
    const iframe = document.createElement('iframe');
    iframe.src = url;
    iframe.style.width = '100%';
    iframe.style.height = '600px';
    iframe.style.border = 'none';
    // 6. Append the iframe to the container
    container.appendChild(iframe);
}
export function displayPdf(elementId, data) {
    // 1. Create a Blob from the byte array data
    const blob = new Blob([new Uint8Array(data)],
        { type: 'application/pdf' });
    // 2. Create a temporary URL for the Blob
    const url = URL.createObjectURL(blob);
    // 3. Find the container element
    const container = document.getElementById(elementId);
    if (!container) return;
    // 4. Clear any previous content
    container.innerHTML = '';
    // 5. Create and configure the iframe
    const iframe = document.createElement('iframe');
    iframe.src = url;
    iframe.style.width = '100%';
    iframe.style.height = '600px';
    iframe.style.border = 'none';
    // 6. Append the iframe to the container
    container.appendChild(iframe);
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

Esta función de JavaScript crea un blob a partir de los datos del PDF y genera una URL de objeto. Luego crea un elemento iframe dinámicamente y lo añade al contenedor. Este enfoque te da más control sobre cómo se muestran las páginas PDF y permite una mejor gestión del ciclo de vida del componente del visor de PDF.

Resultado

Cómo Mostrar un PDF en Blazor (Guía): Figura 2 - Visor de PDF con JavaScript

Carga de archivos PDF desde diferentes fuentes

Tu visor de PDF en Blazor puede recuperar y mostrar documentos PDF desde varias fuentes:

private async Task LoadFromUrl()
{
    var client = new HttpClient();
    var response = await client.GetAsync("https://example.com/file.pdf");
    var stream = await response.Content.ReadAsStreamAsync();
    var pdfDocument = new PdfDocument(stream);
    await DisplayPdfContent(pdfDocument);
}
private async Task LoadFromHtmlContent()
{
    var renderer = new ChromePdfRenderer();
    var htmlContent = "<h1>Generated PDF</h1>";
    var pdfDocument = renderer.RenderHtmlAsPdf(htmlContent);
    await DisplayPdfContent(pdfDocument);
}
private async Task DisplayPdfContent(PdfDocument document)
{
    var data = document.BinaryData;
    pdfUrl = $"data:application/pdf;base64,{Convert.ToBase64String(data)}";
}
private async Task LoadFromUrl()
{
    var client = new HttpClient();
    var response = await client.GetAsync("https://example.com/file.pdf");
    var stream = await response.Content.ReadAsStreamAsync();
    var pdfDocument = new PdfDocument(stream);
    await DisplayPdfContent(pdfDocument);
}
private async Task LoadFromHtmlContent()
{
    var renderer = new ChromePdfRenderer();
    var htmlContent = "<h1>Generated PDF</h1>";
    var pdfDocument = renderer.RenderHtmlAsPdf(htmlContent);
    await DisplayPdfContent(pdfDocument);
}
private async Task DisplayPdfContent(PdfDocument document)
{
    var data = document.BinaryData;
    pdfUrl = $"data:application/pdf;base64,{Convert.ToBase64String(data)}";
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

Estos métodos demuestran la carga de archivos PDF desde URLs utilizando HTTPS, la conversión de contenido HTML a PDF y la visualización del contenido PDF resultante. El método LoadFromUrl recupera documentos PDF desde ubicaciones remotas, mientras que LoadFromHtmlContent muestra cómo convertir HTML a PDF sobre la marcha, proporcionando flexibilidad en cómo tu componente visor de PDF en Blazor obtiene su contenido.

Salida mediante contenido HTML

Cómo Mostrar un PDF en Blazor (Guía): Figura 3 - PDF Generado desde HTML y mostrado

Añadir funciones interactivas

Mejora tu visor de PDF con funcionalidad interactiva:

@code {
    private int currentPage = 1;
    private int totalPages;
    private string rotationClass = "";
    private async Task NavigateToPage(int page)
    {
        currentPage = page;
        await JSRuntime.InvokeVoidAsync("navigateTo", page);
    }
    private void RotateCounterclockwise()
    {
        // Counterclockwise switch orientation
        rotationClass = "rotate-270";
    }
    private async Task PrintPdf()
    {
        await JSRuntime.InvokeVoidAsync("printDocument", documentId);
    }
    private async Task DownloadPdf()
    {
        var fileName = "document.pdf";
        await JSRuntime.InvokeVoidAsync("downloadFile", 
           pdfData, fileName);
    }
}
@code {
    private int currentPage = 1;
    private int totalPages;
    private string rotationClass = "";
    private async Task NavigateToPage(int page)
    {
        currentPage = page;
        await JSRuntime.InvokeVoidAsync("navigateTo", page);
    }
    private void RotateCounterclockwise()
    {
        // Counterclockwise switch orientation
        rotationClass = "rotate-270";
    }
    private async Task PrintPdf()
    {
        await JSRuntime.InvokeVoidAsync("printDocument", documentId);
    }
    private async Task DownloadPdf()
    {
        var fileName = "document.pdf";
        await JSRuntime.InvokeVoidAsync("downloadFile", 
           pdfData, fileName);
    }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

Este código agrega navegación entre páginas PDF, funcionalidad de rotación (incluido el cambio de orientación al sentido contrario a las agujas del reloj) y la capacidad de imprimir PDFs. La funcionalidad de descarga permite a los usuarios guardar archivos PDF localmente. Estas características transforman tu visor de PDF básico en un visor de PDF poderoso con una barra de herramientas incluida que proporciona funcionalidad esencial para los usuarios que trabajan con documentos PDF.

Resultado

Cómo Mostrar un PDF en Blazor (Guía): Figura 4 - Visor de PDF con características interactivas personalizadas

Cómo rellenar formularios y anotaciones en PDF

Para documentos PDF con campos de formulario y anotaciones, IronPDF proporciona un soporte robusto:

private async Task ProcessFormFields(
{
    var pdfDocument = PdfDocument.FromFile("form.pdf");
    foreach (var field in pdfDocument.Form.Fields)
    {
        if (field.Type == PdfFormFieldType.Text)
        {
            field.Value = "User Input";
        }
    }
    // Enable form filling in viewer
    var modifiedPdf = pdfDocument.BinaryData;
    await DisplayPdfContent(pdfDocument);
}
private async Task ProcessFormFields(
{
    var pdfDocument = PdfDocument.FromFile("form.pdf");
    foreach (var field in pdfDocument.Form.Fields)
    {
        if (field.Type == PdfFormFieldType.Text)
        {
            field.Value = "User Input";
        }
    }
    // Enable form filling in viewer
    var modifiedPdf = pdfDocument.BinaryData;
    await DisplayPdfContent(pdfDocument);
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

Esto habilita capacidades de relleno de formularios dentro de tu componente visor de PDF en Blazor, permitiendo a los usuarios interactuar con campos de formularios directamente en el navegador. El código itera a través de los campos de formulario en el documento PDF y puede establecer valores programáticamente, siendo ideal para aplicaciones que requieren rellenado de formularios dinámico.

Resultado

Cómo Mostrar un PDF en Blazor (Guía): Figura 5 - Mostrar PDF con Rellenado de Formularios

Optimización del rendimiento

Para asegurar un alto rendimiento al mostrar PDFs, especialmente para archivos PDF grandes:

private async Task LoadLargePdf()
{
    const int chunkSize = 1024 * 1024; // 1MB chunks
    var pdfPath = "largefile.pdf";
    using (var fileStream = File.OpenRead(pdfPath))
    {
        var buffer = new byte[chunkSize];
        var chunks = new List<byte[]>();
        int bytesRead;
        while ((bytesRead = await fileStream.ReadAsync(buffer)) > 0)
        {
            var chunk = new byte[bytesRead];
            Array.Copy(buffer, chunk, bytesRead);
            chunks.Add(chunk);
        }
        // Process chunks for display
        await ProcessPdfChunks(chunks);
    }
}
private async Task LoadLargePdf()
{
    const int chunkSize = 1024 * 1024; // 1MB chunks
    var pdfPath = "largefile.pdf";
    using (var fileStream = File.OpenRead(pdfPath))
    {
        var buffer = new byte[chunkSize];
        var chunks = new List<byte[]>();
        int bytesRead;
        while ((bytesRead = await fileStream.ReadAsync(buffer)) > 0)
        {
            var chunk = new byte[bytesRead];
            Array.Copy(buffer, chunk, bytesRead);
            chunks.Add(chunk);
        }
        // Process chunks for display
        await ProcessPdfChunks(chunks);
    }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

Este enfoque carga archivos PDF grandes en trozos, evitando problemas de memoria y asegurando un rendimiento suave incluso con documentos PDF sustanciales. Es particularmente útil cuando se trata de archivos PDF en teléfonos móviles o dispositivos con recursos limitados.

Consideraciones de seguridad para su aplicación Blazor

Al trabajar con archivos PDF protegidos con contraseña:

private async Task LoadSecurePdf(string password)
{
    var pdfDocument = PdfDocument.FromFile("secure.pdf", password);
    if (pdfDocument != null)
    {
       var headers = new Dictionary<string, string>
        {
            {"X-Frame-Options", "SAMEORIGIN"},
            {"Content-Security-Policy", "default-src 'self'"}
        };
        await DisplayPdfContent(pdfDocument);
    }
}
private async Task LoadSecurePdf(string password)
{
    var pdfDocument = PdfDocument.FromFile("secure.pdf", password);
    if (pdfDocument != null)
    {
       var headers = new Dictionary<string, string>
        {
            {"X-Frame-Options", "SAMEORIGIN"},
            {"Content-Security-Policy", "default-src 'self'"}
        };
        await DisplayPdfContent(pdfDocument);
    }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

Este código demuestra la carga de documentos PDF protegidos con contraseña mientras se mantiene la seguridad a través de la configuración adecuada de encabezados.

Conclusión

Implementar un visor de PDF en Blazor con IronPDF proporciona a los desarrolladores una solución integral para mostrar PDFs en aplicaciones web. Desde la visualización básica hasta características avanzadas como el relleno de formularios y anotaciones, el componente de visor de PDF de IronPDF ofrece la funcionalidad necesaria para aplicaciones profesionales.

Los ejemplos mostrados demuestran cómo crear un visor de PDF en Blazor robusto que pueda manejar diversas fuentes de PDF, proporcionar características interactivas y mantener un alto rendimiento. Ya sea que estés construyendo un visor de documentos simple o un sistema complejo de gestión de documentos, la integración de IronPDF con apps de Blazor Server hace que sea fácil implementar capacidades de visualización de PDF profesionales.

¿Listo para implementar tu propio visor de PDF? Empieza tu prueba gratuita de IronPDF hoy y accede a documentación completa, aplicaciones de demostración y soporte para desarrolladores para crear experiencias de visualización de PDF poderosas en tus aplicaciones Blazor.

Preguntas Frecuentes

¿Cómo puedo mostrar un PDF en una aplicación Blazor usando IronPDF?

IronPDF proporciona una API integral que le permite renderizar y mostrar PDFs dentro de aplicaciones Blazor. Al integrar IronPDF, puede implementar fácilmente un componente potente de visor de PDF.

¿Cuáles son los beneficios de usar IronPDF para visualizar PDFs en Blazor?

Usar IronPDF para visualizar PDFs en Blazor ofrece beneficios como el manejo de campos de formulario, la creación de visores interactivos y la renderización de PDFs de alta calidad sin problemas dentro de su aplicación.

¿Es posible manejar campos de formulario en PDFs usando IronPDF en Blazor?

Sí, IronPDF le permite manejar y manipular campos de formulario dentro de documentos PDF en una aplicación Blazor, ofreciendo mayor interactividad y participación del usuario.

¿Puede usar IronPDF para crear visores interactivos de PDF en Blazor?

Absolutamente. IronPDF proporciona herramientas para crear visores interactivos de PDF en Blazor, habilitando características como el manejo de formularios y la visualización de contenido dinámico.

¿Qué características ofrece IronPDF para la manipulación de PDF en Blazor?

IronPDF ofrece características como renderización de PDF, manejo de campos de formulario, extracción de texto y manipulación de páginas, lo que lo convierte en una opción versátil para operaciones de PDF en Blazor.

¿Cómo mejora IronPDF las experiencias de visualización de PDF en aplicaciones Blazor?

IronPDF mejora la experiencia de visualización de PDF en aplicaciones Blazor al proporcionar una renderización fluida, características interactivas y un manejo robusto de documentos PDF.

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