Introduction
We recently implemented a SharePoint Framework (SPFx) webpart for a consulting firm based out of Alpharetta, Georgia, United States to display the calendar events inside the calendar cells (a custom calendar). The additional requirement was to allow users to export the HTML content of the calendar to a PDF File with all details.
So, in this blog, we will learn how to export the HTML content to a PDF file in a custom webpart implemented using SharePoint Framework (SPFx).
Overview
Below is the overview of the Calendar's HTML content.
Approach
For exporting the content to a PDF file, follow the below steps:
Step 1: Install the npm package "html2canvas" using the command "npm i html2canvas --save".
Step 2: Import the npm package as shown below.
import html2canvas from 'html2canvas';
(window as any).html2canvas = html2canvas;
Step 3: Now, implement the below code for exporting the content to a PDF file.
Below are the points that need to be kept in mind for providing the values.
1. Inside the getElementById() value, user needs to provide the main div "id" property value inside which the overall HTML is been implemented.
2. Inside the jsPDF(), if the user wants to export the content in portrait mode, provide the value as "p" or for exporting the content in landscape mode, provide the value as "l".
3. "imgWidth" and "imgHeight" property values can also be provided manually as per the requirement.
let eventHTMLDiv = document.getElementById('EventsHTML');
html2canvas(eventHTMLDiv)
.then((canvas) => {
var imgData = canvas.toDataURL('image/jpeg', 1.0);
var doc = new jsPDF('l', 'mm', 'a4');
var imgWidth = doc.internal.pageSize.getWidth();
var imgHeight = canvas.height * imgWidth / canvas.width;
doc.addImage(imgData, 'JPEG', 10, 10, imgWidth, imgHeight);
doc.save('September.pdf');
});
Below is the parameters overview for the "addImage()" method.
(method) jsPDF.addImage(imageData: string | HTMLCanvasElement | HTMLImageElement | Uint8Array, format: string, x: number, y: number, w: number, h: number)
1. imageData: Need to provide the canvas converted in Data URL format.
2. format: In which format, the image should be added e.g JPEG/JPG/PNG.
3. x: How much margin should be kept from the top in the PDF file.
4. y: How much margin should be kept from the left in the PDF file.
5. w: width of the canvas.
6. h: height of the canvas.
The Exported content looks like below in the PDF file "September.pdf".
Conclusion
This is how we can export the HTML content to a PDF File using SPFx webpart.
If you have any questions you can reach out our SharePoint Consulting team here.