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 ?
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
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With