Blazor和JavaScript可以互操作,因此可以使用PDFObject预览pdf文件。实现步骤如下:
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); }
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中的方法名一致 } }
@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