Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I'm using html2pdf to generate a pdf, can I hide the html so the user doesn't see it?

I'm generating vouchers using the html2pdf library.

This works fine with the voucher showing as HTML in the page.

I have a button that triggers the html2pdf() function on click, prompting the user to accept the PDF download.

I would like for the HTML to not show on the page. I tried applying position: absolute; and placing the HTML away from the user's sight. Unfortunately, the PDF then renders as blank.

Is there a way to achieve this ?

like image 288
Brachamul Avatar asked Dec 02 '22 12:12

Brachamul


2 Answers

If you want without showing content to user to download pdf, then use innerHTML

<div id="exportPdf" style="display: none"></div>

style="display: none" to div

var source = window.document.getElementById("exportPdf").innerHTML;

html2pdf().set(opt).from(source).save();

innerHTML will do the trick

like image 144
Sidda Avatar answered Dec 06 '22 12:12

Sidda


Just toggle the display property of 'element-to-print' before and after the html2pdf call.

https://jsfiddle.net/bambang3128/u6o6ne41/10/

function toggleDisplay() {
  var element = document.getElementById('element-to-print');
  if (element.style.display == 'block') {
    element.style.display = 'none'
  } else {
    element.style.display = 'block'
  }

  console.log('toggleDisplay()');
}

function printPDF() {
  var element = document.getElementById('element-to-print');
  element.style.display = 'block'
  html2pdf(element);
  element.style.display = 'none'
  console.log('printPDF()');
}
<script src="https://rawgit.com/eKoopmans/html2pdf/master/dist/html2pdf.bundle.min.js"></script>
<div id="element-to-print" hidden>
  <h1>This is a hidden div</h1>
  This one is hidden div contents.
</div>
<p>
  Save the hidden element as PDF.
</p>
<button type="button" onclick="toggleDisplay();">Toggle Display!</button>
<button type="button" onclick="printPDF();">Click Me!</button>
like image 32
Bambang Avatar answered Dec 06 '22 10:12

Bambang