푸터 콘텐츠로 바로가기
IRONPDF 사용
IronPDF를 사용하여 Blazor HTML을 PDF로 변환하기

Create a PDF File with Blazor Tutorial

IronPDF, a renowned C# library, works with Blazor applications. This review will guide you through using IronPDF to embed a PDF report in a Blazor application, showcasing its seamless integration and effectiveness.

1. IronPDF Features

Developers can quickly create, read, and process a PDF document with the help of the robust IronPDF .NET PDF library. IronPDF has a built-in Chrome engine and offers a wealth of practical and potent capabilities. These include the ability to convert HTML5, JavaScript, CSS, and images to PDF, the ability to add unique headers and footers to PDF documents, and the ability to produce PDFs precisely as they appear in a web browser. IronPDF supports various web technologies, including HTML, ASPX, Razor Pages, and MVC frameworks.

IronPDF's key attributes are as follows:

  • IronPDF offers full control over the creation and modification of PDF files within .NET C# applications
  • IronPDF can generate PDF files of web pages from their URLs using specific User-Agent, Proxy, Header, and Cookie configurations.
  • IronPDF can generate PDF files for web pages located behind login forms using form variables
  • IronPDF can extract and/or remove photos from pre-existing PDF files
  • IronPDF can add text, photos, bookmarks, watermarks, and other elements to PDF documents
  • IronPDF makes it easy to merge and split pages of one or more PDF documents.
  • IronPDF can process web page assets such as JavaScript, CSS, and media files and render them into PDF documents just as they would appear in a browser.
  • IronPDF supports all .NET Frameworks, including .NET Core, .NET Standard, etc.

2. What is Blazor?

Blazor is a Web Application Framework that makes it feasible to create client-side Web Applications in C# and HTML using Web Assembly.

Web Assembly apps are sent to the browser in a binary instruction format that can operate at close-to-native speed. This has created new potential for languages like C# to run inside the browser.

Creating a New Project in Visual Studio

To begin, open the Microsoft Visual Studio application and select "New Project" from the File menu. Then, select "Blazor Server App".

Create a PDF File with Blazor Tutorial, Figure 1: Creating a New Project in Visual Studio Creating a New Project in Visual Studio

Enter a project name and select a file path. Then, click the Create button.

Create a PDF File with Blazor Tutorial, Figure 2: Choosing the name and location of the new Blazor Application Choosing the name and location of the new Blazor Application

Select the desired .NET Framework (we will use .NET 6.0 in this tutorial), as shown in the screenshot below:

Create a PDF File with Blazor Tutorial, Figure 3: Creating a New Project in Visual Studio with the .NET 6.0 Framework Creating a New Project in Visual Studio with the .NET 6.0 Framework

Microsoft Visual Studio will now generate the structure for this Blazor application.

Next, add the IronPDF library to this new project.

3. Install the IronPDF Library

The IronPDF Library can be downloaded and installed in four ways:

  • Using Visual Studio's NuGet Package Manager
  • Using Visual Studio's Command-Line
  • Downloading directly from the NuGet website
  • Downloading directly from the IronPDF website

3.1 Using Visual Studio's NuGet Package Manager

Visual Studio provides the NuGet Package Manager to assist in installing libraries directly into projects. The screenshot below shows how to open the NuGet Package Manager.

Create a PDF File with Blazor Tutorial, Figure 4: Accessing Visual Studio's NuGet Package Manager Accessing Visual Studio's NuGet Package Manager

Use the search field under the Browse tab to search for "IronPDF", as shown in the screenshot below:

Create a PDF File with Blazor Tutorial, Figure 5: Searching for the IronPDF library in the NuGet Package Manager GUI Searching for the IronPDF library in the NuGet Package Manager GUI

In the image above, it shows the list of the related search results. Select the required options to install the package into your project.

3.2 Using Visual Studio Command-Line

In Visual Studio, go to Tools > NuGet Package Manager > Package Manager Console

Enter the following line into the Package Manager Console tab:

Install-Package IronPdf

The package will now be downloaded and installed in the current project.

