60

After updating Google Chrome, the report jsPDF in a new Window does not work any more.

The console shows the message:

Not allowed to navigate top frame to data URL: data:application/pdf;base64,JVBERi0xLjMKMyAwIG9iago8PC9UeXBlIC9QYWdlCi9QYXJlbnQgMSAwIFIKL1....

Can you help-me?

Thanks.

15 Answers 15

64

This works well now that chrome has removed top frame navigation. Only downloading the pdf in chrome gives problem. Download works in well in firefox tho.

var string = doc.output('datauristring');
var iframe = "<iframe width='100%' height='100%' src='" + string + "'></iframe>"
var x = window.open();
x.document.open();
x.document.write(iframe);
x.document.close();
12
  • This solution worked for me very well. I'm using html2canvas. Oct 10, 2017 at 22:13
  • Worked for me on Firefox and Chrome. Needed to encodeURIComponent(string) though. Oct 19, 2017 at 8:44
  • 1
    Then what is the solution for downloading in Chrome? Jan 16, 2018 at 12:24
  • 3
    @SukantaBala As of now this is how I have handled the download issue. doc.save(filename + '.pdf'); This code automatically downloads the pdf without having to click the download button.
    – Joyston
    Jan 16, 2018 at 18:46
  • 1
    Yes @NorCalKnockOut. Atleast for my purpose I needed to view the pdf so I had to open it in an iframe. You could directly save on your local machine as well by using doc.save(filename + '.pdf');
    – Joyston
    Mar 20, 2018 at 11:22
40

Apparently Google Chrome has removed support for top-frame navigation, you can see more informations here: https://groups.google.com/a/chromium.org/forum/#!topic/blink-dev/GbVcuwg_QjM

You may try to render the jsPDF to an iFrame

5
  • 1
    hi @MárcioRossato can you please send me the code to render jsPdf in the i frame. Aug 12, 2017 at 8:43
  • @KuldeePChoudharY hi, i'm using angularJS, I sent the script, and I hope help-you !! Aug 14, 2017 at 0:38
  • Can't download the pdf using this way the download button is not working.
    – adam
    Aug 24, 2017 at 15:44
  • @MárcioRossato Can you post the script as new answer
    – Pruthviraj
    Nov 9, 2017 at 10:50
  • hi @Pruthviraj, after I use de object tag, like this: stackoverflow.com/questions/45649105/… Nov 10, 2017 at 11:37
18

I recently had the same problem using FileReader object to read content and show my JSReport.

 var reader = new FileReader();                        
 reader.onload = function (e) {
      window.open(reader.result, "_blank");
 }
 reader.readAsDataURL(blob);

Unfortunatly after chrome update all my report stopped working. I tried to fix this by using Blob object and it's still working but if you have a popup blocker it will not work.

 var file = new Blob([blob], { type: 'application/pdf' });
 var fileURL = URL.createObjectURL(file);
 window.open(fileURL);

I finally find a way to avoid this problem by creating the iFrame dynamically after reading this topic and i decided to share the solution.

 var file = new Blob([blob], { type: 'application/pdf' });
 var fileURL = URL.createObjectURL(file);
 var win = window.open();
 win.document.write('<iframe src="' + fileURL + '" frameborder="0" style="border:0; top:0px; left:0px; bottom:0px; right:0px; width:100%; height:100%;" allowfullscreen></iframe>')
6
  • 4
    Works for displaying and printing but can't download the pdf, the download button seems to be not triggered.
    – adam
    Aug 24, 2017 at 15:37
  • Download works in FF but not in Chrome. Anyone found a solution for chrome yet?
    – lentyai
    Aug 30, 2017 at 2:12
  • I didn't find a way to fix this but you can temporary add a download button before your iFrame: '<a href="' + fileURL + '" download="DownloadPDF">Download PDF<\a>' This will not affect the print button as long as it is not in the iFrame. You can also ask the user if he wants to download or view the file on main event. Sep 3, 2017 at 6:55
  • Thanks for the solution, But his doesn't seem to be working in edge browser, Any suggestions?
    – Pruthviraj
    Nov 12, 2017 at 3:48
  • The solution works very well but it can be blocked by the popup blocker. Is there a way to prevent this ? My goal was to use this to replace the classic file download. I don't want to show the file link so I've replaced it by an authentified POST call that returns the binary. Thank you. Feb 21, 2018 at 15:55
11

Maybe can help, create a function to export with the download attribute html5:

var docPdf = doc.output();
exportToFile(docPdf,defaults.type);

function exportToFile(data,type){

    var hiddenElement = document.createElement('a');
    hiddenElement.href = 'data:text/'+type+';filename='+'exportar.'+type+';'+'charset=utf-8,' + encodeURI(data);
    hiddenElement.target = '_blank';
    hiddenElement.download = 'exportar.'+type;
    hiddenElement.click();
}
2
  • such approach can cause browser to freeze the whole page for some time Jun 20, 2022 at 10:22
  • Still throws the error, even when the user clicks it
    – Caleb Liu
    Jul 7, 2022 at 13:14
