跳至頁尾內容
使用IRONPDF

HtmlToPdfDocument C# - DinkToPdf 替代軟體 | IronPDF

在Blazor應用程式中顯示PDF,請使用IronPDF的PDF檢視器元件,這個元件可以與Blazor Server應用程式整合,提供高效能的PDF渲染功能,如表單填寫、註解和移動支援,而不依賴第三方瀏覽器工具。

為什麼Blazor應用程式需要一個專用的PDF檢視器?

在現代網頁應用程式中顯示PDF需要超越基本瀏覽器能力的一個可靠檢視器元件。 對於構建Blazor應用程式的.NET開發者,IronPDF提供了一個有效的PDF檢視器解決方案,可以與您的Blazor Server應用程式整合。 這使得在不依賴第三方瀏覽器工具的情況下達成高效能PDF渲染及豐富功能成為可能。

原生瀏覽器對PDF的支援在不同的瀏覽器和平臺之間差異很大,導致不一致的使用者體驗。 通過在您的Blazor應用程式中實施自定義PDF檢視器,您可以完全控制檢視體驗,確保在所有平臺上的一致功能。 這對於需要遵循合規標準和高級安全功能的應用程式尤為重要。

Blazor框架——基於微軟ASP.NET Core之上——允許以組件為基礎的開發,自然地與PDF處理庫配合。 而不是從外部CDN嵌入第三方檢視器小工具,您可以構建一個符合您應用程式精確需求的元件。

如何在Blazor專案中安裝IronPDF?

在實施Blazor PDF檢視器之前,安裝IronPDF。 透過NuGet將其新增到您的Blazor Server應用程式中,可以使用套件管理器主控台或.NET CLI:

Install-Package IronPdf
dotnet add package IronPdf

接下來,建立一個新的Blazor應用程式,並確保已安裝最新版本的.NET。 將PDF檔案儲存在wwwroot資料夾中以便輕鬆存取,或者從其他來源載入,如位元組陣列或URL。 安裝概覽為各種部署場景提供詳細指導。

需要哪些先決條件?

要成功實作Blazor PDF檢視器,請確保您擁有:

  • 在您的開發機器上安裝.NET 10
  • Visual Studio 2022或帶有C#擴展的Visual Studio Code
  • IronPDF授權金鑰(可通過免費試用獲得)
  • 對Blazor元件結構的基本理解
  • 用於測試的範例PDF檔案(將其放在wwwroot資料夾中)

對於Windows部署,請確保您擁有相應的Visual C++運行時。Linux使用者應安裝所需的依賴項,而macOS開發者需要考慮Intel與Apple Silicon的相容性。

PDF檔案應儲存在哪裡?

PDF檔案的儲存位置極大地影響您的應用程式的性能和安全性。 對於Blazor應用程式,請考慮以下選項:

  • wwwroot資料夾:適合不含敏感資訊的靜態PDF
  • Azure Blob儲存:對於需要彈性儲存的雲端應用程式
  • 作為位元組陣列的資料庫:適合需要存取控制的小型PDF
  • 受保護的伺服器目錄:適合具有安全需求的敏感文件
  • 記憶體流:最佳化於使用HTML轉PDF動態生成的PDF

如何建立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 = Array.Empty<byte>();

    private async Task LoadPdfDocument()
    {
        var pdfDocument = PdfDocument.FromFile("wwwroot/sample.pdf");
        pdfData = pdfDocument.BinaryData;
        var base64 = Convert.ToBase64String(pdfData);
        pdfUrl = $"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 = Array.Empty<byte>();

    private async Task LoadPdfDocument()
    {
        var pdfDocument = PdfDocument.FromFile("wwwroot/sample.pdf");
        pdfData = pdfDocument.BinaryData;
        var base64 = Convert.ToBase64String(pdfData);
        pdfUrl = $"data:application/pdf;base64,{base64}";
    }
}
Imports IronPdf
Imports Microsoft.AspNetCore.Hosting
Imports Microsoft.AspNetCore.Components
Imports Microsoft.JSInterop

@page "/pdfviewer"
@rendermode InteractiveServer

