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);
}
}
参考资料: