naminghtml2pdfbloburls

How to set download file name html2pdf.js on blob url


I am using html2pdf.js

I should show preview before my customer will download files.

The way of 'dataurlnewwindow' can show preview, but download button is not working.

So i change bloburl output, and download button is working.

But when i clicked download, i wanna set the download filename.

As you can see below, i cant set the download file name. enter image description here

Does anyone knows to handle it?

This is my html2pdf.js code i used.

const opt = { margin: 10, filename, html2canvas: { width: 800, useCORS: true } };
html2pdf().set(opt).from(html).output('bloburl').then(r => { window.open(r) })

Even you guys know to support preview and download with name, plz tell me. i need help


Solution

  • You should try setting the filename at <a> tag in download property.

    html2pdf().from(html)
              .set(opt)
              .toPdf()
              .get('pdf')
              .then((pdf) => downloadPdf(pdf, options));
    
    const downloadPdf = (pdf, opt) => {
        let link = document.createElement('a');
        link.target = '_blank';
        link.href = pdf.output('bloburl');
        link.download = 'myFileName.pdf';
        link.click();
        link.remove();
    }
    

    This will open PDF in a new tab page, because of target=_blank and download it right after the click() event on <a> tag element.