IronPDF Blazor 伺服器教程:在C#中將HTML渲染為PDF
IronPDF允許在Blazor伺服器應用程式中使用C#進行HTML到PDF的轉換,設置簡單,支持.NET 6,並能直接從Blazor組件生成PDF。
快速入門:在Blazor伺服器中渲染PDF
在您的Blazor伺服器應用程式中開始使用IronPDF。 這個例子展示了如何將HTML內容渲染成PDF。 只需幾行程式碼,即可將您的Blazor組件轉換為PDF。
最小工作流程(5步)
- 為Blazor應用程式安裝HTML到PDF程式庫
- 在Visual Studio中建立一個新的Blazor專案。
- 通過URL將網頁轉換為PDF文件
- 將網頁渲染到客戶端的網頁瀏覽器中
- 從HTML字串查看PDF文件
如何建立新的Blazor伺服器專案?
建立一個新專案並選擇Blazor伺服器應用程式型別。Visual Studio提供了一個模板,用於構建可以使用.NET生成PDF的伺服器端Blazor應用程式。 Blazor伺服器託管模型在伺服器上執行您的應用程式邏輯,使其適合需要伺服器端處理的PDF生成場景。
Blazor伺服器應用程式的先決條件是什麼?
在使用IronPDF建立Blazor伺服器應用程式之前,請確保您安裝了Visual Studio 2022或更高版本,並具備ASP.NET和Web開發工作負載。 您需要.NET 6 SDK或更高版本。 Blazor伺服器應用程式需要與伺服器保持恆定連接,使其適合於從複雜HTML內容生成PDF或處理應留在伺服器上的敏感資料的場景。
使用哪個.NET版本?
為了在Blazor伺服器應用程式中與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伺服器專案時,選擇"Configure for HTTPS"以確保客戶端和伺服器之間的安全通信。 除非您打算在Docker中運行IronPDF,否則不要勾選"Enable Docker"。 對於認證,最初選擇"None" - 如果需要,您可以稍後新增認證。 專案名稱應遵循C#命名約定,避免空格或特殊字元。
如何將IronPDF安裝到我的Blazor專案中?
建立專案後,按照以下步驟在Visual Studio中從NuGet安裝IronPDF程式庫。 IronPDF提供一個API,用於從HTML字串、URL和現有PDF文件建立PDF。
- 在Visual Studio的方案總管視窗中,右鍵點擊
Manage NuGet Packages。 - 選擇瀏覽並搜尋
IronPdf。 - 選擇該包的最新版本,選中您的專案的複選框,然後點擊安裝。
或者,您可以使用.NET CLI來安裝它:
Install-Package IronPdf
對於針對特定平台的專案,您可能需要平台特定的程式包。 例如,如果部署到Linux,請查看Linux安裝指南。
為什麼選擇NuGet程式包管理器而不是CLI?
Visual Studio中的NuGet程式包管理器GUI提供了一個視覺介面,更易於瀏覽程式包版本、查看依賴項並同時管理多個專案。 它幫助新接觸IronPDF的開發者探索可用程式包及其描述。 對於有經驗的開發者,CLI方法更快,並且更適合用於自動化構建管道或在Docker容器中工作時使用。
我應安裝哪個版本的IronPDF?
安裝最新穩定版本的IronPDF,以存取新功能、性能提升和安全更新。 查看changelog以了解最近的更新詳情。 若您在使用現有專案,請確保與其他依賴項的版本相容。 對於生產環境,請在升級主要版本前進行全面測試。
如何驗證安裝成功?
安裝後,通過檢查方案總管中的"程式包"文件夾來驗證IronPDF是否安裝正確。 您應該在專案依賴項中看到"IronPDF"。 將using IronPdf;新增到C#文件中 - IntelliSense應能識別該命名空間。 您還可以通過建立基本的PDF從HTML來進行簡單測試,以確認一切正常。
如何為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中,以允許下載由IronPDF在Blazor應用程式中渲染的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伺服器運行在SignalR連接上,所有C#程式碼在伺服器上執行。 JavaScript互操作需要觸發瀏覽器特定的操作,如文件下載。 DotNetStreamReference類將二進制資料從伺服器傳輸到客戶端,而無需一次性載入整個PDF進入記憶體。 相比base64編碼,此方法更有效,並且適合大型PDF。 對於替代方法,可以考慮將PDF導出到記憶體流。
實現PDF下載時常見問題是什麼?
常見挑戰包括處理可能超時SignalR連接的大文件、管理併發PDF生成請求以及確保資源的正確處置。 為避免記憶洩露,務必妥善處置PDF文件及MemoryStream。 考慮實現非同步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);
});
對於非常大的文件,考慮首先保存到伺服器儲存中,然後提供下載連結,而不是直接流式傳輸。
什麼時候應使用流引用與直接下載?
對於需要立即下載的50MB以下的PDF,使用DotNetStreamReference。 對於較大的文件或當您需要將PDF保存到磁盤時,考慮在伺服器上生成PDF並提供下載連結。 直接下載對報告和發票效果良好,而批量處理或合併多個PDF可能受益於伺服器端儲存。 在選擇方法時,考慮您的應用程式的記憶限制和使用者體驗需求。
常見問題
如何建立一個新的 Blazor Server 項目以生成 PDF?
要使用 IronPDF 建立 Blazor Server 專案,請在 Visual Studio 中選擇 'Blazor Server App' 作為專案型別。Blazor Server 託管模型在伺服器上執行應用程式邏輯,使其非常適合需要伺服器端處理的 PDF 生成方案,與 IronPDF 一起使用。
using PDF 生成功能的 Blazor Server 應用的先決條件是什麼?
您需要 Visual Studio 2022 或更高版本,包含 ASP.NET 和網頁開發工作負載,外加 .NET 6 SDK 或更高版本。Blazor Server 應用需要不斷的伺服器連接,使其適合使用 IronPDF 從複雜的 HTML 內容生成 PDF,或當處理需留存在伺服器上的敏感資料時。
我應該使用哪個 .NET 版本在 Blazor 中進行 PDF 生成?
為了在 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 應用程式的專案設置?
當您為 Blazor Server 專案配置 IronPDF 時,選擇 '設置為 HTTPS' 以進行安全通信。除非您計劃在 Docker 容器中運行 IronPDF,否則請保持未選中 '啟用 Docker'。 起始時使用 '無' 驗證 - 您可稍後新增。使用正確的 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 通過 URL 將網頁轉換為 PDF 文件,4)將網頁內容呈現到客戶端的網頁瀏覽器,5)查看從 HTML 字串生成的 PDF 文件。

