如何用IronPDF合併PDF VB NET
Blazor PDF檢視器通過將PDF文件轉換為base64資料URI並在<iframe>元素中載入結果來內嵌呈現PDF文件。 IronPDF的ChromePdfRenderer將HTML字串、實時URL或動態內容轉換為PDF字元流,在一次非同步呼叫中提供Blazor Server和Blazor WebAssembly應用程式完整的PDF生成和顯示功能,無需外部檢視器插件。
商業應用通常需要顯示發票、合同和報告,而不將使用者重定向到其他標籤或依賴於裝置不同的瀏覽器PDF支持。 Blazor的組件模型使得在伺服器上生成PDF、編碼並流式傳輸到任何頁面組件變得十分簡單,只要程式庫可靠地處理轉換。
本指南涵蓋了安裝、基於URL和HTML的呈現、通過JavaScript互操作進行瀏覽器下載、Blazor Server和Blazor WebAssembly方法的比較以及四種擴展操作:合併、註釋、密碼保護和使用者上傳文件的顯示。 對於每種技術均提供Razor組件和等效的頂層C#範例。
開始免費的IronPDF試用,以便與本指南中的範例一起學習。
如何在Blazor專案中開始使用IronPDF?
開始前需要在Program.cs中安裝NuGet套件並新增授權金鑰。 從套件管理器控制台安裝IronPDF:
Install-Package IronPdf
或者,在NuGet包管理器UI中搜索"IronPDF",並選擇最新版本。
安裝後,在任何PDF操作之前將授權金鑰新增到Program.cs中:
IronPdf.License.LicenseKey = "YOUR-LICENSE-KEY-HERE";
IronPdf.License.LicenseKey = "YOUR-LICENSE-KEY-HERE";
IronPdf.License.LicenseKey = "YOUR-LICENSE-KEY-HERE"
IronPDF與.NET 10、.NET 9、.NET 8、.NET 6和.NET Framework 4.6.2及以上版本相容。 對於開發和測試,程式庫在沒有授權金鑰的情況下運行,但會在生成的PDF上印上浮水印。 免費試用授權在評估期間移除浮水印。
IronPDF支持Blazor Server和Blazor WebAssembly專案。 在Blazor Server中,渲染引擎直接在伺服器上運行。 在Blazor WebAssembly中,PDF生成需要伺服器端API端點; 本指南的架構部分稍後將解釋這兩種方法。
如何從Blazor中的URL顯示PDF文件?
建立Blazor PDF檢視器的最直接方法是將URL轉換為PDF,並在<iframe>中顯示。 IronPDF的ChromePdfRenderer抓取網頁,並使用與Google Chrome相同的Chrome渲染引擎將其轉換為PDF格式,準確保留CSS、JavaScript輸出和佈局。
Razor組件方法
以下Razor組件將URL轉換為PDF並內嵌顯示。GeneratePdf方法在Blazor Server應用中運行在伺服器上,因此可以使用完整的Chrome渲染引擎:
@page "/pdfviewer"
@using IronPdf
<h3>PDF Viewer</h3>
<button @onclick="GeneratePdf" class="btn btn-primary">Load PDF</button>
@if (!string.IsNullOrEmpty(pdfDataUri))
{
<iframe src="@pdfDataUri" style="width:100%; height:600px; border:1px solid #ccc; margin-top:20px;"></iframe>
}
@code {
private string pdfDataUri = string.Empty;
private async Task GeneratePdf()
{
var renderer = new ChromePdfRenderer();
// Convert the URL to PDF using the Chrome rendering engine
var pdf = await renderer.RenderUrlAsPdfAsync("https://ironpdf.com");
// Encode the PDF bytes as a base64 data URI for iframe display
var base64 = Convert.ToBase64String(pdf.BinaryData);
pdfDataUri = $"data:application/pdf;base64,{base64}";
}
}
頂層C#範例
對於背景服務、控制台應用或伺服器端API端點,相同的轉換在任何組件上下文之外使用相同的API呼叫:
using IronPdf;
var renderer = new ChromePdfRenderer();
// Fetch and convert the target URL to a PDF document
var pdf = await renderer.RenderUrlAsPdfAsync("https://ironpdf.com");
// Save to disk or use BinaryData for in-memory operations
pdf.SaveAs("output.pdf");
byte[] pdfBytes = pdf.BinaryData;
using IronPdf;
var renderer = new ChromePdfRenderer();
// Fetch and convert the target URL to a PDF document
var pdf = await renderer.RenderUrlAsPdfAsync("https://ironpdf.com");
// Save to disk or use BinaryData for in-memory operations
pdf.SaveAs("output.pdf");
byte[] pdfBytes = pdf.BinaryData;
Imports IronPdf
Dim renderer As New ChromePdfRenderer()
' Fetch and convert the target URL to a PDF document
Dim pdf = Await renderer.RenderUrlAsPdfAsync("https://ironpdf.com")
' Save to disk or use BinaryData for in-memory operations
pdf.SaveAs("output.pdf")
Dim pdfBytes As Byte() = pdf.BinaryData
PdfDocument物件。 BinaryData屬性公開未經處理的PDF字元流以便於儲存、流式傳輸或顯示。 <iframe>使用內建的瀏覽器工具欄顯示輸出,以便進行縮放、導航和列印。

