跳過到頁腳內容
使用IRONPDF

如何使用IronPDF構建Blazor PDF檢視器

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?

開始使用需要安裝 NuGet 套件並將許可證金鑰新增至 Program.cs。 從軟體包管理器控制台安裝 IronPDF:

Install-Package IronPdf

或者,在 NuGet 套件管理器 UI 中搜尋"IronPdf",然後選擇最新版本。

!{--010011000100100101000010010100100100000101010010010110010101111101001110010101010101010101010101010101010101010 0100010111110100100101001101010100010000010100110001001100010111110100001001001100010011110010101010

安裝完成後,在進行任何 PDF 操作之前,請將您的許可證金鑰新增至 Program.cs

IronPdf.License.LicenseKey = "YOUR-LICENSE-KEY-HERE";
IronPdf.License.LicenseKey = "YOUR-LICENSE-KEY-HERE";
IronPdf.License.LicenseKey = "YOUR-LICENSE-KEY-HERE"
$vbLabelText   $csharpLabel

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 取得網頁並將其轉換為 PDF 格式,使用與 Google Chrome 相同的Chrome 渲染引擎,忠實保留 CSS、JavaScript 輸出和佈局。

剃刀組件方法

以下 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
$vbLabelText   $csharpLabel

RenderUrlAsPdfAsync 取得頁面,執行所有 JavaScript,套用 CSS,並傳回一個包含渲染輸出的 PdfDocument 物件。 BinaryData 屬性公開原始 PDF 位元組,用於儲存、串流或顯示。 <iframe> 顯示輸出時,內建瀏覽器工具列可用於縮放、導覽和列印。

如何使用 IronPDF 建立 Blazor PDF 檢視器:圖 1 - PDF 檢視器輸出的 URL

如何自訂PDF生成?

IronPDF 透過 ChromePdfRenderOptions 類別提供輸出控制。 您可以設定紙張大小、調整頁邊距,並為每一頁新增文字或 HTML 頁首和頁尾。 渲染選項指南涵蓋了所有可用屬性的完整清單。

剃刀組件方法

以下組件為 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")
$vbLabelText   $csharpLabel

範本變數(包括 {page}{total-pages}{date})會在渲染時被替換為實際值。對於複雜的品牌佈局,請使用 HtmlHeaderHtmlFooter 屬性,而不是 TextHeaderTextFooter頁首和頁尾指南包含了兩種方法的完整範例。

如何使用 IronPDF 建立 Blazor PDF 檢視器:圖 2 - 在 PDF 檢視器中開啟的自訂 PDF

啟用 PDF 下載的最佳方法是什麼?

<iframe> 中顯示 PDF 檔案可以處理查看,但使用者通常需要下載檔案。 JavaScript 互通性會觸發瀏覽器從 .NET 位元組流下載檔案。 如需更多下載和匯出圖案,請參閱匯出和儲存 PDF 指南

剃刀組件方法

IJSRuntime 注入到元件中,並呼叫 JavaScript 輔助函數來啟動下載。 DotNetStreamReference 會串流 PDF 位元組,而不會一次將整個檔案載入到 JavaScript 記憶體中:

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

依照微軟 Blazor JavaScript 互通文件中的說明,將此 JavaScript 函數新增至您的 _Host.cshtmlApp.razor 檔案:

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);
};
JAVASCRIPT

頂級 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)
$vbLabelText   $csharpLabel

如何從 Razor 元件產生 PDF?

從 HTML 產生 PDF 可以完全控制佈局、資料綁定和樣式。 這種方法適用於發票、報告以及任何基於即時應用程式資料產生的文件。 有關更進階的渲染技術,請參閱HTML 轉 PDF 轉換指南

剃刀組件方法

以下元件根據 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>$749</td><td>$749</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>$749</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>$749</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>$749</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")
$vbLabelText   $csharpLabel

RenderHtmlAsPdfAsync 接受任何有效的 HTML 字串,包括內嵌 CSS 和嵌入式 JavaScript。 此實作方式可自動處理版面配置、字體渲染和分頁符號。

如何使用 IronPDF 建立 Blazor PDF 檢視器:圖 3 - 檢視器中的發票 PDF

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)
$vbLabelText   $csharpLabel

在 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")
$vbLabelText   $csharpLabel

若要在 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")
$vbLabelText   $csharpLabel

當 PDF 檔案在任何標準檢視器(包括瀏覽器顯示)中開啟時,註釋都會被保留。 對於 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")
$vbLabelText   $csharpLabel

受密碼保護的 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)}"
$vbLabelText   $csharpLabel

這樣既能保持元件結構不變,又能對上傳的文件啟用完整的 IronPDF API。

接下來我該怎麼做?

本指南涵蓋了使用 IronPDF 建立 Blazor PDF 檢視器的完整工作流程:在 .NET 10 上安裝、URL 和 HTML 渲染、使用頁首和頁腳自訂輸出、用於瀏覽器下載的 JavaScript 互通、Blazor Server 和 Blazor WebAssembly 之間的架構差異,以及四種文件操作:使用者合併、組合註釋、密碼保護和使用者合併。

為了進一步拓展這項基礎,請探索以下資源:

取得免費試用許可證,即可移除浮水印並在 Blazor 應用程式中測試 IronPDF。 IronPDF 支援.NET 10 、ASP.NET Core、Blazor Server 和託管的 Blazor WebAssembly 項目,無需額外配置。 如需更多整合指導,請參閱微軟官方 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端點來生成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是否相容於.NET 10的Blazor PDF檢視器專案?

是的。IronPDF支持.NET 10、.NET 9、.NET 8、.NET 6及.NET Framework 4.6.2及更新版本。在針對.NET 10的Blazor應用中使用IronPDF無需特別配置。

Curtis Chau
技術作家

Curtis Chau 擁有卡爾頓大學計算機科學學士學位,專注於前端開發,擅長於 Node.js、TypeScript、JavaScript 和 React。Curtis 熱衷於創建直觀且美觀的用戶界面,喜歡使用現代框架並打造結構良好、視覺吸引人的手冊。

除了開發之外,Curtis 對物聯網 (IoT) 有著濃厚的興趣,探索將硬體和軟體結合的創新方式。在閒暇時間,他喜愛遊戲並構建 Discord 機器人,結合科技與創意的樂趣。

鋼鐵支援團隊

我們每週 5 天,每天 24 小時在線上。
聊天
電子郵件
打電話給我