IronPDF Blazor Server 教學:使用 C# 將 HTML 渲染為 PDF
IronPDF 讓您能透過 C# 在 Blazor Server 應用程式中,以極簡的設定實現 HTML 轉 PDF 功能,支援 .NET 6,並提供直接從您的 Blazor 元件生成 PDF 的能力。
快速入門:在 Blazor Server 中渲染 PDF
在您的 Blazor Server 應用程式中開始使用 IronPDF。 此範例示範如何將 HTML 內容渲染為 PDF。 只需幾行程式碼,即可將您的 Blazor 元件轉換為 PDF 檔案。
簡化工作流程(5 個步驟)
- 為 Blazor 應用程式安裝 HTML 轉 PDF 函式庫
- 在 Visual Studio 中建立一個新的 Blazor 專案。
- 將網頁(透過 URL)轉換為 PDF 文件
- 將網頁渲染至客戶的網頁瀏覽器中
- 從 HTML 字串檢視 PDF 文件
如何建立新的 Blazor Server 專案?
建立新專案並選擇"Blazor Server App"類型。Visual Studio 提供用於建置伺服器端 Blazor 應用程式的範本,該應用程式可利用 .NET 進行 PDF 生成。 Blazor Server 的託管模式會在伺服器端執行您的應用程式邏輯,因此非常適合需要伺服器端處理的 PDF 生成情境。
Blazor Server 應用程式的先決條件有哪些?
在使用 IronPDF 建立 Blazor Server 應用程式之前,請確認您已安裝 Visual Studio 2022 或更新版本,並包含 ASP.NET 及網頁開發工作負載。 您需要 .NET 6 SDK 或更高版本。 Blazor Server 應用程式需要與伺服器保持持續連線,因此特別適合用於需從複雜的 HTML 內容生成 PDF 的情境,或是處理應保留在伺服器上的敏感資料時。
我應該使用哪個 .NET 版本?
為確保在 Blazor Server 應用程式中與 IronPDF 的相容性與效能,請使用 .NET 6 或更高版本。 IronPDF 相容於 .NET Core 3.1、.NET 5、.NET 6、.NET 7 及 .NET 8。最新的 LTS 版本(.NET 6 或 .NET 8)提供穩定性與長期支援。 部署至 Azure 時,請確保您的 Azure App Service 方案支援您所選用的 .NET 版本。
如何設定專案設定?
在設定 Blazor Server 專案時,請選取"設定為 HTTPS",以確保客戶端與伺服器之間的通訊安全。 除非您計劃在 Docker 中執行 IronPDF,否則請勿勾選"啟用 Docker"選項。 關於驗證設定,請先選擇"無"——如有需要,日後可再新增驗證機制。 專案名稱應遵循 C# 命名規範,並避免使用空格或特殊字元。
如何將 IronPDF 安裝到我的 Blazor 專案中?
建立專案後,請依照以下步驟在 Visual Studio 中透過 NuGet 安裝 IronPDF 函式庫。 IronPDF 提供了一組 API,可用於從 HTML 字串、URL 及現有 PDF 文件建立 PDF 檔案。
- 在 Visual Studio 的"解決方案資源管理器"視窗中,右鍵點擊
References並選擇Manage NuGet Packages。 - 點選"瀏覽",並搜尋
IronPdf。 - 選擇套件的最新版本,勾選您專案對應的核取方塊,然後點擊安裝。
此外,您也可以使用 .NET CLI 進行安裝:
Install-Package IronPdf
針對特定平台的專案,您可能需要平台專用的套件。 例如,若要在 Linux 上部署,請參閱 Linux 安裝指南。
為何選擇 NuGet 套件管理員而非 CLI?
Visual Studio 中的 NuGet 套件管理員 GUI 提供了一個視覺化介面,讓使用者能更輕鬆地瀏覽套件版本、檢視依賴項,並同時管理多個專案。 這有助於初次接觸 IronPDF 的開發者探索可用的套件及其說明。 對於經驗豐富的開發者而言,命令列介面 (CLI) 的方式速度更快,且更適合用於自動化建置流程,或在處理 Docker 容器時使用。
我應該安裝哪個版本的 IronPDF?
安裝 IronPDF 的最新穩定版本,即可使用新功能、性能提升及安全性更新。 請查閱變更紀錄以了解近期更新的詳細資訊。 若您正在處理現有專案,請確保與其他依賴項的版本相容性。 在生產環境中,升級主要版本前請務必進行徹底測試。
如何確認安裝是否成功?
安裝完成後,請透過檢視"解決方案資源管理員"中的"套件"資料夾,確認 IronPDF 已正確安裝。 您應能在專案依賴項中看到"IronPDF"。 在 C# 檔案中加入 using IronPdf; —— IntelliSense 應能識別此命名空間。 您亦可透過將 HTML 轉為基本 PDF 檔案進行簡易測試,以確認所有功能運作正常。
如何新增用於 PDF 生成的 Razor 元件?
在您的 Blazor 專案中安裝 IronPDF 後,請新增一個 Razor 元件。 請將本教學命名為 IronPdfComponent。 此元件將處理使用者輸入,並根據 HTML 內容動態產生 PDF 檔案。 Blazor 的元件架構讓您能輕鬆建立可重複使用的 PDF 生成功能,並在整個應用程式中共享。
接著,請依下列方式更新程式碼:
@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>
@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>";
}
}
Imports System.Threading.Tasks
Imports Microsoft.JSInterop
Imports IronPdf
@Code
' Model to bind user input
Private _InputMsgModel As New InputHTMLModel()
Private Async Function SubmitHTML() As Task
' Set your IronPDF license key
IronPdf.License.LicenseKey = "IRONPDF-MYLICENSE-KEY-1EF01"
' Create a renderer to convert HTML to PDF
Dim 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
Dim doc = render.RenderHtmlAsPdf(_InputMsgModel.HTML)
Dim fileName = "iron.pdf"
' Create a stream reference for the PDF content
Using streamRef = New DotNetStreamReference(stream:=doc.Stream)
' Invoke JavaScript function to download the PDF in the browser
Await JS.InvokeVoidAsync("SubmitHTML", fileName, streamRef)
End Using
End Function
Public Class InputHTMLModel
Public Property HTML As String = "<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>"
End Class
此元件使用 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>
請編輯 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>
完成上述設定後,執行您的解決方案,您應會看到以下畫面:
為何在 Blazor 中使用 JavaScript 進行 PDF 下載?
Blazor Server 透過 SignalR 連線運作,所有 C# 程式碼皆在伺服器端執行。 需透過 JavaScript 互通功能來觸發瀏覽器專屬動作,例如檔案下載。 DotNetStreamReference 類別可在不將整個 PDF 檔案一次載入記憶體的情況下,將二進位資料從伺服器傳輸至客戶端。 此方法比 Base64 編碼更有效率,且適用於大型 PDF 檔案。 若需其他解決方案,可考慮將 PDF 匯出至記憶體串流。
實作 PDF 下載時常見哪些問題?
常見的挑戰包括處理可能導致 SignalR 連線超時的大型檔案、管理並發的 PDF 生成請求,以及確保資源的正確釋放。 為避免記憶體洩漏,請務必妥善釋放 PDF 文件及 MemoryStream 的資源。 建議採用非同步 PDF 生成機制以提升效能。 若遇到渲染問題,請參閱渲染選項文件以獲取設定建議。
如何處理大型 PDF 檔案?
針對大型 PDF 檔案,請考慮實作進度指示器與分段下載功能。 您可以透過壓縮技術來優化 PDF 檔案大小。 請在您的 Blazor Server 設定中設定適當的超時值:
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);
});
對於非常大的文件,建議先儲存至伺服器儲存空間,並提供下載連結,而非直接串流傳輸。
何時該使用串流參考,何時該使用直接下載?
若需立即下載小於 50MB 的 PDF 檔案,請使用 DotNetStreamReference。 若檔案較大,或需將 PDF 儲存至磁碟時,建議在伺服器端生成 PDF 並提供下載連結。 直接下載方式適用於報告和發票,而批次處理或合併多個 PDF 檔案時,則可能更適合採用伺服器端儲存方案。 選擇解決方案時,請考量應用程式的記憶體限制與使用者體驗需求。
常見問題
如何建立新的 Blazor Server 專案來產生 PDF?
若要使用 IronPDF 建立 Blazor Server 專案,請在 Visual Studio 中將專案類型選為「Blazor Server App」。Blazor Server 的託管模型會在伺服器端執行應用程式邏輯,因此非常適合需要透過 IronPDF 進行伺服器端處理的 PDF 生成情境。
使用具備 PDF 生成功能的 Blazor Server 應用程式有哪些先決條件?
您需要 Visual Studio 2022 或更新版本,並具備 ASP.NET 和網頁開發工作負載,以及 .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 或 .NET 8)能提供穩定性與長期支援。
如何為 Blazor PDF 應用程式設定專案設定?
在為 IronPDF 設定 Blazor Server 專案時,請選取「Configure for HTTPS」以確保通訊安全。除非您計劃在 Docker 容器中執行 IronPDF,否則請保持「Enable Docker」未勾選。驗證設定請先選取「None」——您稍後可再進行設定。請遵循正確的 C# 命名規範,避免使用空格或特殊字元。
如何在 Blazor Server 中快速將 HTML 轉為 PDF?
IronPDF 為 Blazor Server 中的 HTML 轉 PDF 功能提供了一行即用的簡易解決方案:IronPdf.HtmlToPdf.RenderHtmlAsPdf(htmlContent).SaveAs(outputPath)。這讓您只需極少的程式碼,即可將 Blazor 元件轉換為 PDF 檔案。
在 Blazor 中實作 PDF 生成功能的最低限度工作流程為何?
最簡化的工作流程包含 5 個步驟:1) 安裝 IronPDF HTML 轉 PDF 函式庫,2) 在 Visual Studio 中建立新的 Blazor 專案,3) 使用 IronPDF 根據網址將網頁轉換為 PDF 文件,4) 在客戶端的網頁瀏覽器中渲染網頁,以及 5) 檢視由 HTML 字串生成的 PDF 文件。