如何自定義PDF生成?
IronPDF通過ChromePdfRenderOptions類提供輸出控制。 您可以設置紙張大小、調整邊距,並在每頁新增文字或HTML頁首和頁尾。 渲染選項指南涵蓋了所有可用屬性的完整列表。
Razor組件方法
以下組件配置帶有邊距的A4紙張,並向每頁新增頁首和頁尾文字。 在調用任何渲染方法之前分配RenderingOptions,以全域應用於渲染器實例:
@page "/pdfcustom"
@using IronPdf
<h3>Customized PDF Viewer</h3>
<button @onclick="GenerateCustomizedPdf" class="btn btn-primary">Generate Customized PDF</button>
@if (!string.IsNullOrEmpty(pdfDataUri))
{
<iframe src="@pdfDataUri" style="width:100%; height:600px; border:1px solid #ccc; margin-top:20px;"></iframe>
}
@code {
private string pdfDataUri = string.Empty;
private async Task GenerateCustomizedPdf()
{
var renderer = new ChromePdfRenderer
{
RenderingOptions = new ChromePdfRenderOptions
{
PaperSize = IronPdf.Rendering.PdfPaperSize.A4,
MarginTop = 25,
MarginBottom = 25,
MarginLeft = 20,
MarginRight = 20,
// Header with dynamic date replacement
TextHeader = new TextHeaderFooter
{
CenterText = "Monthly Report - {date}",
FontSize = 12
},
// Footer with page numbering
TextFooter = new TextHeaderFooter
{
LeftText = "Confidential",
RightText = "Page {page} of {total-pages}",
FontSize = 10
}
}
};
var pdf = await renderer.RenderUrlAsPdfAsync("https://example.com/report");
pdfDataUri = $"data:application/pdf;base64,{Convert.ToBase64String(pdf.BinaryData)}";
}
}
頂層C#範例
相同的選項適用於任何.NET環境。 此模式在ASP.NET Core簡單API或計畫報告生成器內效果良好:
using IronPdf;
using IronPdf.Rendering;
var renderer = new ChromePdfRenderer
{
RenderingOptions = new ChromePdfRenderOptions
{
PaperSize = PdfPaperSize.A4,
MarginTop = 25,
MarginBottom = 25,
TextHeader = new TextHeaderFooter { CenterText = "Report - {date}", FontSize = 12 },
TextFooter = new TextHeaderFooter { RightText = "Page {page} of {total-pages}", FontSize = 10 }
}
};
var pdf = await renderer.RenderUrlAsPdfAsync("https://example.com/report");
pdf.SaveAs("customized-report.pdf");
using IronPdf;
using IronPdf.Rendering;
var renderer = new ChromePdfRenderer
{
RenderingOptions = new ChromePdfRenderOptions
{
PaperSize = PdfPaperSize.A4,
MarginTop = 25,
MarginBottom = 25,
TextHeader = new TextHeaderFooter { CenterText = "Report - {date}", FontSize = 12 },
TextFooter = new TextHeaderFooter { RightText = "Page {page} of {total-pages}", FontSize = 10 }
}
};
var pdf = await renderer.RenderUrlAsPdfAsync("https://example.com/report");
pdf.SaveAs("customized-report.pdf");
Imports IronPdf
Imports IronPdf.Rendering
Dim renderer As New ChromePdfRenderer With {
.RenderingOptions = New ChromePdfRenderOptions With {
.PaperSize = PdfPaperSize.A4,
.MarginTop = 25,
.MarginBottom = 25,
.TextHeader = New TextHeaderFooter With {.CenterText = "Report - {date}", .FontSize = 12},
.TextFooter = New TextHeaderFooter With {.RightText = "Page {page} of {total-pages}", .FontSize = 10}
}
}
Dim pdf = Await renderer.RenderUrlAsPdfAsync("https://example.com/report")
pdf.SaveAs("customized-report.pdf")
模板變數,包括TextFooter。 頁首和頁尾指南包含兩種方法的完整範例。

