Saltar al pie de página
USANDO IRONPDF

Cómo Mostrar PDF Desde un Array de Bytes en Blazor

1. Introduction

IronPDF for C# PDF Solutions and Documentation is a C# PDF library that supports handling PDF rendering and converting byte arrays to PDF files. It also supports reviewing and printing PDFs as well as annotating PDFs with annotation tools. Adding headers and footers and merging multiple PDFs is also very convenient using IronPDF.

IronPDF can be used with Blazor PDF viewer to create a PDF viewer, and it can handle larger file sizes by creating an object URL that the browser can display.

Using IronPDF with Blazor, developers can create a PDF viewer that can display PDF files from byte arrays or from a file name, and it also supports uploading files and handling file downloads. IronPDF also provides a method to handle the paging of PDF documents, which works fine with Blazor.

In addition, IronPDF provides code examples to convert byte arrays to PDF documents, download PDF files, and display PDFs from a base64 string. Developers can also convert PDF files to other file formats, such as transforming images to PDF documents.

IronPDF can be used with a Blazor server app and can be integrated with Visual Studio to provide a seamless development experience. With IronPDF, developers can create a professional-grade UI component that can be used to build modern, feature-rich Web Applications.

This article explains how developers can use IronPDF to convert PDF byte arrays to PDF documents and display them in a Blazor PDF viewer.

2. Requirements

To follow along with the tutorial, the following tools and requirements are needed:

  • Visual Studio 2019 or later: This is required to create and run the Blazor application. It can be downloaded from the Visual Studio official website
  • .NET 5.0 or later: This is required to build and run the Blazor application. It can be downloaded from the official .NET download page
  • IronPDF: This is the professional-grade UI library that will be used to convert PDF byte arrays to a PDF document and display it in the Blazor PDF viewer. It can be downloaded from the IronPDF official website
  • IronPDF.Blazor NuGet package: This is the NuGet package that will be used to integrate IronPDF with the Blazor application. It can be installed from the NuGet Package Manager within Visual Studio.

Some features discussed in the tutorial may require a paid version of IronPDF. Additionally, the tutorial assumes a basic understanding of Blazor and C#.

3. Creating a Blazor Application

We must create a new Visual Studio project before we can start building our first Blazor app.

  • Open Visual Studio.
  • Click on "Create a New Project".
  • Choose the Blazor Server App Template.

    How to Display PDF From Byte Array in Blazor, Figure 1: Creating a New Project in Visual Studio Creating a New Project in Visual Studio

  • Select the "Next" option.
  • Name your application.

    How to Display PDF From Byte Array in Blazor, Figure 2: Naming the New Project in Visual Studio Naming the New Project in Visual Studio

  • Select the "Next" option.
  • Select a .NET Framework.

    How to Display PDF From Byte Array in Blazor, Figure 3: Choosing the .NET 6.0 Framework for the New Blazor Server App Choosing the .NET 6.0 Framework for the New Blazor Server App

  • Click on the Create button.
  • A new project will be created, as seen below.

    How to Display PDF From Byte Array in Blazor, Figure 4: Initial Project View in Visual Studio Initial Project View in Visual Studio

Several files were produced to give you a straightforward Blazor software that is ready to use.

  • The entry point for the app that launches the server is program.cs, which is also where you set up the middleware and services for the app.
  • The main part of the application is called "App.razor".
  • Some sample web pages for the app can be found in the "Pages" directory.
  • Different profile settings for the local development environment are defined in the "launchSettings.json" file located in the "Properties" directory. When a project is created, a port number is automatically assigned and saved to this file.

Start the template program.

Blazor Project Types

Blazor supports two project types: Blazor Server and Blazor WebAssembly.

The former type runs on the server and uses SignalR to communicate with the browser. This means that the application's UI is rendered on the server, and the browser only receives updates from the server. Blazor Server has the advantage of being able to support larger applications and can easily handle more users.

Blazor WebAssembly applications, on the other hand, run entirely in the browser and do not require a server to function. This makes them more lightweight and faster to load, but they have a few limitations, such as not being able to support larger files.

For this tutorial, it is recommended to use a Blazor Server application since it can support displaying and handling PDF files, which may be larger. Additionally, Blazor Server can support reviewing and printing PDFs, which may be a useful feature for a PDF viewer application.

Installing IronPDF

In this section, we will discuss how to install IronPDF using different methods.

Using the Command Line

Navigate to Tools > NuGet Package Manager > Package Manager Console in Visual Studio.

Enter the following line into the terminal tab of the package manager:

Install-Package IronPdf

Now that the package has been downloaded, it will be installed in the current project.

How to Display PDF From Byte Array in Blazor, Figure 5: Package Manager Console UI Package Manager Console UI

Using Manage NuGet Packages for Solutions

The NuGet Package Manager UI is available in Visual Studio to install the package directly into the project. The below screenshot shows how to open it.

How to Display PDF From Byte Array in Blazor, Figure 6: Navigate to NuGet Package Manager Navigate to NuGet Package Manager

