1. 程式人生 > 其它 >Blazor使用PDFObject預覽pdf檔案

Blazor使用PDFObject預覽pdf檔案

Blazor和JavaScript可以互操作,因此可以使用PDFObject預覽pdf檔案。實現步驟如下:

  • 新增script.js檔案,呼叫PDFObject函式預覽後端返回的檔案Stream
import "./libs/pdfobject.js";

export async function showPdf(id, stream) {
    const arrayBuffer = await stream.arrayBuffer();
    const blob = new Blob([arrayBuffer], { type: 'application/pdf' });//必須要加type
    const url = URL.createObjectURL(blob);
    PDFObject.embed(url, '#' + id, { forceIframe: true });//只有iframe可以開啟blob連結
    URL.revokeObjectURL(url);
}
  • 新增JsInterop.cs檔案,
public class JsInterop : IAsyncDisposable {
    private readonly Lazy<Task<IJSObjectReference>> moduleTask;
    
    public JsInterop(IJSRuntime jsRuntime) {
        moduleTask = new(() => jsRuntime.InvokeAsync<IJSObjectReference>(
               "import", "./_content/XXX/script.js").AsTask());
        //XXX為Razor類庫名稱
    }
    
    public async void ShowPdf(string id, Stream stream) {
        var module = await moduleTask.Value;
        using var streamRef = new DotNetStreamReference(stream);
        await module.InvokeVoidAsync("showPdf", id, streamRef);//showPdf與script中的方法名一致
    }
}
  • 新增PdfFile.razor檔案
@inject JsInterop Js

<div id="pdf" class="tc-pdf"></div>

@code {
    protected override void OnInitialized() {
        base.OnInitialized();
        var stream = Service.GetPdfFile();
        Js.ShowPdf("pdf", stream);
    }
}

參考資料:

ASP.NET Core Blazor 檔案下載 | Microsoft Docs

javascript - Embed a Blob using PDFObject - Stack Overflow