<h3>PDF Viewer Component</h3>
<div>
    <button @onclick="LoadPdfDocument">Open File</button>
    <div id="pdfContainer">
        @If Not String.IsNullOrEmpty(pdfUrl) Then
            <iframe src="@pdfUrl" style="width:100%; height:600px;"></iframe>
        End If
    </div>
</div>

@Code
    Private pdfUrl As String = ""
    Private pdfData As Byte() = Array.Empty(Of Byte)()

    Private Async Function LoadPdfDocument() As Task
        Dim pdfDocument = PdfDocument.FromFile("wwwroot/sample.pdf")
        pdfData = pdfDocument.BinaryData
        Dim base64 = Convert.ToBase64String(pdfData)
        pdfUrl = $"data:application/pdf;base64,{base64}"
    End Function
End Code
$vbLabelText   $csharpLabel

此程式碼建立了一個PDF檢視器元件,它載入PDF文件並使用iframe顯示它。 wwwroot資料夾中讀取PDF,並將其轉換為基座64的資料URL,這是iframe直接渲染。 這種方法很好地支援各種PDF版本,並支援國際文件的UTF-8編碼。

元件如何載入PDF檔案?

該元件使用IronPDF的文件載入功能以高效讀取PDF檔案。 當使用者單擊"開啟檔案"按鈕時,方法:

  1. 使用PdfDocument.FromFile載入PDF檔案
  2. 從載入的PDF文件中提取二進制資料
  3. 轉換成Base64格式以確保瀏覽器相容性
  4. 建立瀏覽器可以直接渲染的資料URL

這種方法確保了在不同瀏覽器之間的相容性,同時保持良好的PDF顯示性能。 該元件可以處理各種紙張大小和頁面方向

輸出

Blazor PDF檢視器元件的截圖,顯示一個帶有'何謂PDF?'內容的範例PDF,展示了導航控制、縮放選項和打開檔案按鈕。

如何使用JavaScript互操作以更好地顯示PDF?

為了更好地控制PDF內容顯示,使用JavaScript互操作來處理PDF檢視器功能。 此模式以異步方式載入JavaScript模組,並將渲染委託給瀏覽器的原生blob/URL API——這是一種非常適合Blazor的元件生命週期的技術:

@page "/pdf-jsinterop"
@rendermode InteractiveServer
@using IronPdf
@inject IJSRuntime JSRuntime
@inject Microsoft.AspNetCore.Hosting.IWebHostEnvironment WebHostEnvironment
@implements IAsyncDisposable

<h3>IronPDF JavaScript Interop Viewer</h3>
<p>Displays PDF using JavaScript 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;
    private IJSObjectReference? jsModule;

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender && !pdfLoaded)
        {
            try
            {
                jsModule = await JSRuntime.InvokeAsync<IJSObjectReference>(
                    "import", "./pdfViewerInterop.js");
                await LoadPdfWithJavaScript();
                pdfLoaded = true;
            }
            catch (Exception ex)
            {
                ErrorMessage = $"Failed to load JS module: {ex.Message}";
            }
            finally
            {
                StateHasChanged();
            }
        }
    }

    private async Task LoadPdfWithJavaScript()
    {
        if (jsModule is null) return;
        var pdfPath = Path.Combine(WebHostEnvironment.WebRootPath, "sample.pdf");
        if (!File.Exists(pdfPath))
        {
            ErrorMessage = $"File not found: {pdfPath}";
            return;
        }
        var pdf = PdfDocument.FromFile(pdfPath);
        await jsModule.InvokeVoidAsync("displayPdf", documentId, pdf.BinaryData);
    }

    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
@implements IAsyncDisposable

<h3>IronPDF JavaScript Interop Viewer</h3>
<p>Displays PDF using JavaScript 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;
    private IJSObjectReference? jsModule;

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender && !pdfLoaded)
        {
            try
            {
                jsModule = await JSRuntime.InvokeAsync<IJSObjectReference>(
                    "import", "./pdfViewerInterop.js");
                await LoadPdfWithJavaScript();
                pdfLoaded = true;
            }
            catch (Exception ex)
            {
                ErrorMessage = $"Failed to load JS module: {ex.Message}";
            }
            finally
            {
                StateHasChanged();
            }
        }
    }

    private async Task LoadPdfWithJavaScript()
    {
        if (jsModule is null) return;
        var pdfPath = Path.Combine(WebHostEnvironment.WebRootPath, "sample.pdf");
        if (!File.Exists(pdfPath))
        {
            ErrorMessage = $"File not found: {pdfPath}";
            return;
        }
        var pdf = PdfDocument.FromFile(pdfPath);
        await jsModule.InvokeVoidAsync("displayPdf", documentId, pdf.BinaryData);
    }

    public async ValueTask DisposeAsync()
    {
        if (jsModule is not null)
            await jsModule.DisposeAsync();
    }
}
Imports System
Imports System.IO
Imports System.Threading.Tasks
Imports IronPdf
Imports Microsoft.AspNetCore.Components
Imports Microsoft.AspNetCore.Components.Web
Imports Microsoft.JSInterop
Imports Microsoft.AspNetCore.Hosting

@page "/pdf-jsinterop"
@rendermode InteractiveServer

@inject IJSRuntime JSRuntime
@inject IWebHostEnvironment WebHostEnvironment
@implements IAsyncDisposable

<h3>IronPDF JavaScript Interop Viewer</h3>
<p>Displays PDF using JavaScript Blob/ObjectURL capabilities.</p>

@if Not String.IsNullOrEmpty(ErrorMessage) Then
    <div class="alert alert-danger">Error: @ErrorMessage</div>
End If

<div id="@documentId" style="border: 1px solid #ccc; width: 100%; min-height: 600px;">
    Loading PDF...
</div>

@code {
    Private documentId As String = Guid.NewGuid().ToString()
    Private ErrorMessage As String = String.Empty
    Private pdfLoaded As Boolean = False
    Private jsModule As IJSObjectReference

    Protected Overrides Async Function OnAfterRenderAsync(firstRender As Boolean) As Task
        If firstRender AndAlso Not pdfLoaded Then
            Try
                jsModule = Await JSRuntime.InvokeAsync(Of IJSObjectReference)(
                    "import", "./pdfViewerInterop.js")
                Await LoadPdfWithJavaScript()
                pdfLoaded = True
            Catch ex As Exception
                ErrorMessage = $"Failed to load JS module: {ex.Message}"
            Finally
                StateHasChanged()
            End Try
        End If
    End Function

    Private Async Function LoadPdfWithJavaScript() As Task
        If jsModule Is Nothing Then Return
        Dim pdfPath = Path.Combine(WebHostEnvironment.WebRootPath, "sample.pdf")
        If Not File.Exists(pdfPath) Then
            ErrorMessage = $"File not found: {pdfPath}"
            Return
        End If
        Dim pdf = PdfDocument.FromFile(pdfPath)
        Await jsModule.InvokeVoidAsync("displayPdf", documentId, pdf.BinaryData)
    End Function

    Public Async Function DisposeAsync() As ValueTask Implements IAsyncDisposable.DisposeAsync
        If jsModule IsNot Nothing Then
            Await jsModule.DisposeAsync()
        End If
    End Function
}
$vbLabelText   $csharpLabel

將相應的JavaScript函式新增到您的.js模組保存:

export function displayPdf(elementId, data) {
    const blob = new Blob([new Uint8Array(data)], { type: 'application/pdf' });
    const url = URL.createObjectURL(blob);
    const container = document.getElementById(elementId);
    if (!container) return;
    container.innerHTML = '';
    const iframe = document.createElement('iframe');
    iframe.src = url;
    iframe.style.width = '100%';
    iframe.style.height = '600px';
    iframe.style.border = 'none';
    container.appendChild(iframe);
}
export function displayPdf(elementId, data) {
    const blob = new Blob([new Uint8Array(data)], { type: 'application/pdf' });
    const url = URL.createObjectURL(blob);
    const container = document.getElementById(elementId);
    if (!container) return;
    container.innerHTML = '';
    const iframe = document.createElement('iframe');
    iframe.src = url;
    iframe.style.width = '100%';
    iframe.style.height = '600px';
    iframe.style.border = 'none';
    container.appendChild(iframe);
}
The provided code is JavaScript, not C#. Therefore, it cannot be directly converted to VB.NET, as VB.NET is a server-side language and JavaScript is a client-side language. If you have C# code that you need converted to VB.NET, please provide that code for conversion.
$vbLabelText   $csharpLabel

