简体   繁体   中英

PDF of a generate div via jquery, using jsPDF

i want to generate a PDF file from a div using jsPDF, it works flawless in static code, but i want to do it with generate code, like this:

<button id = "click">Click</button>
<div id = "here"></div>

<script type="text/javascript">
$("#click").click(function(){
  var write = '<div id = "example">Hello</div><button id = "click_pdf">PDF</button>';
  $("#here").html(write);
});

$("#click_pdf").click(function(){
  var doc = new jsPDF;
  doc.fromHTML($("#example").get(0),10,10,{
     'width': 180
  }
  doc.save("Test.pdf");
});
</script>

But is not working, not ever display an error message in the console

Also i try to change an onclick event instead of the jquery event, like this:

var write = '<div id = "example">Hello</div><button onclick = click_pdf()>PDF</button>';
...
function click_pdf(){
   var doc = new jsPDF;
   ...
}

In this case, appears an "Uncaught TypeError: Cannot read property '#' of undefined" error.

Also i try to generate the function click_pdf() or the $("#click_pdf").click inside the $("#click").click function without results. Any ideas?

Try this:

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
     <script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/jspdf/0.9.0rc1/jspdf.min.js"></script>
    <script>

    $(function(){
    $("#click").click(function(){
      var write = '<div id = "example">Hello</div><button id= "click_pdf">PDF</button>';
      $("#here").html(write);
    });
    $(document).on("click","#click_pdf",function(){
      var doc = new jsPDF;
var specialElementHandlers = {
    '#editor': function (element, renderer) {
        return true;
    }
};
        doc.fromHTML($('#example').html(), 15, 15, {
            'width': 170,
            'elementHandlers': specialElementHandlers
        });
      doc.save("Test.pdf");
    });
    });

    </script>


    <input type="button" id="click" value="Click!"/>
    <div id="here"></div>

DEMO

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