Blazor WebAssembly在pdf.js中使用流



如何在Blazor应用程序中使用pdf.js中的base64流?使用本地路径(src="path?file=filePath"(更容易,但没有很好的文档说明如何处理pdf流。

在wwwroot/lib中的blazor应用程序中下载、解压并实现pdf.js。

在index.html添加

<script type="text/javascript" src="lib/pdfjs/build/pdf.js"></script>
<script type="text/javascript">
function loadPdf(base64Data) {
try {
var pdfjsframe = document.getElementById('pdfViewer');
if (!base64Data == "") {
pdfjsframe.contentWindow.PDFViewerApplication.open(base64Data);
}
} catch (error) { console.error("Error at pdfjsframe.contentWindow.PDFViewerApplication.open(base64Data)"); }   
}    
</script>

添加到您的页面或组件.razor:

<iframe id="pdfViewer" src="/lib/pdfjs/web/viewer.html"></iframe>

以及在cs:中

public partial class PdfViewerComponent
{
[Parameter]
public int DocumentNumber { get; set; }
private string _stream = "";
protected override async Task OnParametersSetAsync()
{
_stream = await HttpClientService.GetDocumentStreamById(DocumentNumber);
if (!string.IsNullOrEmpty(_stream))
await OpenDocument(_stream);
_stream = ""; // that will ensure that your loading the right pdf at the right time
}
private async Task OpenDocument(string stream)
{
await JSRuntime.InvokeVoidAsync("loadPdf", stream);
}
}

在本例中,_stream来自API。将流字符串放入属性_stream中,无论从何处获取。

最新更新