Create a PDF File with Blazor Tutorial, Figure 6: Installing the IronPDF library using the NuGet Package Manager Console Installing the IronPDF library using the NuGet Package Manager Console

3.3 Downloading Directly from the NuGet Website

The third way to install the IronPDF library is to download the NuGet package directly from the website.

Navigate to NuGet website for IronPDF.

  • Click the "Download Package" option from the menu on the right-hand side.
  • Open the downloaded package on your file system. It will be installed automatically.
  • Reload the solution and start using it in your project.

3.4 Downloading Directly from the IronPDF Website

Visit the IronPDF website to download the IronPDF package directly.

After downloading, follow these steps to add the package to your project:

  • Right-click the project from the solution window.
  • Select the option "Add" > "Reference" and then navigate to the location of the library that you downloaded previously.
  • Click OK to add the library as a reference.

4. Create PDF documents in the Blazor Server App

The Blazor app in this tutorial will use IronPDF to fetch a web page's HTML content by its URL and convert it into a PDF document.

Enter the following source code in the .razor file contained in the project.

@using IronPdf

@code {
    /// <summary>
    /// This method exports data by converting a URL to a PDF file and initiating its download.
    /// </summary>
    public async Task ExportData()
    {
        try
        {
            string fileName = "Demo.pdf";
            var renderer = new ChromePdfRenderer();

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

            // Save the PDF using a JavaScript function
            await JSRuntime.InvokeVoidAsync("saveAsFile", fileName, Convert.ToBase64String(pdf.Stream.ToArray()));
        }
        catch (Exception ex)
        {
            // Handle any exceptions that may occur
            Console.Error.WriteLine($"Error in ExportData: {ex.Message}");
        }
    }
}
@using IronPdf

@code {
    /// <summary>
    /// This method exports data by converting a URL to a PDF file and initiating its download.
    /// </summary>
    public async Task ExportData()
    {
        try
        {
            string fileName = "Demo.pdf";
            var renderer = new ChromePdfRenderer();

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

            // Save the PDF using a JavaScript function
            await JSRuntime.InvokeVoidAsync("saveAsFile", fileName, Convert.ToBase64String(pdf.Stream.ToArray()));
        }
        catch (Exception ex)
        {
            // Handle any exceptions that may occur
            Console.Error.WriteLine($"Error in ExportData: {ex.Message}");
        }
    }
}
$vbLabelText   $csharpLabel

The code snippet above uses two methods to generate PDF documents from HTML. The first one is IronPDF's RenderUrlAsPdf method, which downloads the HTML content from a given URL and converts it into a PDF format.

The second method is the static JSRuntime.InvokeVoidAsync method, which triggers a browser's JavaScript engine to invoke a JavaScript function within the scope of the web page that saves the PDF content to a file on the client's file system.

This JavaScript function is included below:

<script type="text/javascript">
    /**
     * Saves the PDF data as a file on the client's system.
     * @param {string} filename - The name of the file to be created.
     * @param {string} bytesBase64 - The Base64 encoded string of the PDF data.
     */
    function saveAsFile(filename, bytesBase64) {
        if (navigator.msSaveBlob) {
            // Download the document in Microsoft Edge browser
            var data = window.atob(bytesBase64);
            var bytes = new Uint8Array(data.length);
            for (var i = 0; i < data.length; i++) {
                bytes[i] = data.charCodeAt(i);
            }
            var blob = new Blob([bytes.buffer], { type: "application/octet-stream" });
            navigator.msSaveBlob(blob, filename);
            window.navigator.msSaveOrOpenBlob(blob);
        }
        else {
            var link = document.createElement('a');
            link.download = filename;
            link.href = "data:application/octet-stream;base64," + bytesBase64;
            document.body.appendChild(link); // Needed for Firefox
            link.click();
            document.body.removeChild(link);
        }
    }