此JavaScript函式從PDF資料建立blob,生成物件URL,並將iframe附加到容器。 該技術支援JavaScript渲染和複雜文件的自定義渲染延遲。

輸出

IronPDF JavaScript互操作檢視介面展示了一個帶有'何謂PDF?'內容的PDF文件,證明了JavaScript Blob/ObjectURL PDF渲染能力

如何從多個來源載入PDF?

您的Blazor PDF檢視器可以從各種來源檢索和顯示PDF文件。 下面的例子展示了從URL和HTML內容載入:

private async Task LoadFromUrl(string url)
{
    using var client = new HttpClient();
    client.Timeout = TimeSpan.FromSeconds(30);
    var response = await client.GetAsync(url);
    response.EnsureSuccessStatusCode();
    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><p>Dynamic content from Blazor.</p>";
    var pdfDocument = renderer.RenderHtmlAsPdf(htmlContent);
    await DisplayPdfContent(pdfDocument);
}

private Task DisplayPdfContent(PdfDocument document)
{
    var data = document.BinaryData;
    pdfUrl = $"data:application/pdf;base64,{Convert.ToBase64String(data)}";
    return Task.CompletedTask;
}
private async Task LoadFromUrl(string url)
{
    using var client = new HttpClient();
    client.Timeout = TimeSpan.FromSeconds(30);
    var response = await client.GetAsync(url);
    response.EnsureSuccessStatusCode();
    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><p>Dynamic content from Blazor.</p>";
    var pdfDocument = renderer.RenderHtmlAsPdf(htmlContent);
    await DisplayPdfContent(pdfDocument);
}

private Task DisplayPdfContent(PdfDocument document)
{
    var data = document.BinaryData;
    pdfUrl = $"data:application/pdf;base64,{Convert.ToBase64String(data)}";
    return Task.CompletedTask;
}
Imports System
Imports System.Net.Http
Imports System.Threading.Tasks

Private Async Function LoadFromUrl(url As String) As Task
    Using client As New HttpClient()
        client.Timeout = TimeSpan.FromSeconds(30)
        Dim response = Await client.GetAsync(url)
        response.EnsureSuccessStatusCode()
        Dim stream = Await response.Content.ReadAsStreamAsync()
        Dim pdfDocument As New PdfDocument(stream)
        Await DisplayPdfContent(pdfDocument)
    End Using
End Function

Private Async Function LoadFromHtmlContent() As Task
    Dim renderer As New ChromePdfRenderer()
    Dim htmlContent As String = "<h1>Generated PDF</h1><p>Dynamic content from Blazor.</p>"
    Dim pdfDocument = renderer.RenderHtmlAsPdf(htmlContent)
    Await DisplayPdfContent(pdfDocument)
End Function

Private Function DisplayPdfContent(document As PdfDocument) As Task
    Dim data = document.BinaryData
    pdfUrl = $"data:application/pdf;base64,{Convert.ToBase64String(data)}"
    Return Task.CompletedTask
End Function
$vbLabelText   $csharpLabel

LoadFromHtmlContent展示了如何轉換HTML為PDF。 Chrome渲染引擎確保了準確的HTML轉換。 其他源選項包括Azure Blob儲存、資料庫記憶體流DOCX文件

哪種來源方法適合您的用例?

Blazor應用程式的PDF來源方法
來源型別 最適合 性能 安全性
本地文件 靜態內容 極佳
網址 外部文件 良好
HTML轉換 動態報告 可變
Blob儲存 企業應用 極佳
記憶體流 暫時PDF 極佳

