Blasser WebAssembly Using stream in pdf.js

Viewed 12

How can I use a base64 stream in pdf.js inside a Blazor app? It's easier to use a local path (src="path?file=filePath"), but not good documented how to handle a pdf stream.

1 Answers

Download, unpack and implement pdf.js in your blazor app in wwwroot/lib.

Add at 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>

Add at your page or component.razor:

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

and in the 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);
    }
}

In this example the _stream comes from a API. Put in the property _stream your stream string wherever you will get it from.

Related