If you’re encountering issues with loading large PDF files in a Blazor popup, it might be due to limitations in the size of data that can be handled efficiently, especially when using iframe or HTML encoded objects. Loading large files directly into the DOM can sometimes lead to performance issues or even outright failure.
Here is my javascript code block which is called from blazor code behind
Javascript code
function openPdf(base64PdfDoc) {
"use strict";
var left = window.screen.width;
left = left > 0 ? left / 4 : 0;
let pdfWindow = window.open("", 'winname', 'directories=no,titlebar=no,toolbar=no,location=no,status=no,menubar=no,scrollbars=yes,resizable=no,width=800,height=750, top = 0, left=' + left);
pdfWindow.document.write(
"<iframe width='100%' height='100%' src='data:application/pdf;base64, " +
encodeURI(base64PdfDoc) + "'></iframe>"
);
}
Javascript called from Backend code
await JsRuntime.InvokeVoidAsync("openPdf", pdfContent);
Trying to bind in html as well but not working
<object width="100%" height="100%" data="data:application/pdf;base64,@base64pdfString" type="application/pdf" class="internal"
<embed src="data:application/pdf;base64,@base64courierlogpdfString" type="application/pdf" />
</object>
2
Answers
Incorporating the same concept, I've successfully implemented a solution. Since the backend API was returning a response in base64 format, I converted it to a blob and generated a blob URL. Subsequently, I mapped this URL within an iframe to display the content seamlessly.
JavaScript interop is not feasible to pass a very large string. Because Blazor and the underlying
System.Text.Json
library have a limit on the size of a single JSON value passed throughJSInterop
, this limit is to prevent performance issues and potential browser crashes.So we can bypass this limitation by adding a
Controller
toBlazor Server Project
and then using blobs in javascript, as detailed below.Step 1. Prerequisites, add support for controllers in the Blazor project.
Step 2. The structure of my project.
Step 3. Download the pdf.js here. And use it like my project.
Step 4. pdfViewer.js.
Step 5.
HomeController.cs
.Step 6. PdfDemo.razor.
Test Result