使用HTML內容輸出

IronPDF測試介面顯示了從HTML內容成功生成的PDF,提供從URL載入或從HTML生成的選項。

如何向PDF檢視器新增交互功能?

擴展PDF檢視器,新增頁面導航、旋轉、列印和下載功能:

@code {
    private int currentPage = 1;
    private int totalPages;
    private byte[] pdfData = Array.Empty<byte>();
    private string pdfUrl = "";
    private string rotationClass = "";
    private string documentId = Guid.NewGuid().ToString();

    private async Task NavigateToPage(int page)
    {
        currentPage = page;
        await JSRuntime.InvokeVoidAsync("navigateTo", page);
    }

    private void RotateCounterclockwise()
    {
        rotationClass = "rotate-270";
    }

    private async Task PrintPdf()
    {
        await JSRuntime.InvokeVoidAsync("printDocument", documentId);
    }

    private async Task DownloadPdf()
    {
        await JSRuntime.InvokeVoidAsync("downloadFile", pdfData, "document.pdf");
    }
}
@code {
    private int currentPage = 1;
    private int totalPages;
    private byte[] pdfData = Array.Empty<byte>();
    private string pdfUrl = "";
    private string rotationClass = "";
    private string documentId = Guid.NewGuid().ToString();

    private async Task NavigateToPage(int page)
    {
        currentPage = page;
        await JSRuntime.InvokeVoidAsync("navigateTo", page);
    }

    private void RotateCounterclockwise()
    {
        rotationClass = "rotate-270";
    }

    private async Task PrintPdf()
    {
        await JSRuntime.InvokeVoidAsync("printDocument", documentId);
    }

    private async Task DownloadPdf()
    {
        await JSRuntime.InvokeVoidAsync("downloadFile", pdfData, "document.pdf");
    }
}
Imports System

Public Class CodeBehind
    Private currentPage As Integer = 1
    Private totalPages As Integer
    Private pdfData As Byte() = Array.Empty(Of Byte)()
    Private pdfUrl As String = ""
    Private rotationClass As String = ""
    Private documentId As String = Guid.NewGuid().ToString()

    Private Async Function NavigateToPage(page As Integer) As Task
        currentPage = page
        Await JSRuntime.InvokeVoidAsync("navigateTo", page)
    End Function

    Private Sub RotateCounterclockwise()
        rotationClass = "rotate-270"
    End Sub

    Private Async Function PrintPdf() As Task
        Await JSRuntime.InvokeVoidAsync("printDocument", documentId)
    End Function

    Private Async Function DownloadPdf() As Task
        Await JSRuntime.InvokeVoidAsync("downloadFile", pdfData, "document.pdf")
    End Function
End Class
$vbLabelText   $csharpLabel

此程式碼新增了頁面導航、旋轉列印下載功能。 考慮為高度依賴導航的文件新增頁碼和書簽。 高級功能可能包括文字提取和PDF轉HTML。

輸出

一個功能齊全的PDF檢視器元件,使用Blazor構建,顯示文件導航控件、設定為100%的縮放功能和自定義操作按鈕,包含載入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";
        }
    }

    await DisplayPdfContent(pdfDocument);
}

private async Task SaveFormData()
{
    var pdfWithFormData = PdfDocument.FromFile("filled-form.pdf");
    var formData = pdfWithFormData.Form.Fields
        .ToDictionary(f => f.Name, f => f.Value);

    var json = System.Text.Json.JsonSerializer.Serialize(formData);
    await File.WriteAllTextAsync("form-data.json", json);

    pdfWithFormData.Form.Flatten();
    pdfWithFormData.SaveAs("form-submission.pdf");
}
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";
        }
    }

    await DisplayPdfContent(pdfDocument);
}

private async Task SaveFormData()
{
    var pdfWithFormData = PdfDocument.FromFile("filled-form.pdf");
    var formData = pdfWithFormData.Form.Fields
        .ToDictionary(f => f.Name, f => f.Value);

    var json = System.Text.Json.JsonSerializer.Serialize(formData);
    await File.WriteAllTextAsync("form-data.json", json);

    pdfWithFormData.Form.Flatten();
    pdfWithFormData.SaveAs("form-submission.pdf");
}
Imports System.IO
Imports System.Threading.Tasks
Imports System.Text.Json

