How to put and download the content of a div in html into pdf file using JS?

吃可爱长大的小学妹 提交于 2019-12-14 02:13:59

问题


I need to put the content of a div into a pdf file then download it. I've searched a bit and I found that you can use javascript to do this via jsPDF.

I found this sample code but it seems that it doesn't work for me. When I click the generate pdf button nothing happens. I am also using codeigniter for my framework and my website is currently uploaded in 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>

回答1:


Works for me on JSFiddle.net: http://jsfiddle.net/scottcanoni/h3Lb05wa/

What error are you getting on your website?

All I am including is jQuery and the jsPDF script:

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

If you include both jQuery and jsPDF in your <head> tag, you should be fine with the code provided.




回答2:


Are you using JavaScript for a reason? I would (and have) use DOM PDF;

https://github.com/dompdf/dompdf

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



来源:https://stackoverflow.com/questions/27362819/how-to-put-and-download-the-content-of-a-div-in-html-into-pdf-file-using-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!