4

the download property of the a element has to contain a file name.

function window_download( datauri )
{
  const match = datauri.match(/(filename=)([^;]+)/);
  const fileName = match ? match[2] : '' ;
  if ( fileName )
  {
    const downloadLink = document.createElement("a");
    downloadLink.download = fileName;
    downloadLink.innerHTML = "Download File";
    downloadLink.href = datauri ;
    downloadLink.click();
  }
else
{
throw 'missing download file name' ;
}


   // get contents of pdf from jsPDF as a data uri.
    const uri = pdf.output('datauristring', 'packing-list.pdf' );
    window_download( uri ) ;

3

As chrome removed its support for - Top-frame navigation. Luckily jsPDF has an API - "save()", which offers the same functionality as doc.output('datauri')

Below is the example implementation of save()

var doc = new jsPDF();
doc.addImage(imgData, 'JPEG', 0, 0, 300, 160);    
doc.save('fileName.pdf');

save(filename, options) → {jsPDF|Promise}

Saves as PDF document. An alias of jsPDF.output('save', 'filename.pdf'). Uses FileSaver.js-method saveAs. Refer JSPDF documentation for more information -

1
  • 1
    best and easiest answer . should be the highest votes . thanks alot Apr 23, 2022 at 0:06
2
<iframe id="ManualFrame"
        frameborder="0"
        style="border:0"
        allowfullscreen>
</iframe>

<script>
    $(function () {
        setManualFrame();
    });

    function setManualFrame() {
        $("#ManualFrame").attr("height", screen.height);
        $("#ManualFrame").attr("width", screen.width);
        $("#ManualFrame").attr("src", "data:application/pdf;base64," + Your_PDF_Data);
    }
</script>
2
var pdfUrl = doc.output('datauri').substring(doc.output('datauri').indexOf(',')+1);
var binary = atob(pdfUrl.replace(/\s/g, ''));
var len = binary.length;
var buffer = new ArrayBuffer(len);
var view = new Uint8Array(buffer);
for (var i = 0; i < len; i++) {
    view[i] = binary.charCodeAt(i);
}

var blob = new Blob( [view], { type: "application/pdf" });
var url = URL.createObjectURL(blob);

function openPDF(){
    window.open(url);
}
2
  • 1
    Can you please explain how this solves the original question? Dec 17, 2017 at 23:33
  • you can use this code to open the pdf document in a new tab as a blob... cause chrome blocks JsPDF from opening the document.... which i believe is the original question.
    – Surya T
    Dec 18, 2017 at 12:12
2

Add attrbute download

<a href="data:image/jpg;base64,/AA/AABBCCDD..." download="name.jpg"></a>
0
1

Based on Joyston's answer, but without reparsing and therefore without additional need to escape something:

x=window.open();
iframe=x.document.createElement('iframe')
iframe.width='100%'
iframe.height='100%'
iframe.frameBorder=0
iframe.style="border: 0"
iframe.src='data:text/html........' //data-uri content here
x.document.body.appendChild(iframe);
1
  • I don’t know why, but by using x=window.open(‘about:whatever’); seems to enable downloading. May 4, 2018 at 10:03
1

Not related to jspdf, but did help me here (and this question is the top hit at google): If specifying a download="..." attribute to the anchor tag, the download prompt will properly open up.

1

@kuldeep-choudhary

Hi, in fact, to solve i'm using object tag with angularJS 1.5.xx

<object ng-attr-data="{{data}}" type="application/pdf"></object>

and in script:

$scope.doc.data = $sce.trustAsResourceUrl(doc.output("datauristring"));

In pure javascript, maybe like this works:

html:

<object id="obj" type="application/pdf" ></object>

js:

document.elementById('obj').data = doc.output("datauristring");

please, try and correct-me if I wrong.

2
1

Using download="" made me able to download the file

0
1
/**
 * Creates an anchor element `<a></a>` with
 * the base64 pdf source and a filename with the
 * HTML5 `download` attribute then clicks on it.
 * @param  {string} pdf 
 * @return {void}     
 */
function downloadPDF(pdf) {
    const linkSource = `data:application/pdf;base64,${pdf}`;
    const downloadLink = document.createElement("a");
    const fileName = "vct_illustration.pdf";

    downloadLink.href = linkSource;
    downloadLink.download = fileName;
    downloadLink.click();
}

Source from: https://medium.com/octopus-labs-london/downloading-a-base-64-pdf-from-an-api-request-in-javascript-6b4c603515eb

0

In angular2+ -

app.component.html -

 <object id="obj"  [attr.data]  type="application/pdf"> </object>

app.component.ts

 document.getElementById('obj').dataset.data = doc.output("datauristring");

  var blob = doc.output("blob");
  window.open(URL.createObjectURL(blob));

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.