javascripthtmljqueryhtml-to-pdf

How To Convert HTML to PDF using JavaScript


I want to convert HTML to PDF with the click of a button and download. My js working perfectly only need the latest JavaScript CDN link.

HTML

<div id="pageprint">
   <div id="reportbox">Hello World!!</div>
</div> 
<button type="button" onclick="downloadCode();">Download HTML</button>

Javascript

<script>
    function generatePDF() {
    
    const element = document.getElementById("pageprint");
    document.getElementById("reportbox").style.display = "block";
    document.getElementById("reportbox").style.marginTop = "0px"; 
    document.getElementById("pageprint").style.border = "1px solid black";
    html2pdf().from(element).save('download.pdf'); 
    }
    
    function downloadCode(){
    var x = document.getElementById("reportbox");  
    generatePDF();
    setTimeout(function() { window.location=window.location;},3000);}
</script>

Solution

  • If all you need is the CDN then simply add it after the </body>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.10.1/html2pdf.bundle.min.js" integrity="sha512-GsLlZN/3F2ErC5ifS5QtgpiJtWd43JWSuIgh7mbzZ8zBps+dvLusV+eNQATqgA/HdeKFVgA5v3S/cIrLF7QnIg==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
    
    

        function generatePDF() {
        
        const element = document.getElementById("pageprint");
        document.getElementById("reportbox").style.display = "block";
        document.getElementById("reportbox").style.marginTop = "0px"; 
        document.getElementById("pageprint").style.border = "1px solid black";
        html2pdf().from(element).save('download.pdf'); 
        }
        
        function downloadCode(){
        var x = document.getElementById("reportbox");  
        generatePDF();
        setTimeout(function() { window.location=window.location;},3000);}
        
    <div id="pageprint">
       <div id="reportbox">Hello World!!</div>
    </div> 
    <button type="button" onclick="downloadCode();">Download HTML</button>
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.10.1/html2pdf.bundle.min.js"></script>

    However seems a very odd way to ask a user to download a pdf page since the option disappears after the download is attempted, so change of mind does not keep it user visible to try differently on fail.
    enter image description here

    So for example, I say open the download on current page, I see enter image description here

    but if I say open in PDF Viewer I see enter image description here

    It's much simpler to layout the printable HTML page as text not image, and suggest the user prints or saves exactly as their browser is configured and their desire, best result for all, especially as no libraries are needed. Nor will the page be cluttered by buttons. enter image description here