啟用PDF下載的最佳方法是什麼?
在<iframe>中顯示PDF處理檢視,但使用者經常需要下載文件。JavaScript互操作從.NET字元流觸發瀏覽器下載。 有關其他下載和導出模式,請參閱導出和保存PDF指南。
Razor組件方法
將IJSRuntime注入組件,並調用JavaScript輔助函式以啟動下載。 DotNetStreamReference在不將整個文件載入到JavaScript記憶體中的情況下流式傳輸PDF字元流:
@page "/pdfdownload"
@using IronPdf
@inject IJSRuntime JSRuntime
<h3>Download PDF</h3>
<button @onclick="DownloadPdf" class="btn btn-success">Download PDF</button>
@code {
private async Task DownloadPdf()
{
var renderer = new ChromePdfRenderer();
var pdf = await renderer.RenderHtmlAsPdfAsync("<h1>Invoice</h1><p>Total: $1,299</p>");
// Stream the PDF bytes to the browser as a downloadable file
using var streamRef = new DotNetStreamReference(stream: new MemoryStream(pdf.BinaryData));
await JSRuntime.InvokeVoidAsync("downloadFileFromStream", "invoice.pdf", streamRef);
}
}
將此JavaScript函式新增到您的App.razor文件中,如Microsoft的Blazor JavaScript互操作文件所述:
window.downloadFileFromStream = async (fileName, contentStreamReference) => {
const arrayBuffer = await contentStreamReference.arrayBuffer();
const blob = new Blob([arrayBuffer]);
const url = URL.createObjectURL(blob);
const anchorElement = document.createElement('a');
anchorElement.href = url;
anchorElement.download = fileName ?? '';
anchorElement.click();
anchorElement.remove();
URL.revokeObjectURL(url);
};
window.downloadFileFromStream = async (fileName, contentStreamReference) => {
const arrayBuffer = await contentStreamReference.arrayBuffer();
const blob = new Blob([arrayBuffer]);
const url = URL.createObjectURL(blob);
const anchorElement = document.createElement('a');
anchorElement.href = url;
anchorElement.download = fileName ?? '';
anchorElement.click();
anchorElement.remove();
URL.revokeObjectURL(url);
};
頂層C#範例
在伺服器端API端點中,使用Results.File直接返回PDF字元流。 瀏覽器接收到文件並帶有正確的Content-Disposition標頭,並自動觸發下載:
using IronPdf;
// ASP.NET Core minimal API endpoint
app.MapGet("/api/pdf/invoice", async () =>
{
var renderer = new ChromePdfRenderer();
var pdf = await renderer.RenderHtmlAsPdfAsync("<h1>Invoice</h1><p>Total: $1,299</p>");
// Return with file download headers
return Results.File(pdf.BinaryData, "application/pdf", "invoice.pdf");
});
using IronPdf;
// ASP.NET Core minimal API endpoint
app.MapGet("/api/pdf/invoice", async () =>
{
var renderer = new ChromePdfRenderer();
var pdf = await renderer.RenderHtmlAsPdfAsync("<h1>Invoice</h1><p>Total: $1,299</p>");
// Return with file download headers
return Results.File(pdf.BinaryData, "application/pdf", "invoice.pdf");
});
Imports IronPdf
' ASP.NET Core minimal API endpoint
app.MapGet("/api/pdf/invoice", Async Function()
Dim renderer As New ChromePdfRenderer()
Dim pdf = Await renderer.RenderHtmlAsPdfAsync("<h1>Invoice</h1><p>Total: $1,299</p>")
' Return with file download headers
Return Results.File(pdf.BinaryData, "application/pdf", "invoice.pdf")
End Function)
如何從Razor組件生成PDF?
從HTML生成PDF提供了對佈局、資料綁定和樣式的完全控制。 這種方法適合於發票、報告和任何從實時應用程式資料構建的文件。 有關更高級的渲染技術,請參閱HTML到PDF轉換指南。
Razor組件方法
下面的組件從C#資料構建一個發票HTML字串,並將其轉換為PDF。 ChromePdfRenderer將HTML字串視為網頁,應用所有CSS並使用Chrome引擎渲染:
@page "/invoicedemo"
@using IronPdf
<h3>Invoice Generator</h3>
<button @onclick="GenerateInvoice" class="btn btn-primary">Generate Invoice PDF</button>
@if (!string.IsNullOrEmpty(pdfDataUri))
{
<iframe src="@pdfDataUri" style="width:100%; height:600px; border:1px solid #ccc; margin-top:20px;"></iframe>
}
@code {
private string pdfDataUri = string.Empty;
private async Task GenerateInvoice()
{
var invoiceHtml = $@"
<html>
<head>
<style>
body {{font-family: Arial, sans-serif;}}
.header {{background-color: #f0f0f0; padding: 20px;}}
.invoice-table {{width: 100%; border-collapse: collapse;}}
.invoice-table th, .invoice-table td {{border: 1px solid #ddd; padding: 8px;}}
.total {{font-weight: bold; font-size: 18px;}}
</style>
</head>
<body>
<div class='header'>
<h1>Invoice #INV-2025-001</h1>
<p>Date: {DateTime.Now:MM/dd/yyyy}</p>
</div>
<table class='invoice-table'>
<thead>
<tr>
<th>Item</th><th>Quantity</th><th>Price</th><th>Total</th>
</tr>
</thead>
<tbody>
<tr>
<td>IronPDF License</td><td>1</td><td>$999</td><td>$999</td>
</tr>
<tr>
<td>Priority Support</td><td>1</td><td>$250</td><td>$250</td>
</tr>
</tbody>
</table>
<p class='total'>Total Amount: $999</p>
</body>
</html>";
var renderer = new ChromePdfRenderer();
var pdf = await renderer.RenderHtmlAsPdfAsync(invoiceHtml);
pdfDataUri = $"data:application/pdf;base64,{Convert.ToBase64String(pdf.BinaryData)}";
}
}
頂層C#範例
相同的HTML字串方法適用於任何.NET環境,包括控制台應用、背景服務和API端點。 C#字串插值或模板庫在將字串傳遞給渲染器之前插入動態資料:
using IronPdf;
var html = """
<html>
<body>
<h1>Invoice #INV-2025-001</h1>
<table>
<tr><th>Item</th><th>Total</th></tr>
<tr><td>IronPDF License</td><td>$999</td></tr>
<tr><td>Priority Support</td><td>$250</td></tr>
</table>
<p><strong>Total: $999</strong></p>
</body>
</html>
""";
var renderer = new ChromePdfRenderer();
var pdf = await renderer.RenderHtmlAsPdfAsync(html);
pdf.SaveAs("invoice.pdf");
using IronPdf;
var html = """
<html>
<body>
<h1>Invoice #INV-2025-001</h1>
<table>
<tr><th>Item</th><th>Total</th></tr>
<tr><td>IronPDF License</td><td>$999</td></tr>
<tr><td>Priority Support</td><td>$250</td></tr>
</table>
<p><strong>Total: $999</strong></p>
</body>
</html>
""";
var renderer = new ChromePdfRenderer();
var pdf = await renderer.RenderHtmlAsPdfAsync(html);
pdf.SaveAs("invoice.pdf");
Imports IronPdf
Dim html As String = "
<html>
<body>
<h1>Invoice #INV-2025-001</h1>
<table>
<tr><th>Item</th><th>Total</th></tr>
<tr><td>IronPDF License</td><td>$999</td></tr>
<tr><td>Priority Support</td><td>$250</td></tr>
</table>
<p><strong>Total: $999</strong></p>
</body>
</html>
"
Dim renderer As New ChromePdfRenderer()
Dim pdf = Await renderer.RenderHtmlAsPdfAsync(html)
pdf.SaveAs("invoice.pdf")
RenderHtmlAsPdfAsync接受任何有效的HTML字串,包括內聯CSS和嵌入式JavaScript。 該實現自動處理佈局、字體渲染和分頁符。

Blazor Server PDF檢視器和Blazor WebAssembly有何不同?
托管模型確定PDF生成在哪裡運行,以及字元流如何進入瀏覽器。 理解這一差別能防止構建Blazor PDF檢視器時常見的架構錯誤。
Blazor Server在伺服器上執行所有C#程式碼。 ChromePdfRenderer在伺服器端運行,並且結果字元流通過現有的SignalR連接推送到瀏覽器。 這是最簡單的整合路徑,除了之前章節所顯示的內容外,無需額外的API端點或網路呼叫。
Blazor WebAssembly使用WASM在瀏覽器的沙盒中運行C#。 IronPDF的渲染引擎依賴於無法在瀏覽器沙盒中運行的原生二進制,因此ChromePdfRenderer在WASM專案中不可用。 正確的方法是調用伺服器端API端點,該端點執行PDF生成並將字元流作為響應返回。
為Blazor WebAssembly設置PDF生成API
在伺服器上,定義一個最小API端點,用於生成和返回PDF:
// Program.cs (ASP.NET Core host project)
using IronPdf;
IronPdf.License.LicenseKey = "YOUR-LICENSE-KEY-HERE";
app.MapGet("/api/pdf/report", async () =>
{
var renderer = new ChromePdfRenderer();
var pdf = await renderer.RenderHtmlAsPdfAsync("<h1>Quarterly Report</h1><p>Generated server-side.</p>");
// Return PDF bytes with file download headers
return Results.File(pdf.BinaryData, "application/pdf", "report.pdf");
});
// Program.cs (ASP.NET Core host project)
using IronPdf;
IronPdf.License.LicenseKey = "YOUR-LICENSE-KEY-HERE";
app.MapGet("/api/pdf/report", async () =>
{
var renderer = new ChromePdfRenderer();
var pdf = await renderer.RenderHtmlAsPdfAsync("<h1>Quarterly Report</h1><p>Generated server-side.</p>");
// Return PDF bytes with file download headers
return Results.File(pdf.BinaryData, "application/pdf", "report.pdf");
});
Imports IronPdf
IronPdf.License.LicenseKey = "YOUR-LICENSE-KEY-HERE"
app.MapGet("/api/pdf/report", Async Function()
Dim renderer = New ChromePdfRenderer()
Dim pdf = Await renderer.RenderHtmlAsPdfAsync("<h1>Quarterly Report</h1><p>Generated server-side.</p>")
' Return PDF bytes with file download headers
Return Results.File(pdf.BinaryData, "application/pdf", "report.pdf")
End Function)
在WASM客戶端上,注入HttpClient並調用API端點。 Blazor WASM託管專案模板預先配置HttpClient以定位伺服器的基址:
@page "/wasm-pdf-viewer"
@inject HttpClient Http
<h3>PDF Viewer</h3>
<button @onclick="LoadPdf" class="btn btn-primary">Load Report</button>
@if (!string.IsNullOrEmpty(pdfDataUri))
{
<iframe src="@pdfDataUri" style="width:100%; height:600px;"></iframe>
}
@code {
private string pdfDataUri = string.Empty;
private async Task LoadPdf()
{
// Fetch PDF bytes from the server-side generation endpoint
var bytes = await Http.GetByteArrayAsync("/api/pdf/report");
pdfDataUri = $"data:application/pdf;base64,{Convert.ToBase64String(bytes)}";
}
}
此模式使所有繁重的渲染工作保持在伺服器上,而WASM客戶端僅處理顯示。 在生產使用中,新增身份驗證到API端點,並將生成的PDF內容範圍限定為經身份驗證的使用者資料。
我還能執行哪些其他PDF操作?
IronPDF的API擴展遠不止於基本檢視。 以下部分涵蓋Blazor文件工作流中常需的四個操作:合併多個文件、新增註釋、應用密碼保護和顯示使用者上傳的文件。
如何合併多個PDF文件?
合併將多個PdfDocument實例合併為單個文件,這對於組裝報告部分、附加附錄或串聯使用者選擇的文件非常有用。 合併和拆分PDF指南涵蓋頁面級別插入和拆分操作。
using IronPdf;
var renderer = new ChromePdfRenderer();
// Generate two separate sections as individual PDF documents
var section1 = await renderer.RenderHtmlAsPdfAsync("<h1>Section 1: Overview</h1>");
var section2 = await renderer.RenderHtmlAsPdfAsync("<h1>Section 2: Details</h1>");
// Merge into a single document preserving all pages
var merged = PdfDocument.Merge(section1, section2);
merged.SaveAs("combined-report.pdf");
using IronPdf;
var renderer = new ChromePdfRenderer();
// Generate two separate sections as individual PDF documents
var section1 = await renderer.RenderHtmlAsPdfAsync("<h1>Section 1: Overview</h1>");
var section2 = await renderer.RenderHtmlAsPdfAsync("<h1>Section 2: Details</h1>");
// Merge into a single document preserving all pages
var merged = PdfDocument.Merge(section1, section2);
merged.SaveAs("combined-report.pdf");
Imports IronPdf
Dim renderer As New ChromePdfRenderer()
' Generate two separate sections as individual PDF documents
Dim section1 = Await renderer.RenderHtmlAsPdfAsync("<h1>Section 1: Overview</h1>")
Dim section2 = Await renderer.RenderHtmlAsPdfAsync("<h1>Section 2: Details</h1>")
' Merge into a single document preserving all pages
Dim merged = PdfDocument.Merge(section1, section2)
merged.SaveAs("combined-report.pdf")
要在Blazor組件中顯示合併的文件,請將merged.BinaryData傳遞給早期章節中的base64資料URI模式。 合併的PdfDocument物件還接受進一步的操作(浮水印、安全設置或附加頁面附加)以便在顯示之前進行編碼。
如何向PDF新增註釋?
註釋將評論者筆記和評論附加到特定頁面位置,而不改變基礎文件內容。 IronPDF支持文字註釋、自由文字框和其他標註型別。完整註釋屬性列表請參閱註釋指南。
using IronPdf;
using IronPdf.Annotations;
var renderer = new ChromePdfRenderer();
var pdf = await renderer.RenderHtmlAsPdfAsync("<h1>Contract Document</h1><p>Review required on clause 3.</p>");
// Add a text annotation to page 0 at position (50, 650)
var annotation = new TextAnnotation(pageIndex: 0)
{
Title = "Reviewer Note",
Contents = "Please confirm clause 3 before signing.",
X = 50,
Y = 650,
Width = 200,
Height = 50,
Printable = false,
OpenByDefault = true
};
pdf.Annotations.Add(annotation);
pdf.SaveAs("annotated-contract.pdf");
using IronPdf;
using IronPdf.Annotations;
var renderer = new ChromePdfRenderer();
var pdf = await renderer.RenderHtmlAsPdfAsync("<h1>Contract Document</h1><p>Review required on clause 3.</p>");
// Add a text annotation to page 0 at position (50, 650)
var annotation = new TextAnnotation(pageIndex: 0)
{
Title = "Reviewer Note",
Contents = "Please confirm clause 3 before signing.",
X = 50,
Y = 650,
Width = 200,
Height = 50,
Printable = false,
OpenByDefault = true
};
pdf.Annotations.Add(annotation);
pdf.SaveAs("annotated-contract.pdf");
Imports IronPdf
Imports IronPdf.Annotations
Dim renderer As New ChromePdfRenderer()
Dim pdf = Await renderer.RenderHtmlAsPdfAsync("<h1>Contract Document</h1><p>Review required on clause 3.</p>")
' Add a text annotation to page 0 at position (50, 650)
Dim annotation As New TextAnnotation(pageIndex:=0) With {
.Title = "Reviewer Note",
.Contents = "Please confirm clause 3 before signing.",
.X = 50,
.Y = 650,
.Width = 200,
.Height = 50,
.Printable = False,
.OpenByDefault = True
}
pdf.Annotations.Add(annotation)
pdf.SaveAs("annotated-contract.pdf")
註釋在任何標準檢視器中打開PDF時都會保留,包括瀏覽器<iframe>顯示。 對於Blazor應用,在伺服器上運行註釋邏輯,並將pdf.BinaryData返回給組件以顯示。
如何對PDF應用密碼保護?
密碼保護限制對於敏感文件(例如財務報告或人力資源記錄)的存取。 IronPDF支持使用者密碼(開啟文件所需)和所有者密碼(更改權限所需)。 PDF安全指南列出了所有可用的權限標誌。
using IronPdf;
var renderer = new ChromePdfRenderer();
var pdf = await renderer.RenderHtmlAsPdfAsync("<h1>Confidential Report</h1>");
// Set the password required to open the document
pdf.Password = "user-open-password";
// Set the owner password to control editing and printing rights
pdf.SecuritySettings.OwnerPassword = "owner-edit-password";
pdf.SecuritySettings.AllowUserPrinting = IronPdf.Security.PdfPrintSecurity.FullPrintRights;
pdf.SecuritySettings.AllowUserCopyPasteContent = false;
pdf.SaveAs("protected-report.pdf");
using IronPdf;
var renderer = new ChromePdfRenderer();
var pdf = await renderer.RenderHtmlAsPdfAsync("<h1>Confidential Report</h1>");
// Set the password required to open the document
pdf.Password = "user-open-password";
// Set the owner password to control editing and printing rights
pdf.SecuritySettings.OwnerPassword = "owner-edit-password";
pdf.SecuritySettings.AllowUserPrinting = IronPdf.Security.PdfPrintSecurity.FullPrintRights;
pdf.SecuritySettings.AllowUserCopyPasteContent = false;
pdf.SaveAs("protected-report.pdf");
Imports IronPdf
Dim renderer As New ChromePdfRenderer()
Dim pdf = Await renderer.RenderHtmlAsPdfAsync("<h1>Confidential Report</h1>")
' Set the password required to open the document
pdf.Password = "user-open-password"
' Set the owner password to control editing and printing rights
pdf.SecuritySettings.OwnerPassword = "owner-edit-password"
pdf.SecuritySettings.AllowUserPrinting = IronPdf.Security.PdfPrintSecurity.FullPrintRights
pdf.SecuritySettings.AllowUserCopyPasteContent = False
pdf.SaveAs("protected-report.pdf")
密碼保護的PDF在瀏覽器<iframe>中顯示密碼提示。 此方法適用於通過下載分發的文件; 如需無提示內嵌顯示,僅對通過下載路線返回的文件應用密碼。
如何顯示使用者上傳的PDF?
顯示使用者上傳的PDF需要讀取進來的文件字元流並將其編碼為資料URI。 下面的上傳組件使用Blazor的InputFile控制來捕獲文件,然後直接顯示內容而無需重新渲染:
@page "/upload-viewer"
@using IronPdf
<h3>Upload and View a PDF</h3>
<InputFile OnChange="LoadUploadedPdf" accept=".pdf" />
@if (!string.IsNullOrEmpty(pdfDataUri))
{
<iframe src="@pdfDataUri" style="width:100%; height:600px; margin-top:20px;"></iframe>
}
@code {
private string pdfDataUri = string.Empty;
private async Task LoadUploadedPdf(InputFileChangeEventArgs e)
{
using var stream = e.File.OpenReadStream(maxAllowedSize: 10 * 1024 * 1024);
using var ms = new MemoryStream();
await stream.CopyToAsync(ms);
var bytes = ms.ToArray();
// Encode the uploaded PDF bytes directly for display
pdfDataUri = $"data:application/pdf;base64,{Convert.ToBase64String(bytes)}";
}
}
對於需要在顯示之前進行伺服器端處理(如加水印、頁面提取或重新加密)的上傳PDF,首先將字元流載入到PdfDocument中:
var pdf = new PdfDocument(bytes);
// Apply operations, then re-encode
pdfDataUri = $"data:application/pdf;base64,{Convert.ToBase64String(pdf.BinaryData)}";
var pdf = new PdfDocument(bytes);
// Apply operations, then re-encode
pdfDataUri = $"data:application/pdf;base64,{Convert.ToBase64String(pdf.BinaryData)}";
Dim pdf As New PdfDocument(bytes)
' Apply operations, then re-encode
pdfDataUri = $"data:application/pdf;base64,{Convert.ToBase64String(pdf.BinaryData)}"
這保持相同的組件結構,同時在上傳文件上啟用完整的IronPDF API。
下一步該怎麼做?
本指南涵蓋了使用IronPDF的Blazor PDF檢視器的完整工作流:在.NET 10上安裝、URL和HTML渲染、頁首和頁尾的輸出自定義、JavaScript互操作實現瀏覽器下載、Blazor Server和Blazor WebAssembly之間的架構差異以及四個文件操作:合併、註釋、密碼保護和使用者上傳。
要擴展此基礎,可以瀏覽這些資源:
- HTML到PDF教程:高級渲染、CSS媒體查詢和JavaScript執行策略
- PDF權限和密碼:完整的安全設置和權限標誌
- 合併和拆分PDF:頁面級文件組裝和拆分
- 水印指南:生成文件的文字和圖像水印
- IronPDF API參考:完整的類和方法文件
獲取免費的試用授權以移除水印並在您的Blazor應用程式中測試IronPDF。 IronPDF支持[.NET 10]()、ASP.NET Core、Blazor Server和託管的Blazor WebAssembly專案而無需額外配置。 如需更多整合指導,請參閱Microsoft的官方Blazor文件。
常見問題
什麼是Blazor PDF查看器?
Blazor PDF查看器是一個將PDF文件內嵌顯示在Blazor Server或WebAssembly應用程式中的組件。通常將PDF字節轉換為base64資料URI,並在iframe元素內渲染,為使用者提供內建瀏覽器工具欄進行縮放、導航和列印。
如何在Blazor Server應用程式中顯示PDF?
通過NuGet安裝IronPDF,將您的授權金鑰新增到Program.cs,然後使用ChromePdfRenderer從URL或HTML字串生成PDF字節。將字節編碼為base64資料URI,並將其分配給您的Razor組件中iframe的src屬性。
IronPDF可以在Blazor WebAssembly項目中運行嗎?
IronPDF的渲染引擎需要本機二進制文件,無法在瀏覽器的WASM沙箱中運行。對於Blazor WebAssembly項目,請建立一個伺服器端ASP.NET Core API端點,使用IronPDF生成PDF並返回字節。WASM客戶端通過HttpClient調用此端點並顯示結果。
如何在Blazor中觸發PDF下載?
將IJSRuntime注入到您的組件中,使用IronPDF生成PDF字節,將其包裝在DotNetStreamReference中,並使用InvokeVoidAsync調用JavaScript函式。JavaScript函式建立了一個Blob URL,並觸發點擊錨點元素以觸發瀏覽器下載。
使用IronPDF進行Blazor PDF檢視有哪些好處?
IronPDF使用Chrome渲染引擎,能夠準確將HTML、CSS和JavaScript輸出轉換為PDF格式。支持.NET 10,適用於Blazor Server和WebAssembly架構,提供單一API用於PDF生成、合併、註釋、密碼保護和使用者上傳處理。
如何在生成的Blazor PDF中新增標題和頁腳?
在調用渲染方法之前,設置ChromePdfRenderer的RenderingOptions屬性。對於純文字標題和頁腳,使用TextHeader和TextFooter與模板變數如{page}、{total-pages}和{date}。對於HTML佈局,改用HtmlHeader和HtmlFooter。
如何在Blazor中合併多個PDF文件?
使用ChromePdfRenderer將每個文件生成為PdfDocument實例,然後調用PdfDocument.Merge(pdf1, pdf2)以合併它們。將合併文件的BinaryData傳遞給Blazor組件的base64資料URI以顯示合併結果。
能否在Blazor中顯示使用者上傳的PDF而不將其保存到磁碟?
可以。使用Blazor的InputFile組件將上傳的文件讀取到MemoryStream中,將字節轉換為base64資料URI,並分配給iframe的src屬性。無需寫入文件系統。對於伺服器端處理,將字節載入到PdfDocument實例中然後編碼。
如何為Blazor生成的PDF應用密碼保護?
生成PdfDocument後,為使用者打開密碼設置Password屬性,並使用SecuritySettings.OwnerPassword設置擁有者密碼。使用SecuritySettings.AllowUserPrinting和AllowUserCopyPasteContent控制權限,然後保存或編碼文件。
IronPDF是否與Blazor PDF查看器項目中的.NET 10相容?
是的。IronPDF支持.NET 10、.NET 9、.NET 8、.NET 6及.NET Framework 4.6.2及更高版本。無需特殊配置即可在以.NET 10為目標的Blazor應用中使用IronPDF。