</script>
<script type="text/javascript">
    /**
     * Saves the PDF data as a file on the client's system.
     * @param {string} filename - The name of the file to be created.
     * @param {string} bytesBase64 - The Base64 encoded string of the PDF data.
     */
    function saveAsFile(filename, bytesBase64) {
        if (navigator.msSaveBlob) {
            // Download the document in Microsoft Edge browser
            var data = window.atob(bytesBase64);
            var bytes = new Uint8Array(data.length);
            for (var i = 0; i < data.length; i++) {
                bytes[i] = data.charCodeAt(i);
            }
            var blob = new Blob([bytes.buffer], { type: "application/octet-stream" });
            navigator.msSaveBlob(blob, filename);
            window.navigator.msSaveOrOpenBlob(blob);
        }
        else {
            var link = document.createElement('a');
            link.download = filename;
            link.href = "data:application/octet-stream;base64," + bytesBase64;
            document.body.appendChild(link); // Needed for Firefox
            link.click();
            document.body.removeChild(link);
        }
    }
</script>
HTML

The JavaScript function above receives the Base64 data from Blazor and converts it into a blob before saving it to the client-side location.

Alternatively, The SaveAs method from the ChromePdfRenderer class can also be used to save PDF documents to the browser's local storage.

5. Create a PDF Document from an HTML String

The following snippet of code shows how to turn an HTML string into a document.

@using IronPdf

@code {
    /// <summary>
    /// Demonstrates turning an HTML string into a PDF document.
    /// </summary>
    public void GeneratePdfFromHtmlString()
    {
        var renderer = new ChromePdfRenderer();
        var pdf = renderer.RenderHtmlAsPdf("<h1>Hello world!!</h1>");

        // You can save the generated PDF locally
        pdf.SaveAs("HelloWorld.pdf");
    }
}
@using IronPdf

@code {
    /// <summary>
    /// Demonstrates turning an HTML string into a PDF document.
    /// </summary>
    public void GeneratePdfFromHtmlString()
    {
        var renderer = new ChromePdfRenderer();
        var pdf = renderer.RenderHtmlAsPdf("<h1>Hello world!!</h1>");

        // You can save the generated PDF locally
        pdf.SaveAs("HelloWorld.pdf");
    }
}
$vbLabelText   $csharpLabel

The preceding example uses the RenderHtmlAsPdf instance method to transform any string of HTML into PDF content. Furthermore, the SaveAs method can be used in the procedures described previously to save this content on the client's computer.

Create a PDF File with Blazor Tutorial, Figure 7: The Blazor PDF Generation Application created in this tutorial The Blazor PDF Generation Application created in this tutorial

The screenshot above shows the Web Application that developed in this tutorial. Clicking on the Download button will trigger the C# code to produce the PDF content, and a JavaScript function to download the PDF content on the client-side.

Conclusion

This article demonstrated how to develop a Blazor Web Application that uses the IronPDF PDF library to generate PDF files from web pages.

IronPDF is not open source, however, a free trial key allows you to use it in production without watermarks.

자주 묻는 질문

PDF 라이브러리를 Blazor 서버 측 애플리케이션과 통합하려면 어떻게 해야 하나요?

IronPDF를 사용하여 PDF 라이브러리를 Blazor 서버 측 애플리케이션과 통합할 수 있습니다. 먼저 Visual Studio에서 Blazor 프로젝트를 생성한 다음 NuGet 패키지 관리자 또는 명령줄을 통해 IronPDF 라이브러리를 설치합니다. IronPDF를 사용하면 HTML 콘텐츠로부터 PDF 문서를 원활하게 생성할 수 있습니다.

Blazor 애플리케이션에서 HTML로 PDF를 생성하는 데 사용할 수 있는 방법은 무엇인가요?

블레이저 애플리케이션에서는 IronPDF의 RenderUrlAsPdf 메서드를 사용하여 웹 페이지 URL을 PDF로 변환하거나 RenderHtmlAsPdf로 HTML 문자열에서 직접 PDF를 생성할 수 있습니다. 이러한 메서드를 사용하면 다양한 HTML 소스에서 PDF 문서를 유연하게 생성할 수 있습니다.

Blazor 애플리케이션에서 PDF 파일을 클라이언트의 파일 시스템에 저장하려면 어떻게 해야 하나요?

