Open Base64 Encoded Pdf File Using Javascript. Issue With File Size Larger Than 2 Mb
Solution 1:
There indeed seems to be a limit on both Chrome's pdf reader plugin and Mozilla's pdf.js (used by Firefox) as to the size of pdf documents loaded by a data-URI.
Note that this limit is not dictated by anything else than these plugin/scripts (pdf.js even just crash the tab), browsers do support far bigger dataURLs in many places like <img>, <video>, <iframe> etc.
You can see a live repro hereBut beware if you are on Firefox, it may crash your browser, so toggle the checkbox at your own risk. (Outsourced because somehow Chrome can't load pdfs from StackSnippet's null origined iframes).
For a fix, convert your base64 data back to binary, packed in a Blob and then set your iframe's src to a blob-URI pointing to that Blob:
const blob = base64ToBlob( base64, 'application/pdf' );
const url = URL.createObjectURL( blob );
const pdfWindow = window.open("");
pdfWindow.document.write("<iframe width='100%' height='100%' src='" + url + "'></iframe>");
functionbase64ToBlob( base64, type = "application/octet-stream") {
const binStr = atob( base64 );
const len = binStr.length;
const arr = newUint8Array(len);
for (let i = 0; i < len; i++) {
arr[ i ] = binStr.charCodeAt( i );
}
returnnewBlob( [ arr ], { type: type } );
}
Once again Live Demo as an outsourced plnkr.
But note that it would be even more efficient if your API sent that pdf directly as a Blob, or even if you could make your <iframe> point directly to the resource's URL.
Solution 2:
The URL limit on most popular browsers is usually 65,535 characters (~64 KB), so this is a constraint on the number of characters in the URL. You usually want this number below 2,000 (2 KB) so that your site works on most browsers (legacy is some cases).
See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs
Length limitations
Although Firefox supports
data
URLs of essentially unlimited length, browsers are not required to support any particular maximum length ofdata
. For example, the Opera 11 browser limited URLs to 65535 characters long which limitsdata
URLs to 65529 characters (65529 characters being the length of the encoded data, not the source, if you use the plaindata:
, without specifying a MIME type).
See also
Solution 3:
You could instead try to read/store the file as Blob then use saveAs from FileSaver.js to download or open the pdf file
Post a Comment for "Open Base64 Encoded Pdf File Using Javascript. Issue With File Size Larger Than 2 Mb"