如何使用 IronPDF 与 Blazor 进行 PDF 生成 | IronPDF

IronPDF Blazor 服务器教程:在 C# 中将 HTML 渲染为 PDF;

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

IronPDF 可在 Blazor Server 应用程序中使用 C# 实现 HTML 到 PDF 的转换,只需最少的设置,支持 .NET 6 并可直接从您的 Blazor 组件提供 PDF 生成功能。

快速入门:在Blazor Server 中渲染 PDF

在您的 Blazor Server 应用程序中开始使用 IronPDF。 本示例演示了如何将 HTML 内容呈现为 PDF。 只需几行代码即可将您的 Blazor 组件转化为 PDF。

  1. 使用 NuGet 包管理器安装 https://www.nuget.org/packages/IronPdf

    PM > Install-Package IronPdf
  2. 复制并运行这段代码。

    IronPdf.HtmlToPdf.RenderHtmlAsPdf(htmlContent).SaveAs(outputPath);
  3. 部署到您的生产环境中进行测试

    通过免费试用立即在您的项目中开始使用IronPDF

    arrow pointer

如何创建新的 Blazor 服务器项目?

创建一个新项目,选择 Blazor 服务器应用程序类型。Visual Studio 提供了用于构建服务器端 Blazor 应用程序的模板,这些应用程序可以使用 .NET 生成 PDF。 Blazor 服务器托管模式可在服务器上执行您的应用程序逻辑,因此适用于需要服务器端处理的 IronPDF 生成场景。

Visual Studio 创建项目对话框显示 Blazor 服务器应用程序和其他 Blazor 项目模板及说明

Blazor服务器应用程序的前提条件是什么?

在使用 IronPDF 创建 Blazor Server 应用程序之前,请确保您已安装 Visual Studio 2022 或更高版本的 ASP.NET 和 Web 开发工作负载。 您需要 .NET 6 SDK 或更高版本。 Blazor Server 应用程序需要与服务器保持持续连接,因此适用于需要从复杂的 HTML 内容生成 PDF 的场景,或处理应保留在服务器上的敏感数据时。

我应该使用哪个 .NET 版本?

为保证 IronPDF for .NET 在 Blazor Server 应用程序中的兼容性和性能,请使用 .NET 6 或更高版本。 IronPDF 兼容 .NET Core 3.1、.NET 5、.NET 6、.NET 7 和 .NET 8。最新的 LTS 版本(.NET 6 或 .NET8)可提供稳定性和长期支持。 当 部署到 Azure 时,请确保您的 Azure 应用程序服务计划支持您选择的 .NET 版本。

如何配置项目设置?

配置 Blazor 服务器项目时,请选择 "Configure for HTTPS"(为 HTTPS 配置),以确保客户端与服务器之间的通信安全。 请不要选中 "启用 Docker",除非您计划在 Docker 中运行 IronPDF。 对于身份验证,请先选择 "无"--如果需要,您可以稍后再添加身份验证。 项目名称应遵循 C# 命名规范,避免空格或特殊字符。

如何将 IronPDF 安装到我的 Blazor 项目中?

创建项目后,请按照以下步骤在 Visual Studio 中安装来自 NuGet 的 IronPDF 库。 IronPdf 提供了一个 API,用于从 HTML 字符串、URL 和现有 PDF 文档创建 PDF。

  1. 在 Visual Studio 的解决方案资源管理器窗口中,右键单击 References,然后选择 Manage NuGet Packages
  2. 选择"浏览"并搜索 IronPdf
  3. 选择软件包的最新版本,勾选您的项目复选框,然后单击安装。

或者,您可以使用.NET CLI来安装它:

Install-Package IronPdf

对于针对特定平台的项目,您可能需要特定平台的软件包。 例如,如果部署到 Linux,请查看 Linux 安装指南

为什么选择 NuGet 包管理器而不是 CLI?

Visual Studio 中的 NuGet 软件包管理器图形用户界面提供了一个可视化界面,使浏览软件包版本、查看依赖关系和同时管理多个项目变得更加容易。 它可以帮助刚接触 IronPDF 的开发人员探索可用的软件包及其说明。 对于有经验的开发人员来说,CLI 方法更快,更适合自动构建管道或在使用 Docker 容器时使用。

