简体   繁体   English

使用jsPDF通过jquery生成div的PDF

[英]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: 我想使用jsPDF从div生成PDF文件,它在静态代码中可以完美地工作,但是我想通过生成代码来做到这一点,例如:

<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: 我也尝试更改onclick事件而不是jquery事件,如下所示:

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. 在这种情况下,会出现“未捕获的TypeError:无法读取未定义的属性'#'”错误。

Also i try to generate the function click_pdf() or the $("#click_pdf").click inside the $("#click").click function without results. 我也尝试生成$(“#click”)。click函数内部的click_pdf()或$(“#click_pdf”)。click函数,但没有结果。 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 DEMO

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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