Generate PDF Document In Spfx

Introduction

 
JSPDF is a powerful plugin to play with pdf in Clientside. html2canvas is a plugin to take screenshots of web pages of users' browsers. The screenshot is based on the element of html provided .
 
Here we are using a combination of both to achieve our goal .
 
Intially we want to construct an html dom element and take a snapshot as a image format with the help of html2canvas plugin and next convert the image into base64 format using,
  1. canvas.toDataURL('image/png');  
Once canvas part is completed, we have  to intiate jspdf plugin to generate  and download pdf.
  1. new jsPDF('p''mm''a4');  
 As  I mentioned earlier here we are using canvas screenshot to save as pdf, for that jspdf provides a method name as follows:
  1. addImage(imageData, format, x, y, width, height, alias, compression, rotation)  
  And finally save method in jspdf plugin used to download the generated pdf file in our local machine
  1. save(filename, options)  
eg. save("mypdf.pdf");
 
Let's make its practical.
 
Open a command prompt. Create a directory for the SPFx solution.
 
md spfx-Pdf
 
Navigate to the above-created directory.
 
cd spfx-Pdf
 
Run the Yeoman SharePoint Generator to create the solution.
 
yo @microsoft/sharepoint
 
Solution Name
 
Hit Enter to have the default name (spfx-Pdf in this case) or type in any other name for your solution.
Selected choice - Hit Enter
 
Target for the component
 
Here, we can select the target environment where we are planning to deploy the client web part, i.e., SharePoint Online or SharePoint OnPremise (SharePoint 2016 onwards).
Selected choice - SharePoint Online only (latest).
 
Place of files
 
We may choose to use the same folder or create a subfolder for our solution.
Selected choice - Same folder
 
Deployment option
 
Selecting Y will allow the app to be deployed instantly to all sites and be accessible everywhere.
Selected choice - N (install on each site explicitly)
 
Permissions to access web APIs
 
Choose if the components in the solution require permission to access web APIs that are unique and not shared with other components in the tenant.
Selected choice - N (solution contains unique permissions)
 
Type of client-side component to create
 
We can choose to create a client-side web part or an extension. Choose the web part option.
Selected choice - WebPart
 
Web part name
 
Hit Enter to select the default name or type in any other name.
Selected choice - SpfxPdf
 
Web part description
 
Hit Enter to select the default description or type in any other value.
 
Framework to use
 
Select any JavaScript framework to develop the component. Available choices are - No JavaScript Framework, React, and Knockout.
Selected choice - React
 
The Yeoman generator will perform a scaffolding process to generate the solution. The scaffolding process will take a significant amount of time.
 
Once the scaffolding process is completed, lock down the version of project dependencies by running the below command,
 
npm shrinkwrap
 
In the command prompt, type the below command to open the solution in the code editor of your choice.
 
 
NPM Packages Used,
 
On the command prompt, run the below commands
  1. npm i jspdf --save    
  2. npm i  html2canvas --save  
  3. npm i @types/jspdf --save  
in SpfxPdf.tsx,
  1. import * as React from 'react';  
  2. import { ISpfxPdfProps } from './ISpfxPdfProps';  
  3. import * as jsPDF from 'jspdf';  
  4. import html2canvas from 'html2canvas';  
  5. require('./tablestyle.css');  
  6. export default class SpfxPdf extends React.Component<ISpfxPdfProps, {}> {  
  7.   public documentprint = (e) => {  
  8.     e.preventDefault();  
  9.     const myinput = document.getElementById('mypdf');  
  10.     html2canvas(myinput)  
  11.       .then((canvas) => {  
  12.         var imgWidth = 200;  
  13.         var pageHeight = 290;  
  14.         var imgHeight = canvas.height * imgWidth / canvas.width;  
  15.         var heightLeft = imgHeight;  
  16.         const imgData = canvas.toDataURL('image/png');  
  17.         const mynewpdf = new jsPDF('p''mm''a4');  
  18.         var position = 0;  
  19.         mynewpdf.addImage(imgData, 'JPEG', 5, position, imgWidth, imgHeight);  
  20.         mynewpdf.save("mypdf.pdf");  
  21.       });  
  22.   }  
  23.   public render(): React.ReactElement<ISpfxPdfProps> {  
  24.     return (  
  25.       <div>  
  26.         <div id="mypdf">  
  27.           <br />  
  28.           <table>  
  29.             <tbody>  
  30.               <tr>  
  31.                 <th>Name</th>  
  32.                 <th>City</th>  
  33.                 <th>Country</th>  
  34.               </tr>  
  35.               <tr>  
  36.                 <td>Madhan Thurai</td>  
  37.                 <td>Chennai</td>  
  38.                 <td>India</td>  
  39.               </tr>  
  40.               <tr>  
  41.                 <td>Reghu</td>  
  42.                 <td>Madurai</td>  
  43.                 <td>India</td>  
  44.               </tr>  
  45.               <tr>  
  46.                 <td>Ananth</td>  
  47.                 <td>Nagercoil</td>  
  48.                 <td>India</td>  
  49.               </tr>  
  50.               <tr>  
  51.                 <td>Vanitha</td>  
  52.                 <td>Cuddalore</td>  
  53.                 <td>India</td>  
  54.               </tr>  
  55.               <tr>  
  56.                 <td>Boopathi</td>  
  57.                 <td>Dindigul</td>  
  58.                 <td>India</td>  
  59.               </tr>  
  60.               <tr>  
  61.                 <td>Risha</td>  
  62.                 <td>Tirunelveli</td>  
  63.                 <td>India</td>  
  64.               </tr>  
  65.             </tbody>  
  66.           </table>  
  67.   
  68.         </div>  
  69.         <button onClick={this.documentprint} >  
  70.           Generate Pdf  </button>  
  71.       </div>  
  72.     );  
  73.   }  
  74. }  
in tablestyle.css,
  1. table {    
  2.     font-familyarialsans-serif;    
  3.     border-collapsecollapse;    
  4.     width100%;    
  5. }    
  6.   
  7. th {    
  8.     border1px solid #dddddd;    
  9.     text-alignleft;    
  10.     padding8px;    
  11.     backgroundred;  
  12.     colorwhite;  
  13. }    
  14. td {  
  15.     border1px solid #dddddd;    
  16.     text-alignleft;    
  17.     padding8px;   
  18.      
  19. }   
  20. tr:nth-child(even) {    
  21.     background-color#dddddd;    
  22. }    
Dom Output
 
Generate PDF Document In Spfx
 
Generated Pdf output
 
Generate PDF Document In Spfx
 

Conclusion

 
From this article we have learned about generating pdf documents in spfx using jspdf and html2canvas plugin. I hope this helps someone. Happy coding :)