我应该安装哪个版本的 IronPDF?

安装 IronPDF 的最新稳定版本,以访问新功能、性能改进和安全更新。 请查看 更新日志,了解最近更新的详细信息。 如果您正在使用现有项目,请确保与其他依赖项的版本兼容。 对于生产环境,应在升级主要版本之前进行全面测试。

如何验证安装是否成功?

安装后,通过检查解决方案资源管理器中的 "软件包 "文件夹来验证 IronPDF 是否正确安装。 您应在项目依赖项中看到 "IronPdf"。 在 C# 文件中添加 using IronPdf; - IntelliSense 应该能够识别该命名空间。 您还可以通过创建从 HTML 导出的基本 PDF 来运行一个简单的测试,以确认一切工作正常。

如何为 PDF 生成添加新的 Razor 组件?

在 Blazor 项目中安装 IronPDF 后,添加一个新的 Razor 组件。 本教程命名为 "IronPdfComponent"。 该组件将处理用户输入,并根据 HTML 内容动态生成 PDF。 Blazor 中的组件架构可以轻松创建可在应用程序中共享的可重用 PDF 生成功能。

Visual Studio

之后,更新代码如下:

@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();

        // Configure rendering options for better output
        render.RenderingOptions.PaperSize = IronPdf.Rendering.PdfPaperSize.A4;
        render.RenderingOptions.MarginTop = 40;
        render.RenderingOptions.MarginBottom = 40;

        // 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; } = @"<h1>Welcome to IronPDF</h1>
            <p>This is a sample PDF generated from HTML content in Blazor Server.</p>
            <ul>
                <li>Easy to use API</li>
                <li>High-quality rendering</li>
                <li>Full HTML5 and CSS3 support</li>
            </ul>";
    }
}
@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();

        // Configure rendering options for better output
        render.RenderingOptions.PaperSize = IronPdf.Rendering.PdfPaperSize.A4;
        render.RenderingOptions.MarginTop = 40;
        render.RenderingOptions.MarginBottom = 40;

        // 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; } = @"<h1>Welcome to IronPDF</h1>
            <p>This is a sample PDF generated from HTML content in Blazor Server.</p>
            <ul>
                <li>Easy to use API</li>
                <li>High-quality rendering</li>
                <li>Full HTML5 and CSS3 support</li>
            </ul>";
    }
}
$vbLabelText   $csharpLabel

该组件使用 ChromePdfRenderer 类 生成 PDF。 您可以使用 自定义纸张大小边距页眉/页脚等各种选项自定义呈现效果。

将此JavaScript代码添加到 _layout.cshtml,以允许在Blazor应用程序中下载IronPDF渲染的 PDF 文件:

<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

编辑 Shared 文件夹中的 NavMenu.razor 文件,为我们的新Razor组件添加导航选项卡。 添加以下代码:

<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

完成所有这些工作后,您就可以运行解决方案了,您应该会看到以下内容:

带有 IronPDF 组件的 Blazor 应用程序,在主内容区域显示 HTML 输入文本框和渲染 HTML 按钮

为什么在 Blazor 中使用 JavaScript 进行 PDF 下载?

Blazor 服务器通过 SignalR 连接运行,所有 C# 代码都在服务器上执行。 需要 JavaScript 互操作来触发特定于浏览器的操作,如文件下载。 DotNetStreamReference 类将二进制数据从服务器传输到客户端,而无需一次性将整个 PDF 加载到内存中。 这种方法比 base64 编码更有效,而且适用于大型 PDF。 如需其他方法,请考虑将 PDF 导出到内存流

实施 PDF 下载时有哪些常见问题?

常见的挑战包括处理可能导致 SignalR 连接超时的大文件、管理并发的 PDF 生成请求以及确保资源的正确处理。 为避免内存泄漏,请始终正确处理 PDF 文档和流。 考虑实施 async PDF 生成,以获得更好的性能。 如果遇到渲染问题,请查看渲染选项文档了解配置技巧。

如何处理大型 PDF 文件?

对于大型 PDF 文件,可考虑实施进度指示器和分块下载。 您可以使用 压缩技术优化 PDF 大小。 在 Blazor 服务器配置中设置适当的超时:

services.AddServerSideBlazor()
    .AddHubOptions(options =>
    {
        options.MaximumReceiveMessageSize = 10 * 1024 * 1024; // 10MB
        options.ClientTimeoutInterval = TimeSpan.FromSeconds(60);
    });
services.AddServerSideBlazor()
    .AddHubOptions(options =>
    {
        options.MaximumReceiveMessageSize = 10 * 1024 * 1024; // 10MB
        options.ClientTimeoutInterval = TimeSpan.FromSeconds(60);
    });
$vbLabelText   $csharpLabel

对于非常大的文档,可考虑先保存到服务器存储中,并提供下载链接,而不是直接流式传输。

何时应使用流引用与直接下载?

对于小于 50MB 且需要立即下载的 PDF 文件,请使用 DotNetStreamReference。 对于较大的文件或需要将 PDF 保存到磁盘时,可考虑在服务器上生成 PDF 并提供下载链接。 直接下载适用于报告和发票,而批处理或合并多个 PDF 可能会受益于服务器端存储。 在选择翻译方法时,请考虑应用程序的内存限制和用户体验要求。

常见问题解答

如何为生成 PDF 创建新的 Blazor Server 项目?

要使用 IronPDF 创建 Blazor Server 项目,请在 Visual Studio 中选择 "Blazor Server App "作为项目类型。Blazor Server托管模式在服务器上执行应用逻辑,因此非常适合需要使用IronPDF进行服务器端处理的PDF生成场景。

使用带有 PDF 生成功能的 Blazor Server 应用程序的前提条件是什么?

您需要 Visual Studio 2022 或更高版本的 ASP.NET 和 Web 开发工作负载,Plus .NET 6 SDK 或更高版本。Blazor Server 应用程序需要持续的服务器连接,因此适合使用 IronPDF 从复杂的 HTML 内容生成 PDF,或处理应保留在服务器上的敏感数据时使用。

在 Blazor 中生成 PDF 时应使用哪个 .NET 版本?

为在 Blazor Server 应用程序中与 IronPDF 实现最佳兼容性和性能,请使用 .NET 6 或更高版本。IronPDF 支持 .NET Core 3.1、.NET 5、.NET 6、.NET 7 和 .NET 8。最新的 LTS 版本(.NET 6 或 .NET8)可提供稳定性和长期支持。

如何配置 Blazor PDF 应用程序的项目设置?

在为 IronPDF 配置 Blazor 服务器项目时,选择 "Configure for HTTPS "以确保通信安全。不要选中 "启用 Docker",除非你计划在 Docker 容器中运行 IronPDF。身份验证从 "无 "开始--你可以稍后添加。使用正确的 C# 命名规范,不要使用空格或特殊字符。

如何在 Blazor Server 中从 HTML 快速生成 PDF?

IronPDF 为在 Blazor Server 中将 HTML 转换为 PDF 提供了简单的单线解决方案:IronPdf.HtmlToPdf.RenderHtmlAsPdf(htmlContent).SaveAs(outputPath)。这样,您就可以用最少的代码将 Blazor 组件转换为 PDF。

在 Blazor 中实现 PDF 生成的最基本工作流程是什么?

最基本的工作流程包括 5 个步骤:1) 安装 IronPDF HTML-to-PDF 库;2) 在 Visual Studio 中创建一个新的 Blazor 项目;3) 使用 IronPDF 将网页通过 URL 转换为 PDF 文档;4) 将网页渲染到客户端的网络浏览器中;5) 查看从 HTML 字符串生成的 PDF 文档。

Curtis Chau
技术作家

Curtis Chau 拥有卡尔顿大学的计算机科学学士学位,专注于前端开发,精通 Node.js、TypeScript、JavaScript 和 React。他热衷于打造直观且美观的用户界面,喜欢使用现代框架并创建结构良好、视觉吸引力强的手册。

除了开发之外,Curtis 对物联网 (IoT) 有浓厚的兴趣,探索将硬件和软件集成的新方法。在空闲时间,他喜欢玩游戏和构建 Discord 机器人,将他对技术的热爱与创造力相结合。

准备开始了吗?
Nuget 下载 17,803,474 | 版本: 2026.3 刚刚发布
Still Scrolling Icon

还在滚动吗?

想快速获得证据? PM > Install-Package IronPdf
运行示例看着你的HTML代码变成PDF文件。