Private Async Function ProcessFormFields() As Task
    Dim pdfDocument = PdfDocument.FromFile("form.pdf")

    For Each field In pdfDocument.Form.Fields
        If field.Type = PdfFormFieldType.Text Then
            field.Value = "User Input"
        End If
    Next

    Await DisplayPdfContent(pdfDocument)
End Function

Private Async Function SaveFormData() As Task
    Dim pdfWithFormData = PdfDocument.FromFile("filled-form.pdf")
    Dim formData = pdfWithFormData.Form.Fields.ToDictionary(Function(f) f.Name, Function(f) f.Value)

    Dim json = JsonSerializer.Serialize(formData)
    Await File.WriteAllTextAsync("form-data.json", json)

    pdfWithFormData.Form.Flatten()
    pdfWithFormData.SaveAs("form-submission.pdf")
End Function
$vbLabelText   $csharpLabel

這使得在Blazor PDF檢視器中的表單填寫功能成為現實,允許使用者直接在瀏覽器中與表單欄位交互。 程式碼會遍歷表單欄位並以程式方式設定值,這對於需要動態預填的應用程式來說是理想的。 IronPDF還支援電子簽名和文字註釋。

支援的欄位型別包括文字輸入、複選框、單選按鈕、下拉列表、電子簽名欄位、多行文字區域和日期選擇器。

何時應使用程式化與互動式表單填寫?

表單填寫方法比較
方法 何時使用 益處
程式化 預填已知資料 更快、一致、可自動化
互動式 需要使用者輸入 靈活、即時驗證
混合 部分資料可用 兩種方法的最佳結合

考慮在提交後將表單平面化以防止被篡改。 對於安全,請使用PDF淨化

輸出

顯示PDF檢視器元件的表單填寫功能範例,展示使用者如何直接在瀏覽器中與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);
    }

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

    await ProcessPdfChunks(chunks);
}
Imports System.IO
Imports System.Threading.Tasks

Private Async Function LoadLargePdf() As Task
    Const chunkSize As Integer = 1024 * 1024 ' 1MB chunks
    Dim pdfPath As String = "largefile.pdf"

    Using fileStream As FileStream = File.OpenRead(pdfPath)
        Dim buffer(chunkSize - 1) As Byte
        Dim chunks As New List(Of Byte())()
        Dim bytesRead As Integer

        Do
            bytesRead = Await fileStream.ReadAsync(buffer, 0, buffer.Length)
            If bytesRead > 0 Then
                Dim chunk(bytesRead - 1) As Byte
                Array.Copy(buffer, chunk, bytesRead)
                chunks.Add(chunk)
            End If
        Loop While bytesRead > 0
    End Using

    Await ProcessPdfChunks(chunks)
End Function
$vbLabelText   $csharpLabel

此方法分段載入大型PDF文件,可防止記憶體問題,並確保即使是龐大的文件也能保持流暢性能。 這在處理移動裝置或資源有限系統上的PDF文件時特別有用。 請參閱IronPDF的性能指南以獲取其他調整選項。

其他優化策略還包括線性化以快速網頁檢視,壓縮以減少文件大小,以及異步處理以同時處理多個PDF。 根據PDF協會最佳實踐,線性化(網頁優化)的PDF可將大型文件的初始載入時間減少30--60%。

哪種文件大小需要分段載入?

PDF文件大小載入策略指南
文件大小 載入策略 記憶體影響
小於5 MB 直接載入 最低
5 -- 20 MB 選擇性分段 中等
20 -- 50 MB 建議分段 顯著
大於50 MB 需要分段 關鍵性

伺服器端渲染在處理大於100 MB的PDF,實施複雜註釋或支援多個同時使用者時變得有益。

如何為受密碼保護的文件加固Blazor PDF檢視器?

處理受密碼保護的PDF文件時,將密碼直接傳遞給PdfDocument.FromFile並配置適當的HTTP安全標頭:

