跳過到頁腳內容
使用IRONPDF

如何在 Blazor 中顯示 PDF(指南)

介紹

Blazor 在現代 Web 應用程式中顯示 PDF 功能需要一個功能強大的 PDF 檢視器元件,該元件的功能遠遠超出瀏覽器的基本功能。 對於建立 Blazor 應用程式的 .NET 開發人員來說, IronPDF提供了一個強大的 PDF 檢視器解決方案,可與您的Blazor Server 應用程式無縫整合。 這樣,您無需依賴第三方瀏覽器工具,即可高效能、高功能地顯示 PDF 文件。

在本教程中,我們將探索如何使用 IronPDF 實現 Blazor PDF 檢視器,建立一個 PDF 檢視器元件,該元件可以開啟 PDF 檔案、處理 PDF 內容,並為使用者提供直覺的介面,以便在桌面和行動裝置上顯示 PDF。

IronPDF 開始顯示 PDF

在實作 Blazor PDF 檢視器之前,您需要安裝 IronPDF。 透過 NuGet 將其新增至 Blazor Server 應用程式:

Install-Package IronPdf

接下來,建立一個新的 Blazor 應用程序,並確保已安裝最新版本的 .NET Core。 將您的 PDF 文件儲存在 wwwroot 資料夾中以便輕鬆訪問,或準備從其他來源(如位元組數組或 URL)加載它們。

建立您的第一個 Blazor PDF 檢視器元件

讓我們建立一個基本的 Blazor PDF 檢視器元件,它可以顯示 PDF 文件。 首先,建立一個新的 Razor 元件:

@page "/pdfviewer"
@rendermode InteractiveServer
@using IronPdf
@inject IJSRuntime JSRuntime
@inject Microsoft.AspNetCore.Hosting.IWebHostEnvironment WebHostEnvironment
<h3>PDF Viewer Component</h3>
<div>
    <button @onclick="LoadPdfDocument">Open File</button>
    <div id="pdfContainer">
        @if (!string.IsNullOrEmpty(pdfUrl))
        {
            <iframe src="@pdfUrl" style="width:100%; height:600px;"></iframe>
        }
    </div>
</div>
@code {
    private string pdfUrl = "";
    private byte[] pdfData;
    private async Task LoadPdfDocument()
    {
        // Load PDF from file
        var pdfDocument = PdfDocument.FromFile("wwwroot/sample.pdf");
        pdfData = pdfDocument.BinaryData;
        // Create object URL for display
        pdfUrl = await CreateObjectUrl(pdfData);
    }
    private async Task<string> CreateObjectUrl(byte[] data)
    {
        var base64 = Convert.ToBase64String(data);
        return $"data:application/pdf;base64,{base64}";
    }
}
@page "/pdfviewer"
@rendermode InteractiveServer
@using IronPdf
@inject IJSRuntime JSRuntime
@inject Microsoft.AspNetCore.Hosting.IWebHostEnvironment WebHostEnvironment
<h3>PDF Viewer Component</h3>
<div>
    <button @onclick="LoadPdfDocument">Open File</button>
    <div id="pdfContainer">
        @if (!string.IsNullOrEmpty(pdfUrl))
        {
            <iframe src="@pdfUrl" style="width:100%; height:600px;"></iframe>
        }
    </div>
