Skip to content Skip to sidebar Skip to footer

Window.open With Pdf Stream Instead Of Pdf Location

Based on the question Open PDF in new browser full window, it looks like I can use JavaScript to open a new window with a PDF file with the following code: window.open('MyPDF.pdf',

Solution 1:

It looks like window.open will take a Data URI as the location parameter.

So you can open it like this from the question: Opening PDF String in new window with javascript:

window.open("data:application/pdf;base64, " + base64EncodedPDF);

Here's an runnableexample in plunker, and sample pdf file that's already base64 encoded.

Then on the server, you can convert the byte array to base64 encoding like this:

string fileName = @"C:\TEMP\TEST.pdf";
byte[] pdfByteArray = System.IO.File.ReadAllBytes(fileName);
string base64EncodedPDF = System.Convert.ToBase64String(pdfByteArray);

NOTE: This seems difficult to implement in IE because the URL length is prohibitively small for sending an entire PDF.

Solution 2:

Note: I have verified this in the latest version of IE, and other browsers like Mozilla and Chrome and this works for me. Hope it works for others as well.

if (data == "" || data == undefined) {
    alert("Falied to open PDF.");
} else { //For IE using atob convert base64 encoded data to byte arrayif (window.navigator && window.navigator.msSaveOrOpenBlob) {
        var byteCharacters = atob(data);
        var byteNumbers = newArray(byteCharacters.length);
        for (var i = 0; i < byteCharacters.length; i++) {
            byteNumbers[i] = byteCharacters.charCodeAt(i);
        }
        var byteArray = newUint8Array(byteNumbers);
        var blob = newBlob([byteArray], {
            type: 'application/pdf'
        });
        window.navigator.msSaveOrOpenBlob(blob, fileName);
    } else { // Directly use base 64 encoded data for rest browsers (not IE)var base64EncodedPDF = data;
        var dataURI = "data:application/pdf;base64," + base64EncodedPDF;
        window.open(dataURI, '_blank');
    }

}

Solution 3:

Adding to @Dinesh's answer to handle Not allowed to navigate top frame to data URL error in Chrome and Edge

if (data == "" || data == undefined) {
    // Log Error: PDF data not available
} else {
    var byteCharacters = atob(data);                        
    var byteNumbers = newArray(byteCharacters.length);
    for (var i = 0; i < byteCharacters.length; i++) {
      byteNumbers[i] = byteCharacters.charCodeAt(i);
    }
    var byteArray = newUint8Array(byteNumbers);
    var file = newBlob([byteArray], { type: 'application/pdf;base64' });
                            
    if (window.navigator && window.navigator.msSaveOrOpenBlob) {
        // For IEwindow.navigator.msSaveOrOpenBlob(file, 'mypdf.pdf');
    } else {
        // For non-IEvar fileURL = URL.createObjectURL(file);
        window.open(fileURL);
    }
}

Post a Comment for "Window.open With Pdf Stream Instead Of Pdf Location"