private async Task LoadSecurePdf(string password)
{
    var pdfDocument = PdfDocument.FromFile("secure.pdf", password);

    var headers = new Dictionary<string, string>
    {
        { "X-Frame-Options", "SAMEORIGIN" },
        { "Content-安全性-Policy", "default-src 'self'" },
        { "X-Content-Type-Options", "nosniff" },
        { "Referrer-Policy", "no-referrer" }
    };

    await DisplayPdfContent(pdfDocument);
}
private async Task LoadSecurePdf(string password)
{
    var pdfDocument = PdfDocument.FromFile("secure.pdf", password);

    var headers = new Dictionary<string, string>
    {
        { "X-Frame-Options", "SAMEORIGIN" },
        { "Content-安全性-Policy", "default-src 'self'" },
        { "X-Content-Type-Options", "nosniff" },
        { "Referrer-Policy", "no-referrer" }
    };

    await DisplayPdfContent(pdfDocument);
}
Private Async Function LoadSecurePdf(password As String) As Task
    Dim pdfDocument = PdfDocument.FromFile("secure.pdf", password)

    Dim headers = New Dictionary(Of String, String) From {
        {"X-Frame-Options", "SAMEORIGIN"},
        {"Content-安全性-Policy", "default-src 'self'"},
        {"X-Content-Type-Options", "nosniff"},
        {"Referrer-Policy", "no-referrer"}
    }

    Await DisplayPdfContent(pdfDocument)
End Function
$vbLabelText   $csharpLabel

此程式碼演示了載入受密碼保護的PDF文件同時通過適當的標頭配置來保持安全性。 考慮電子簽名以改善認證。 實施PDF淨化以去除潛在的惡意內容並刪除敏感資訊。

處理密碼時,切勿將其以純文字或客戶端程式碼儲存。 使用安全的輸入方法,用適當的驗證方式,為敏感文件實施會話超時,並在使用後清除記憶體中的密碼。 微軟的ASP.NET Core安全指南建議,始終驗證和淨化任何使用者提供的憑證,然後再將其傳遞給下游API。

使用者端與伺服器端解密

PDF解密方法安全比較
解密型別 使用案例 安全級別
使用者端 公共文件
伺服器端 敏感資料
混合 混合內容

為了最大限度地提高安全性,始終在伺服器端進行解密,並安全地將解密內容串流到客戶端。 為長期存檔需要實施PDF/A合規

在Blazor中顯示PDF的關鍵要點是什麼?

使用IronPDF實施Blazor PDF檢視器為開發者提供了一個完整的解決方案,以在網頁應用程式中顯示PDF。 從基本顯示到高級功能如表單填寫和註解,IronPDF的PDF檢視器元件提供了專業應用程式所需的功能。

範例展示了如何建立可靠的Blazor PDF檢視器以處理各種PDF來源,提供交互功能,並保持良好的性能。 無論是構建一個簡單的文件檢視器還是複雜的文件管理系統,IronPDF與Blazor Server應用程式的整合使實施專業PDF檢視功能變得直截了當。

主要優勢包括:

  • 跨平臺相容性,在所有瀏覽器中具有一致渲染
  • 對敏感文件的高級安全功能
  • 通過異步和分段載入對大型文件進行性能優化
  • 包括電子簽名的完整表單處理能力
  • 與現有.NET應用程式的平滑整合

IronPDF支援Azure、AWS、Docker和傳統的Windows環境。 準備好構建您自己的檢視器了嗎? 開始使用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擁有Carleton大學的電腦科學學士學位,專精於前端開發,擁有Node.js、TypeScript、JavaScript和React的專業知識。Curtis熱衷於建立直觀且美觀的使用者介面,喜愛使用現代框架並建立結構良好、視覺吸引力的手冊。

除了開發,Curtis對物聯網(IoT)有濃厚的興趣,探索創新的方法來整合硬體和軟體。在空閒時間,他喜歡玩遊戲和建立Discord機器人,結合他對技術的熱愛與創造力。

Iron 支援團隊

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