</div>
@code {
    private string pdfUrl = "";
    private byte[] pdfData;
    private async Task LoadPdfDocument()
    {
        // Load PDF from file
        var pdfDocument = PdfDocument.FromFile("wwwroot/sample.pdf");
        pdfData = pdfDocument.BinaryData;
        // Create object URL for display
        pdfUrl = await CreateObjectUrl(pdfData);
    }
    private async Task<string> CreateObjectUrl(byte[] data)
    {
        var base64 = Convert.ToBase64String(data);
        return $"data:application/pdf;base64,{base64}";
    }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

這段程式碼創建了一個簡單的 PDF 檢視器元件,該元件會載入 PDF 文件並使用 iframe 顯示它。 LoadPdfDocument 方法從相同路徑(wwwroot 資料夾)讀取 PDF 文件,並將其轉換為位元組陣列。 CreateObjectUrl 方法隨後將此位元組陣列轉換為 iframe 可以顯示的資料 URL,使用戶能夠輕鬆查看已載入的 PDF 文件。

輸出

如何在 Blazor 中顯示 PDF 檔案(指南):圖 1

實作 JavaScript 互通以增強顯示效果

為了更好地控制PDF內容的顯示,我們可以使用JavaScript函數來處理PDF檢視器的功能:

@page "/pdf-jsinterop"
@rendermode InteractiveServer
@using IronPdf
@inject IJSRuntime JSRuntime
@inject Microsoft.AspNetCore.Hosting.IWebHostEnvironment WebHostEnvironment
<h3>IronPDF JavaScript Interop Viewer</h3>
<p>Displays PDF using JavaScript's Blob/ObjectURL capabilities.</p>
@if (!string.IsNullOrEmpty(ErrorMessage))
{
    <div class="alert alert-danger">Error: @ErrorMessage</div>
}
<div id="@documentId" style="border: 1px solid #ccc; width: 100%; min-height: 600px;">
    Loading PDF...
</div>
@code {
    private string documentId = Guid.NewGuid().ToString();
    private string ErrorMessage = string.Empty;
    private bool pdfLoaded = false;
    // Hold the reference to the loaded JavaScript module
    private IJSObjectReference? jsModule;
    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender && !pdfLoaded)
        {
            try
            {
                // 1. Asynchronously load the JavaScript file as a module
                // This guarantees the script is loaded before the next line executes.
                jsModule = await JSRuntime.InvokeAsync<IJSObjectReference>("import",
                    "./pdfViewerInterop.js");
                await LoadPdfWithJavaScript();
                pdfLoaded = true;
            }
            catch (Exception ex)
            {
                ErrorMessage = $"Failed to load JS module or execute: {ex.Message}";
            }
            finally
            {
                StateHasChanged();
            }
        }
    }
    private async Task LoadPdfWithJavaScript()
    {
        if (jsModule is null) return; // Should never happen if the module loads successfully
        try
        {
            var pdfPath = Path.Combine(WebHostEnvironment.WebRootPath, "sample.pdf");
            if (!File.Exists(pdfPath))
            {
                ErrorMessage = $"File not found: {pdfPath}";
                return;
            }
            var pdf = PdfDocument.FromFile(pdfPath);
            var stream = new MemoryStream(pdf.BinaryData);
            // 2. Invoke the function using the module reference
            // Note: We only pass the function name here.
            await jsModule.InvokeVoidAsync("displayPdf",
                documentId, stream.ToArray());
        }
        catch (Exception ex)
        {
            ErrorMessage = $"Failed to load PDF or invoke JS: {ex.Message}";
        }
    }
    // IMPORTANT: Dispose of the module when the component is removed
    public async ValueTask DisposeAsync()
    {
        if (jsModule is not null)
        {
            await jsModule.DisposeAsync();
        }
    }
}
@page "/pdf-jsinterop"
@rendermode InteractiveServer
@using IronPdf
@inject IJSRuntime JSRuntime
@inject Microsoft.AspNetCore.Hosting.IWebHostEnvironment WebHostEnvironment
<h3>IronPDF JavaScript Interop Viewer</h3>
<p>Displays PDF using JavaScript's Blob/ObjectURL capabilities.</p>
@if (!string.IsNullOrEmpty(ErrorMessage))
{
    <div class="alert alert-danger">Error: @ErrorMessage</div>
}
<div id="@documentId" style="border: 1px solid #ccc; width: 100%; min-height: 600px;">
    Loading PDF...
</div>
@code {
    private string documentId = Guid.NewGuid().ToString();
    private string ErrorMessage = string.Empty;
    private bool pdfLoaded = false;
    // Hold the reference to the loaded JavaScript module
    private IJSObjectReference? jsModule;
    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender && !pdfLoaded)
        {
            try
            {
                // 1. Asynchronously load the JavaScript file as a module
                // This guarantees the script is loaded before the next line executes.
                jsModule = await JSRuntime.InvokeAsync<IJSObjectReference>("import",
                    "./pdfViewerInterop.js");
                await LoadPdfWithJavaScript();
                pdfLoaded = true;
            }
            catch (Exception ex)
            {
                ErrorMessage = $"Failed to load JS module or execute: {ex.Message}";
            }
            finally
            {
                StateHasChanged();
            }
        }
    }
    private async Task LoadPdfWithJavaScript()
    {
        if (jsModule is null) return; // Should never happen if the module loads successfully
        try
        {
            var pdfPath = Path.Combine(WebHostEnvironment.WebRootPath, "sample.pdf");
            if (!File.Exists(pdfPath))
            {
                ErrorMessage = $"File not found: {pdfPath}";
                return;
            }
            var pdf = PdfDocument.FromFile(pdfPath);
            var stream = new MemoryStream(pdf.BinaryData);
            // 2. Invoke the function using the module reference
            // Note: We only pass the function name here.
            await jsModule.InvokeVoidAsync("displayPdf",
                documentId, stream.ToArray());
        }
        catch (Exception ex)
        {
            ErrorMessage = $"Failed to load PDF or invoke JS: {ex.Message}";
        }
    }
    // IMPORTANT: Dispose of the module when the component is removed
    public async ValueTask DisposeAsync()
    {
        if (jsModule is not null)
        {
            await jsModule.DisposeAsync();
        }
    }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

