如何使用JS将html中div的内容下载到pdf文件中?

时间:2014-12-08 16:51:39

标签: html html5 codeigniter jspdf

我需要将div的内容放入pdf文件然后下载。我搜索了一下,发现您可以通过jsPDF使用javascript来执行此操作。

我找到了这个示例代码,但它似乎对我不起作用。当我单击生成pdf按钮时没有任何反应。我也使用codeigniter作为我的框架,我的网站目前上传到000.webhost.com。

     <div id="content">
      <h3>Hello, this is a H3 tag</h3>

          <p>a pararaph</p>
     </div>
      <div id="editor"></div>
       <button id="cmd">generate PDF</button>

         <script type="text/javascript">
       var doc = new jsPDF();
        var specialElementHandlers = { 
     '#editor': function (element, renderer) {
            return true;
        }
        };

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

     </script>

2 个答案:

答案 0 :(得分:1)

在JSFiddle.net上为我工作: http://jsfiddle.net/scottcanoni/h3Lb05wa/

您在网站上遇到了什么错误?

我所包括的是jQuery和jsPDF脚本:

<script type="text/javascript" src="https://parall.ax/parallax/js/jspdf.js"></script>

如果在<head>标记中同时包含jQuery和jsPDF,则应该可以使用提供的代码。

答案 1 :(得分:0)

您使用JavaScript是有原因的吗?我会(并且已经)使用DOM PDF;

https://github.com/dompdf/dompdf

https://github.com/bcit-ci/CodeIgniter/wiki/PDF-generation-using-dompdf