The Package Manager UI provides a Browse feature that displays a list of the package libraries that are offered on the NuGet website. Enter the "IronPDF" keyword, as in the below screenshot, to find the IronPDF package.

How to Display PDF From Byte Array in Blazor, Figure 7: Search and install the IronPDF package in NuGet Package Manager UI Search and install the IronPDF package in NuGet Package Manager UI

Locate the IronPDF library in NuGet Package Manager by searching for it in the Browse section.

Select the IronPDF package and click the "Install" button to add it to the project.

4. Creating and Displaying PDFs from Byte Array

To generate PDF byte arrays using IronPDF in a Blazor application, you first need to add the IronPDF dependency to your project.

Once you have added the IronPDF dependency to your Blazor application, you can create a PDF document using the following code:

// Placeholder for the URL used to generate the PDF
string _url = "";

// Method to render a URL as a PDF and convert the result to a base64 string
private async Task ViewFile()
{
    var renderer = new IronPdf.ChromePdfRenderer();

    // Render the specified URL as a PDF
    var pdf = renderer.RenderUrlAsPdf("https://localhost:7018/fetchdata");

    // Convert the PDF stream to a base64 string
    _url = $"data:application/pdf;base64,{Convert.ToBase64String(pdf.Stream.ToArray())}";
}
// Placeholder for the URL used to generate the PDF
string _url = "";

// Method to render a URL as a PDF and convert the result to a base64 string
private async Task ViewFile()
{
    var renderer = new IronPdf.ChromePdfRenderer();

    // Render the specified URL as a PDF
    var pdf = renderer.RenderUrlAsPdf("https://localhost:7018/fetchdata");

    // Convert the PDF stream to a base64 string
    _url = $"data:application/pdf;base64,{Convert.ToBase64String(pdf.Stream.ToArray())}";
}
' Placeholder for the URL used to generate the PDF
Private _url As String = ""

' Method to render a URL as a PDF and convert the result to a base64 string
Private Async Function ViewFile() As Task
	Dim renderer = New IronPdf.ChromePdfRenderer()

	' Render the specified URL as a PDF
	Dim pdf = renderer.RenderUrlAsPdf("https://localhost:7018/fetchdata")

	' Convert the PDF stream to a base64 string
	_url = $"data:application/pdf;base64,{Convert.ToBase64String(pdf.Stream.ToArray())}"
End Function
$vbLabelText   $csharpLabel

The aforementioned code snippet makes use of IronPDF's RenderUrlAsPdf method, which downloads the HTML text from a specified URL and converts it into a PDF format. The resulting PDF material is then rendered as a string of unprocessed base64 data by converting the PDF stream to a base64 format and storing it in a local variable.

Applications can save created PDF files on the server's file system for later access by using IronPDF's SaveAs function, which is accessible on every ChromePdfRenderer instance.

The base64 PDF data is prepared for output onto the client's browser in the next section of the code:

@if (_url != string.Empty)
{
    // Render the PDF base64 data as a PDF in an iframe
    <iframe src="@_url" width="100%" height="500px"></iframe>
}
@if (_url != string.Empty)
{
    // Render the PDF base64 data as a PDF in an iframe
    <iframe src="@_url" width="100%" height="500px"></iframe>
}
'INSTANT VB WARNING: The following constructor is declared outside of its associated class:
'ORIGINAL LINE: if(_url != string.Empty)
Private Sub New(Optional _url (Not ByVal) As = String.Empty)
	' Render the PDF base64 data as a PDF in an iframe
'INSTANT VB WARNING: An assignment within expression was extracted from the following statement:
'ORIGINAL LINE: <iframe src="@_url" width="100%" height="500px"></iframe>
	"100%" height="500px"></iframe>
'INSTANT VB WARNING: An assignment within expression was extracted from the following statement:
'ORIGINAL LINE: <iframe src="@_url" width="100%" height
	"@_url" width="100%" height
	<iframe src="@_url" width
End Sub
$vbLabelText   $csharpLabel

This code snippet binds the base64 data to the src attribute of an iframe element. This causes browsers to use their built-in web viewers to render the Base64 content as an appropriate PDF document as soon as the page loads.

Here is an image of a PDF file that was generated from a base64 string.

How to Display PDF From Byte Array in Blazor, Figure 8: Viewing a PDF Generated in a Blazor app in the browser Viewing a PDF Generated in a Blazor app in the browser

Creating Simple PDF Files

Here's an example code snippet for creating a simple PDF document using IronPDF in C#:

// Create a simple PDF document with the text "Hello world!!"
var pdfDocument = new IronPdf.ChromePdfRenderer().RenderHtmlAsPdf("Hello world!!");
// Create a simple PDF document with the text "Hello world!!"
var pdfDocument = new IronPdf.ChromePdfRenderer().RenderHtmlAsPdf("Hello world!!");
' Create a simple PDF document with the text "Hello world!!"
Dim pdfDocument = (New IronPdf.ChromePdfRenderer()).RenderHtmlAsPdf("Hello world!!")
$vbLabelText   $csharpLabel

Using the method described in the preceding section, a client's browser can be used to view the created PDF document.

6. Conclusion

The tutorial shows how to use IronPDF Capabilities and Tutorials to create and display PDF documents in a Blazor Server app. It first introduces IronPDF and its capabilities, including how to convert HTML to PDF, adding custom headers and footers, and merging multiple PDFs. It then provides step-by-step instructions for installing IronPDF, creating a PDF file in a Blazor Server app and then converting it to a PDF byte array and displaying it on Blazor PDF viewer by using an iframe.

Overall, the tutorial provides a comprehensive overview of how to work with IronPDF and Blazor to create and display PDF documents. It encourages readers to experiment with IronPDF further and try out different features to create feature-rich applications.

If you're interested in trying out IronPDF in your Blazor project, you can take advantage of the free trial of IronPDF. This gives you ample time to experiment with the features and functionality of the library and see if it meets your needs.

To get started, you can refer to the IronPDF Documentation for Blazor, which provides detailed information on using the library in your project. You can also browse the IronPDF Blog and Tutorials for tutorials and articles that cover a range of topics related to PDF manipulation and rendering.

We encourage you to take the time to experiment with IronPDF and Blazor further and see how they can enhance your PDF-related development efforts. For more information on Blazor PDF viewer, please refer to the following IronPDF Blazor PDF Viewer Tutorial.

Preguntas Frecuentes

¿Cómo puedo mostrar un PDF desde una matriz de bytes en una aplicación Blazor?

Puedes usar IronPDF para convertir una matriz de bytes a una cadena base64 y luego vincular esta cadena al atributo 'src' de un iframe en tu aplicación Blazor. Este método aprovecha el visor de PDF integrado en el navegador para mostrar el documento.

¿Cuáles son los beneficios de usar Blazor Server sobre Blazor WebAssembly para el manejo de PDFs?

Se recomienda Blazor Server para el manejo de PDFs ya que puede gestionar archivos más grandes de manera más eficiente y admite funciones como revisión e impresión de PDFs, las cuales son cruciales para una aplicación comprensiva de visor de PDF.

¿Cómo integro IronPDF en un proyecto Blazor?

Puedes integrar IronPDF en un proyecto Blazor descargando la biblioteca IronPDF y usando el Administrador de Paquetes NuGet en Visual Studio para agregarla. El comando Install-Package IronPdf puede usarse en la consola del Administrador de Paquetes.

¿Puedo convertir URLs a PDFs en una aplicación Blazor?

Sí, usando el método RenderUrlAsPdf de IronPDF, puedes convertir contenido de una URL especificada en un formato PDF dentro de tu aplicación Blazor.

¿Es posible crear PDFs programáticamente en una aplicación Blazor?

Sí, con el método RenderHtmlAsPdf de IronPDF, puedes crear PDFs programáticamente renderizando contenido HTML como documentos PDF en una aplicación Blazor.

¿Qué herramientas se requieren para trabajar con IronPDF en un proyecto Blazor?

Para trabajar con IronPDF en un proyecto Blazor, necesitas Visual Studio 2019 o posterior, .NET 5.0 o posterior, y el paquete NuGet de IronPDF. Un entendimiento fundamental de Blazor y C# también es beneficioso.

¿Cómo puedo manejar cargadas y descargas de archivos en un visor de PDF de Blazor?

IronPDF admite cargadas y descargas de archivos en un visor de PDF de Blazor. Al integrar la biblioteca, puedes crear una aplicación web que maneje PDFs eficientemente usando código C# y componentes de Blazor.

¿Puedo fusionar varios PDFs dentro de una aplicación Blazor?

Sí, IronPDF proporciona funcionalidad para fusionar varios PDFs. Esto se puede lograr usando sus métodos para combinar diferentes documentos PDF en un solo archivo dentro de tu aplicación Blazor.

¿Hay una prueba gratuita disponible para IronPDF?

Sí, IronPDF ofrece un periodo de prueba gratuito que permite a los desarrolladores explorar sus características y funcionalidades para asegurarse de que cumple con los requisitos de su proyecto antes de realizar una compra.

¿Dónde puedo encontrar más recursos para usar IronPDF con Blazor?

Se pueden encontrar recursos adicionales para usar IronPDF con Blazor en la documentación de IronPDF, blogs y tutoriales. Estos recursos proporcionan una guía comprensiva sobre la implementación de funcionalidades PDF en aplicaciones Blazor.

¿IronPDF es compatible con .NET 10 y cómo afecta eso a la visualización de PDF de Blazor desde matrices de bytes?

Sí, IronPDF es totalmente compatible con .NET 10 y admite proyectos que lo implementan de forma predeterminada. Al usar Blazor en .NET 10, las mejoras de rendimiento, como la reducción de la sobrecarga de asignación y las capacidades asíncronas mejoradas, benefician operaciones como la conversión de matrices de bytes a PDF y su transmisión al cliente.

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