Wednesday, 8 July 2015

PDF generation using jspdf

PDF generation using jspdf

Python and PDF generation


PDF generation using python is one of the trickiest task that I have recently encountered. So today I want list all the possible ways that one can convert an HTML to pdf using python (Django framework).

Let start from basic before going on to Python lets check one of the simplest way to generate pdf using jspdf.

PDF generation using jspdf

For jspdf to work, first of all you will have to link all the required js files to the html.

      
  <script type="text/javascript" src="jspdf/jspdf.js"></script>  
  <script type="text/javascript" src="jspdf/jspdf.plugin.addimage.js"></script> 
  <script type="text/javascript" src="jspdf/jspdf.plugin.cell.js"></script> 
  <script type="text/javascript" src="jspdf/jspdf.plugin.from_html.js"></script> 
  <script type="text/javascript" src="jspdf/jspdf.plugin.ie_below_9_shim.js"></script> 
  <script type="text/javascript" src="jspdf/jspdf.plugin.javascript.js"></script> 
  <script type="text/javascript" src="jspdf/jspdf.plugin.sillysvgrenderer.js"></script> 
  <script type="text/javascript" src="jspdf/jspdf.plugin.split_text_to_size.js"></script> 
  <script type="text/javascript" src="jspdf/jspdf.plugin.standard_fonts_metrics.js"></script> 
  <script type="text/javascript" src="jspdf/jspdf.PLUGINTEMPLATE.js"></script> 
  <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
 

Now give the content (you want to convert to pdf) an id as shown below:


<body>
  <div id="target">
     (your content goes here........) 
  </div>  
  <div>
     <a href="javascript:void(0)" id="cmd">generate PDF</a>
  </div>
</body>
       

Next for the script part:

  
  <script type="text/javascript">
      $(document).ready(function(){

          var specialElementHandlers = {
              '#editor': function (element,renderer) {
                  return true;
              }
          };
          $('#cmd').click(function () {
              var doc = new jsPDF();
              var source = $('#target').html();
              var specialElementHandlers = {
                  '#bypassme': function (element, renderer) {
                      return true;
                  }
              };
              doc.fromHTML(source, 0.5, 0.5, {
                  'width': 75,'elementHandlers': specialElementHandlers
              });
              doc.output("dataurlnewwindow");
          });
      });
  </script>
 

Thats all Folks!!!

No comments:

Post a Comment