Blazor 애플리케이션에서 PDF 파일을 클라이언트의 파일 시스템에 저장하려면 JavaScript 함수를 사용하여 PDF 데이터를 블롭으로 변환하고 다운로드를 트리거할 수 있습니다. IronPDF는 PDF를 생성하는 데 필요한 도구를 제공하며, 클라이언트 측 JavaScript를 사용하여 처리할 수 있습니다.

Visual Studio에서 Blazor 서버 측 프로젝트를 만드는 과정은 어떻게 되나요?

Visual Studio에서 Blazor 서버 측 프로젝트를 만들려면 파일 메뉴에서 '새 프로젝트'를 선택하고 'Blazor 서버 앱'을 선택한 다음 프로젝트 이름과 위치를 지정하고 적절한 .NET Framework 버전을 선택하면 됩니다. 이 설정을 통해 IronPDF와 같은 추가 라이브러리를 통합하여 기능을 향상시킬 수 있습니다.

이 라이브러리를 사용하여 HTML 내의 JavaScript 및 CSS 콘텐츠를 PDF로 변환할 수 있나요?

예, IronPDF를 사용하여 HTML 내의 JavaScript 및 CSS 콘텐츠를 PDF로 변환할 수 있습니다. HTML5, CSS 및 JavaScript 콘텐츠 렌더링을 지원하므로 원본 웹 페이지의 레이아웃과 스타일을 유지하는 포괄적인 PDF 문서를 생성할 수 있습니다.

Blazor에서 PDF 생성이 예상대로 작동하지 않는 경우 어떤 문제 해결 단계가 있나요?

Blazor에서 PDF 생성이 예상대로 작동하지 않는 경우 프로젝트에 IronPDF 라이브러리가 올바르게 설치되어 있는지 확인하세요. HTML 콘텐츠의 형식이 올바르게 지정되어 있고 액세스할 수 있는지 확인합니다. 또한 브라우저 콘솔에서 PDF 렌더링 프로세스에 영향을 줄 수 있는 JavaScript 오류가 있는지 확인하세요.

PDF 라이브러리를 사용할 때 PDF 문서에 머리글과 바닥글이 포함되도록 하려면 어떻게 해야 하나요?

IronPDF를 사용하여 PDF 문서에 머리글과 바닥글을 포함하려면 렌더링 옵션을 구성하여 사용자 지정 머리글 및 바닥글 콘텐츠를 추가할 수 있습니다. 이렇게 하면 PDF 출력물에 페이지 번호나 제목과 같은 추가 정보를 포함할 수 있습니다.

Blazor 애플리케이션에서 인증 후 페이지에 대한 PDF를 생성할 수 있나요?

예, IronPDF는 Blazor 애플리케이션에서 인증 후 페이지에 대한 PDF를 생성할 수 있습니다. 라이브러리의 기능을 사용하여 PDF로 변환하기 전에 제한된 콘텐츠에 액세스하기 위해 인증 쿠키 또는 토큰을 관리해야 합니다.

IronPDF는 .NET 10과 호환되며, .NET 10과 함께 사용하면 어떤 이점이 있나요?

예, IronPDF는 .NET 10과 완벽하게 호환되며 사용자 정의 해결 방법, 심 또는 버려진 API 없이도 즉시 작동합니다. .NET 10은 향상된 성능, 향상된 종속성 관리, 향상된 프레임워크 참조 처리, 향상된 JavaScript 격리 등 ASP.NET Core 및 Blazor에 대한 업데이트를 제공하며, 이 모든 기능은 Razor 페이지, URL 또는 HTML 콘텐츠를 사용하는 PDF 생성 워크플로우에 도움이 됩니다.

.NET 10과 함께 IronPDF를 사용하면 성능과 런타임 효율성이 어떻게 향상되나요?

.NET 10과 함께 IronPDF를 사용하면 배열 인터페이스 메서드 가상화, 구조체에 대한 이스케이프 분석, 향상된 JIT 최적화, AVX-512 명령어 지원 등 여러 런타임 개선 사항을 활용할 수 있습니다. 이러한 개선 사항으로 메모리 할당을 줄이고 가비지 컬렉션 오버헤드를 줄이며 HTML 렌더링 및 PDF 조작과 같은 작업 속도를 높일 수 있습니다.

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

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

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