0

I am using this piece of javascript to print out some html content:

function printHTML(htmlToPrint) {
    var mywindow = window.open('', 'PRINT', 'height=400, width=600');

    mywindow.document.write("<html><head><title>My Doc Title</title>");
    mywindow.document.write("</head><body>");
    mywindow.document.write(htmlToPrint);
    mywindow.document.write("</body></html>");

    mywindow.document.close(); // necessary for IE >= 10
    mywindow.focus(); // necessary for IE >= 10*/

    mywindow.print();
    mywindow.close();

    return true;
}

And this work absolutely fine.

It opens the print dialog and then you can either 'print' it or 'save it as pdf'.

What I'd like to do is to skip the print dialog and save (download) it as pdf sraight away at the end of my function. I found a lot of suggestions to use jsPDF library for this, but couldn't find any easy examples on how to use it in my case...

Any advise is highly appreciated :)

Gintas K
  • 1,438
  • 3
  • 18
  • 38

1 Answers1

-1

I found a nice demo here showing what you need.

There is also a codepen link for the same given at the bottom of that page where you can check out the complete code with html markup

In short, if your HTML markup is like below

<div id="content">
    <h3>Sample h3 tag</h3>
    <p>Sample pararaph</p>
</div>
<button id="cmd">Generate PDF</button>

Then on click over button, you can generate the pdf this way just by calling save function over the jsPDF object

var doc = new jsPDF();

$('#cmd').click(function () {   
    doc.fromHTML($('#content').html(), 15, 15, {
        'width': 170,
        'elementHandlers': specialElementHandlers
    });
    doc.save('sample-file.pdf');
});
Sandip Ghosh
  • 719
  • 7
  • 13