將此 JavaScript 函數新增至 wwwroot 資料夾中的 JavaScript 檔案:

export function displayPdf(elementId, data) {
    // 1. Create a Blob from the byte array data
    const blob = new Blob([new Uint8Array(data)],
        { type: 'application/pdf' });
    // 2. Create a temporary URL for the Blob
    const url = URL.createObjectURL(blob);
    // 3. Find the container element
    const container = document.getElementById(elementId);
    if (!container) return;
    // 4. Clear any previous content
    container.innerHTML = '';
    // 5. Create and configure the iframe
    const iframe = document.createElement('iframe');
    iframe.src = url;
    iframe.style.width = '100%';
    iframe.style.height = '600px';
    iframe.style.border = 'none';
    // 6. Append the iframe to the container
    container.appendChild(iframe);
}
export function displayPdf(elementId, data) {
    // 1. Create a Blob from the byte array data
    const blob = new Blob([new Uint8Array(data)],
        { type: 'application/pdf' });
    // 2. Create a temporary URL for the Blob
    const url = URL.createObjectURL(blob);
    // 3. Find the container element
    const container = document.getElementById(elementId);
    if (!container) return;
    // 4. Clear any previous content
    container.innerHTML = '';
    // 5. Create and configure the iframe
    const iframe = document.createElement('iframe');
    iframe.src = url;
    iframe.style.width = '100%';
    iframe.style.height = '600px';
    iframe.style.border = 'none';
    // 6. Append the iframe to the container
    container.appendChild(iframe);
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

此 JavaScript 函數從 PDF 資料建立一個 blob,並產生一個物件 URL。 然後,它會動態建立一個 iframe 元素並將其新增到容器中。 這種方法可以讓你更能控制 PDF 頁面的顯示方式,並且更能管理 PDF 檢視器元件的生命週期。

輸出

如何在 Blazor 中顯示 PDF(指南):圖 2 - JavaScript PDF 檢視器

從不同來源載入 PDF 文件

Blazor PDF 檢視器可以從各種來源檢索和顯示 PDF 文件:

private async Task LoadFromUrl()
{
    var client = new HttpClient();
    var response = await client.GetAsync("https://example.com/file.pdf");
    var stream = await response.Content.ReadAsStreamAsync();
    var pdfDocument = new PdfDocument(stream);
    await DisplayPdfContent(pdfDocument);
}
private async Task LoadFromHtmlContent()
{
    var renderer = new ChromePdfRenderer();
    var htmlContent = "<h1>Generated PDF</h1>";
    var pdfDocument = renderer.RenderHtmlAsPdf(htmlContent);
    await DisplayPdfContent(pdfDocument);
}
private async Task DisplayPdfContent(PdfDocument document)
{
    var data = document.BinaryData;
    pdfUrl = $"data:application/pdf;base64,{Convert.ToBase64String(data)}";
}
private async Task LoadFromUrl()
{
    var client = new HttpClient();
    var response = await client.GetAsync("https://example.com/file.pdf");
    var stream = await response.Content.ReadAsStreamAsync();
    var pdfDocument = new PdfDocument(stream);
    await DisplayPdfContent(pdfDocument);
}
private async Task LoadFromHtmlContent()
{
    var renderer = new ChromePdfRenderer();
    var htmlContent = "<h1>Generated PDF</h1>";
    var pdfDocument = renderer.RenderHtmlAsPdf(htmlContent);
    await DisplayPdfContent(pdfDocument);
}
private async Task DisplayPdfContent(PdfDocument document)
{
    var data = document.BinaryData;
    pdfUrl = $"data:application/pdf;base64,{Convert.ToBase64String(data)}";
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

這些方法示範如何使用 HTTPS 從 URL 載入 PDF 檔案、如何將 HTML 內容轉換為 PDF 以及如何顯示產生的 PDF 內容。 LoadFromUrl 方法從遠端位置檢索 PDF 文檔,而 LoadFromHtmlContent 則展示瞭如何動態地將 HTML 轉換為 PDF,從而為 Blazor PDF 檢視器元件獲取其內容的方式提供了靈活性。

使用 HTML 內容輸出

如何在 Blazor 中顯示 PDF(指南):圖 3 - 由 HTML 產生並顯示的 PDF

新增互動功能

透過互動功能增強您的 PDF 檢視器:

@code {
    private int currentPage = 1;
    private int totalPages;
    private string rotationClass = "";
    private async Task NavigateToPage(int page)
    {
        currentPage = page;
        await JSRuntime.InvokeVoidAsync("navigateTo", page);
    }
    private void RotateCounterclockwise()
    {
        // Counterclockwise switch orientation
        rotationClass = "rotate-270";
    }
    private async Task PrintPdf()
    {
        await JSRuntime.InvokeVoidAsync("printDocument", documentId);
    }
    private async Task DownloadPdf()
    {
        var fileName = "document.pdf";
        await JSRuntime.InvokeVoidAsync("downloadFile", 
           pdfData, fileName);
    }
}
@code {
    private int currentPage = 1;
    private int totalPages;
    private string rotationClass = "";
    private async Task NavigateToPage(int page)
    {
        currentPage = page;
        await JSRuntime.InvokeVoidAsync("navigateTo", page);
    }
    private void RotateCounterclockwise()
    {
        // Counterclockwise switch orientation
        rotationClass = "rotate-270";
    }
    private async Task PrintPdf()
    {
        await JSRuntime.InvokeVoidAsync("printDocument", documentId);
    }
    private async Task DownloadPdf()
    {
        var fileName = "document.pdf";
        await JSRuntime.InvokeVoidAsync("downloadFile", 
           pdfData, fileName);
    }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

這段程式碼加入了在 PDF 頁面之間導航、旋轉功能(包括逆時針切換方向)以及列印 PDF 的功能。 下載功能允許使用者將 PDF 檔案儲存到本機。 這些功能將您的基本 PDF 檢視器轉變為強大的 PDF 檢視器,內建工具列可為處理 PDF 文件的使用者提供基本功能。

輸出

如何在 Blazor 中顯示 PDF(指南):圖 4 - 具有自訂互動功能的 PDF 檢視器

處理PDF表單填寫和註釋

對於具有表單欄位和註釋的 PDF 文檔,IronPDF 提供強大的支援:

private async Task ProcessFormFields(
{
    var pdfDocument = PdfDocument.FromFile("form.pdf");
    foreach (var field in pdfDocument.Form.Fields)
    {
        if (field.Type == PdfFormFieldType.Text)
        {
            field.Value = "User Input";
        }
    }
    // Enable form filling in viewer
    var modifiedPdf = pdfDocument.BinaryData;
    await DisplayPdfContent(pdfDocument);
}
private async Task ProcessFormFields(
{
    var pdfDocument = PdfDocument.FromFile("form.pdf");
    foreach (var field in pdfDocument.Form.Fields)
    {
        if (field.Type == PdfFormFieldType.Text)
        {
            field.Value = "User Input";
        }
    }
    // Enable form filling in viewer
    var modifiedPdf = pdfDocument.BinaryData;
    await DisplayPdfContent(pdfDocument);
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

這樣,您就可以在 Blazor PDF 檢視器元件中啟用表單填寫功能,允許使用者直接在瀏覽器中與表單欄位互動。 該程式碼遍歷 PDF 文件中的表單字段,並能以程式設計方式設定值,因此非常適合需要動態表單填入的應用程式。

輸出

如何在 Blazor 中顯示 PDF(指南):圖 5 - 顯示帶有表單填寫的 PDF

效能最佳化

為了確保在顯示 PDF 文件時(尤其是顯示大型 PDF 文件時)擁有高效能:

private async Task LoadLargePdf()
{
    const int chunkSize = 1024 * 1024; // 1MB chunks
    var pdfPath = "largefile.pdf";
    using (var fileStream = File.OpenRead(pdfPath))
    {
        var buffer = new byte[chunkSize];
        var chunks = new List<byte[]>();
        int bytesRead;
        while ((bytesRead = await fileStream.ReadAsync(buffer)) > 0)
        {
            var chunk = new byte[bytesRead];
            Array.Copy(buffer, chunk, bytesRead);
            chunks.Add(chunk);
        }
        // Process chunks for display
        await ProcessPdfChunks(chunks);
    }
}
private async Task LoadLargePdf()
{
    const int chunkSize = 1024 * 1024; // 1MB chunks
    var pdfPath = "largefile.pdf";
    using (var fileStream = File.OpenRead(pdfPath))
    {
        var buffer = new byte[chunkSize];
        var chunks = new List<byte[]>();
        int bytesRead;
        while ((bytesRead = await fileStream.ReadAsync(buffer)) > 0)
        {
            var chunk = new byte[bytesRead];
            Array.Copy(buffer, chunk, bytesRead);
            chunks.Add(chunk);
        }
        // Process chunks for display
        await ProcessPdfChunks(chunks);
    }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

這種方法分塊載入大型 PDF 文件,防止記憶體問題,即使處理大型 PDF 文件也能確保流暢的效能。 在手機或資源有限的設備上處理 PDF 文件時,它尤其有用。

Blazor應用程式的安全注意事項

處理受密碼保護的PDF檔案時:

private async Task LoadSecurePdf(string password)
{
    var pdfDocument = PdfDocument.FromFile("secure.pdf", password);
    if (pdfDocument != null)
    {
       var headers = new Dictionary<string, string>
        {
            {"X-Frame-Options", "SAMEORIGIN"},
            {"Content-Security-Policy", "default-src 'self'"}
        };
        await DisplayPdfContent(pdfDocument);
    }
}
private async Task LoadSecurePdf(string password)
{
    var pdfDocument = PdfDocument.FromFile("secure.pdf", password);
    if (pdfDocument != null)
    {
       var headers = new Dictionary<string, string>
        {
            {"X-Frame-Options", "SAMEORIGIN"},
            {"Content-Security-Policy", "default-src 'self'"}
        };
        await DisplayPdfContent(pdfDocument);
    }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

此程式碼示範如何在保持安全性的同時,透過正確的標頭配置來載入受密碼保護的 PDF 文件。

結論

使用 IronPDF 實作 Blazor PDF 檢視器,可為開發人員提供一個全面的解決方案,用於在 Web 應用程式中顯示 PDF 檔案。 從基本顯示到表單填寫和註釋等高級功能,IronPDF 的 PDF 檢視器元件提供了專業應用程式所需的功能。

所示範例示範如何建立一個強大的 Blazor PDF 檢視器,它可以處理各種 PDF 來源,提供互動式功能,並保持高效能。 無論您是建立簡單的文件檢視器還是複雜的文件管理系統,IronPDF 與 Blazor Server 應用程式的整合都能輕鬆實現專業的 PDF 檢視功能。

準備好實現您自己的 PDF 檢視器了嗎? 立即開始 IronPDF 的免費試用,即可存取完整的文件、演示應用程式和開發者支持,從而在您的 Blazor 應用程式中創建強大的 PDF 查看體驗。

常見問題解答

如何使用 IronPDF 在 Blazor 應用程式中顯示 PDF?

IronPDF 提供全面的 API,可讓您在 Blazor 應用程式中渲染並顯示 PDF。透過整合 IronPDF,您可以輕鬆實作功能強大的 PDF 檢視器元件。

使用 IronPDF 檢視 Blazor PDF 有什麼好處?

使用 IronPDF 進行 Blazor PDF 檢視可提供多種優點,例如處理表單欄、建立互動式檢視器,以及在您的應用程式中無縫呈現高品質的 PDF。

是否可以在 Blazor 中使用 IronPDF 處理 PDF 中的表單欄位?

是的,IronPDF 允許您在 Blazor 應用程式中處理和操作 PDF 文件中的表單欄位,提供增強的互動性和使用者參與度。

IronPDF 是否可用於在 Blazor 中建立互動式 PDF 檢視器?

絕對可以。IronPDF 提供在 Blazor 中建立互動式 PDF 檢視器的工具,可實現表單處理和動態內容顯示等功能。

IronPDF 為 Blazor 中的 PDF 處理提供哪些功能?

IronPDF 提供 PDF 渲染、表單欄位處理、文字萃取和頁面處理等功能,使其成為 Blazor 中 PDF 操作的多功能選擇。

IronPDF 如何增強 Blazor 應用程式中的 PDF 檢視體驗?

IronPDF 可提供流暢的渲染、互動功能以及強大的 PDF 文件處理能力,從而增強 Blazor 應用程式中的 PDF 檢視體驗。

Curtis Chau
技術作家

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

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