简体   繁体   中英

Converting HTML content to PDF file using jsPDF

Trying to automatically convert this content to a pdf file. Based on how the rest of my code is setup, I have to have the button to click INSIDE the div that I want to export to pdf. Is this a problem? Here's what I have so far. When I click the button, it does nothing.

JS:

<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.4/jspdf.debug.js"></script>

<script>
jQuery('#generatereport').click(function () {
    doc.fromHTML(jQuery('#lppresults').html(), 15, 15, {
        'width': 170
    });
    doc.save('sample-file.pdf');
});
</script>

HTML:

<div class="survey-results" style="display: none;" id="lppresults">
   <button id="generatereport">Download Report</button>
   TEST CONTENT
</div>

No, this is not a problem. You can have the button inside the div element. Though you have some other issues. Here is the revised version of your code ...

 var doc = new jsPDF(); $('#generatereport').click(function() { doc.fromHTML($('#lppresults')[0], 15, 15, { width: 170 }, function() { doc.save('sample-file.pdf'); }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.4/jspdf.min.js"></script> <div class="survey-results" id="lppresults"> <button id="generatereport">Download Report</button> TEST CONTENT </div> 

You need to initialize the jsPDF class : var doc = new jsPDF();

 var doc = new jsPDF(); jQuery('#generatereport').click(function() { doc.fromHTML(jQuery('#lppresults').html(), 15, 15, { 'width': 170 }); doc.save('sample-file.pdf'); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.4/jspdf.min.js"></script> <div class="survey-results" id="lppresults"> <button id="generatereport">Download Report</button> TEST CONTENT </div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM