eKoopmans / html2pdf.js

Client-side HTML-to-PDF rendering using pure JS.
MIT License
4.15k stars 1.39k forks source link

jspdf.autoPrint() with .set(options) not working #380

Open k1ns3 opened 3 years ago

k1ns3 commented 3 years ago

Hello everyone!

I ran into the problem of assigning options for the document that I am going to print in the browser I have a piece of code responsible for opening a dialog box in the browser for printing

    const pdfNode = document.getElementById('pdfNode');

    const opt = {
      margin: 1,
      filename: `${template.title}-${new Date().toLocaleDateString()}.pdf`,
      image: { type: 'png', quality: 0.98 },
      html2canvas: {
        scale: 1,
        imageTimeout: 0
      },
      pagebreak: {
        mode: 'avoid-all'
      },
      jsPDF: { unit: 'in', format: 'letter', orientation: 'portrait' }
    };

      html2pdf()
        .set(opt) // here I set the option for the file
        .from(pdfNode)
        .toPdf()
        .get('pdf')
        .then(pdfObj => {
          pdfObj.autoPrint();
          pdfObj.output('dataurlnewwindow');
        });

In this case, the page goes into eternal loading and the dialog box does not open. If you remove .set (opt), then the page opens, but without the settings I need

I have two implementations. Downloading the file directly to the user's PC. The second is to print the document in the browser In the second case, the options are successfully installed

I will give a working code for downloading on the user's PC

html2pdf()
        .set(opt) // here I set the option for the file
        .from(pdfNode)
        .save()
        .then(() => {
          setTimeout(() => {
            window.close();
          }, 100);
        });

Perhaps someone has already encountered a similar problem. I will be glad to help

psclrzn commented 1 year ago

... 2years later, but just in case, try this as an alternative:

(I am not into iFrames though)

html2pdf()
  .set(opt)
  .from(el)
  .toPdf()
  .get('pdf')
  .then(pdfObj => {
      pdfObj.autoPrint();
      let str = pdfObj.output('datauristring');
      let iframe = "<iframe width='100%' height='100%' src='" + str + "'></iframe>";
      let x = window.open();
      x.document.open();
      x.document.write(iframe);
      x.document.close();
  });