Search code examples
javascriptpdfjspdfhtml2canvas

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 ?


Solution

  • 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>