Saturday, June 3, 2017

Client side PDF generation


We can generate PDF in JavaScript using jsPDF library.

Edit in plkr

Steps involved
  • Use CDN reference to jsPDF 
  • Open the document
  • Pass the Json Object to the document
  • Save the file

 <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.4/jspdf.debug.js"></script>
      
<script>
var module=angular.module("myApp",[])
module.controller("cntrl", function($scope)
{
  $scope.Employee=[
     { "FirstName" :"Prathap",
       "LastName"  :"Kudupu"
     },
     { "FirstName" :"Atharv",
       "LastName"  :"Kudupu"
     }
    ];
  
//Open the document  
var doc = new jsPDF();
//Loop through the JSON object
$scope.Employee.forEach(function(employee, i){
    doc.text(20, 10 + (i * 10), 
        "First Name: " + employee.FirstName +
        "Last Name: " + employee.LastName);
});
doc.save('employee.pdf');
});
</script>

No comments:

Post a Comment