user1031947
user1031947

Reputation: 6664

How to print a base64 pdf?

I receive a base64 pdf from the server which I want to print.

I have been trying the following:

$.ajax({
    type: "POST",
    url: url,
    data: blahblahblah,
    success: function(data) {
        var printWindow = window.open( "data:application/pdf;base64, " + data );
        printWindow.print();
    }
});

Sadly, this does not work in Chrome. I am receiving the following error:

SecurityError: Blocked a frame with origin "xxx" from accessing a frame with origin "null". The frame requesting access has a protocol of "http", the frame being accessed has a protocol of "data". Protocols must match.

Suggestions on how to work around this?

Upvotes: 4

Views: 29393

Answers (4)

ChrisE
ChrisE

Reputation: 576

This library works well for us: https://printjs.crabbly.com/

$.ajax({
type: "POST",
url: url,
data: blahblahblah,
success: function(base64) {
    printJS({printable: base64, type: 'pdf', base64: true});
});

Upvotes: 1

TommyZG
TommyZG

Reputation: 560

// open PDF received as Base64 encoded string in new tab
const openPdf = (basePdf) => {
  let byteCharacters = atob(basePdf);
  let byteNumbers = new Array(byteCharacters.length);
  for (let i = 0; i < byteCharacters.length; i++) {
    byteNumbers[i] = byteCharacters.charCodeAt(i);
  }
  let byteArray = new Uint8Array(byteNumbers);
  let file = new Blob([byteArray], {type: 'application/pdf;base64'});
  let fileURL = URL.createObjectURL(file);
  window.open(fileURL);
}

Upvotes: 6

Muhammad Fahad
Muhammad Fahad

Reputation: 1

you can use jspdf to do this like

var p=new jspdf();
p.addImage(imgData, 'JPEG', 0, 0); // where imageDate contains base64 string

Upvotes: -1

Ricardo Pontual
Ricardo Pontual

Reputation: 3757

You can try to open your window and try to insert the pdf data as embed.

Here is an piece of code I've found and used fine (I changed to fit on your code, but not tested):

    $.ajax({
    type: "POST",
    url: url,
    data: blahblahblah,
    success: function(data) {

        var winparams = 'dependent=yes,locationbar=no,scrollbars=yes,menubar=yes,'+
            'resizable,screenX=50,screenY=50,width=850,height=1050';

        var htmlPop = '<embed width=100% height=100%'
                         + ' type="application/pdf"'
                         + ' src="data:application/pdf;base64,'
                         + escape(data)
                         + '"></embed>'; 

        var printWindow = window.open ("", "PDF", winparams);
        printWindow.document.write (htmlPop);
        printWindow.print();
    }
});

Hope it helps.

Upvotes: 9

Related Questions