Show or hide the SfPdfViewer Component dynamically in Blazor

21 Jun 20232 minutes to read

In the below code, the SfPdfViewer is hidden at page load. Then, on clicking a button, the SfPdfViewer container will be loaded. When the user clicks on a PDF file (here it is demonstrated with buttons), the SfPdfViewer already present on the same page will be updated to show the selected document.

@using Syncfusion.Blazor.Buttons
@using Syncfusion.Blazor.SfPdfViewer;
@using System.Net;

    .e-spinner-pane {
        display: none !important;

<!--Show or hide the visibility of the SfPdfViewer-->
<SfButton OnClick="ShowHidePdfViewer">@Label SfPdfViewer</SfButton>

@if (IsShowPDFViewer)
    <SfButton OnClick="LoadDocument1">Physical Path</SfButton>
    <SfButton OnClick="LoadDocument2">Remote Path</SfButton>

    <div class="mt-2">
        <SfPdfViewer2 DocumentPath="@Base64Content" Height="100%" Width="100%"></SfPdfViewer2>

    SfPdfViewer2 PdfViewerServerRef { get; set; }

    string Base64Content { get; set; }

    bool IsShowPDFViewer { get; set; }

    string Label => IsShowPDFViewer ? "Hide" : "Show";

    //This method handles the visibility of the SfPdfViewer.
    void ShowHidePdfViewer() => IsShowPDFViewer = !IsShowPDFViewer;

    public void LoadDocument1()
        //Returns a byte array containing the contents of the file.
        byte[] byteArray = System.IO.File.ReadAllBytes("wwwroot/Data/PDF_Succinctly.pdf");
        //Sets the document path from base64 string.
        Base64Content = $"data:application/pdf;base64,{Convert.ToBase64String(byteArray)}";

    public async Task LoadDocument2()
        using (var webClient = new WebClient())
            //Downloads the resource as a byte array from the url specified.
            var data = await webClient.DownloadDataTaskAsync("");
            //Sets the document path from base64 string.
            Base64Content = $"data:application/pdf;base64,{Convert.ToBase64String(data)}";

View sample in GitHub.

See also