푸터 콘텐츠로 바로가기
IRONPDF 사용

How to Display PDF From Byte Array in 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())}";
}
$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>
}
$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!!");
$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.

자주 묻는 질문

Blazor 애플리케이션에서 바이트 배열의 PDF를 표시하려면 어떻게 해야 하나요?

IronPDF를 사용하여 바이트 배열을 base64 문자열로 변환한 다음 이 문자열을 Blazor 애플리케이션에서 iframe의 'src' 속성에 바인딩할 수 있습니다. 이 방법은 브라우저에 내장된 PDF 뷰어를 활용하여 문서를 표시합니다.

PDF 처리를 위해 Blazor WebAssembly보다 Blazor Server를 사용하면 어떤 이점이 있나요?

대용량 파일을 보다 효율적으로 관리할 수 있고 종합적인 PDF 뷰어 애플리케이션에 필수적인 PDF 검토 및 인쇄와 같은 기능을 지원하므로 PDF를 처리하는 데 Blazor Server를 권장합니다.

IronPDF를 Blazor 프로젝트에 통합하려면 어떻게 해야 하나요?

IronPDF 라이브러리를 다운로드하고 Visual Studio의 NuGet 패키지 관리자를 사용하여 추가함으로써 IronPDF를 Blazor 프로젝트에 통합할 수 있습니다. 패키지 관리자 콘솔에서 Install-Package IronPdf 명령을 사용할 수 있습니다.

Blazor 애플리케이션에서 URL을 PDF로 변환할 수 있나요?

예, IronPDF의 RenderUrlAsPdf 메서드를 사용하면 Blazor 애플리케이션 내에서 지정된 URL의 콘텐츠를 PDF 형식으로 변환할 수 있습니다.

Blazor 앱에서 프로그래밍 방식으로 PDF를 만들 수 있나요?

예, IronPDF의 RenderHtmlAsPdf 메서드를 사용하면 Blazor 애플리케이션에서 HTML 콘텐츠를 PDF 문서로 렌더링하여 프로그래밍 방식으로 PDF를 만들 수 있습니다.

블레이저 프로젝트에서 IronPDF로 작업하려면 어떤 도구가 필요하나요?

Blazor 프로젝트에서 IronPDF로 작업하려면 Visual Studio 2019 이상, .NET 5.0 이상 및 IronPDF NuGet 패키지가 필요합니다. Blazor와 C#에 대한 기본적인 이해도 도움이 됩니다.

Blazor PDF 뷰어에서 파일 업로드 및 다운로드는 어떻게 처리하나요?

IronPDF는 Blazor PDF 뷰어에서 파일 업로드 및 다운로드를 지원합니다. 라이브러리를 통합하면 C# 코드와 Blazor 구성 요소를 사용하여 PDF를 효율적으로 처리하는 웹 애플리케이션을 만들 수 있습니다.

Blazor 애플리케이션 내에서 여러 PDF를 병합할 수 있나요?

예, IronPDF는 여러 PDF를 병합하는 기능을 제공합니다. 이 기능을 사용하면 Blazor 애플리케이션 내에서 여러 PDF 문서를 하나의 파일로 결합할 수 있습니다.

IronPDF에 무료 평가판이 있나요?

예, IronPDF는 개발자가 구매하기 전에 프로젝트 요구 사항을 충족하는지 확인하기 위해 기능을 살펴볼 수 있는 무료 평가판을 제공합니다.

Blazor에서 IronPDF를 사용하기 위한 더 많은 리소스는 어디에서 찾을 수 있나요?

Blazor와 함께 IronPDF를 사용하기 위한 추가 리소스는 IronPDF 문서, 블로그 및 튜토리얼에서 찾을 수 있습니다. 이러한 리소스는 Blazor 애플리케이션에서 PDF 기능을 구현하는 데 대한 포괄적인 지침을 제공합니다.

IronPDF는 .NET 10과 호환되며, 이는 바이트 배열에서 Blazor PDF 디스플레이에 어떤 영향을 미치나요?

예 - IronPDF는 .NET 10과 완벽하게 호환되며, 이를 대상으로 하는 프로젝트를 즉시 지원합니다. .NET 10에서 Blazor를 사용하면 할당 오버헤드 감소 및 향상된 비동기 기능과 같은 성능 개선으로 바이트 배열을 PDF로 변환하고 클라이언트로 스트리밍하는 등의 작업에 도움이 됩니다.

커티스 차우
기술 문서 작성자

커티스 차우는 칼턴 대학교에서 컴퓨터 과학 학사 학위를 취득했으며, Node.js, TypeScript, JavaScript, React를 전문으로 하는 프론트엔드 개발자입니다. 직관적이고 미적으로 뛰어난 사용자 인터페이스를 만드는 데 열정을 가진 그는 최신 프레임워크를 활용하고, 잘 구성되고 시각적으로 매력적인 매뉴얼을 제작하는 것을 즐깁니다.

커티스는 개발 분야 외에도 사물 인터넷(IoT)에 깊은 관심을 가지고 있으며, 하드웨어와 소프트웨어를 통합하는 혁신적인 방법을 연구합니다. 여가 시간에는 게임을 즐기거나 디스코드 봇을 만들면서 기술에 대한 애정과 창의성을 결합합니다.