In this blog you will learn how you can create a PDF in Lightning Web Component. I will use a PDF library to create the PDF.
Please follow steps below :
Official Document : https://pdf-lib.js.org/
Step 1
Save the JS library as static resource in your org as shown below :
https://unpkg.com/pdf-lib@1.16.0/dist/pdf-lib.js
Step 2
Import the library in your lightning web component
1 2 | import pdflib from "@salesforce/resourceUrl/pdflib"; import { loadScript } from "lightning/platformResourceLoader"; |
Step 3
Create a rendercallback to load the Script
1 2 3 | renderedCallback() { loadScript(this, pdflib).then(() => {}); } |
Step 4
Add a button on your Lightning Web Component
1 2 3 4 5 6 7 8 | <template> <lightning-card title="Create PDF File" icon-name="utility:user"> </lightning-card> <div style="background-color: white; padding: 10px"> <lightning-button label="Create PDF" onclick={createPdf}> </lightning-button> </div> </template> |
Step 5
Add create pdf and download function in the Javascript file
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | import { LightningElement } from "lwc"; import pdflib from "@salesforce/resourceUrl/pdflib"; import { loadScript } from "lightning/platformResourceLoader"; export default class CreatePDF extends LightningElement { renderedCallback() { loadScript(this, pdflib).then(() => {}); } async createPdf() { const pdfDoc = await PDFLib.PDFDocument.create(); const timesRomanFont = await pdfDoc.embedFont( PDFLib.StandardFonts.TimesRoman ); const page = pdfDoc.addPage(); const { width, height } = page.getSize(); const fontSize = 30; page.drawText("Learning with Salesforce Bolt !", { x: 50, y: height - 4 * fontSize, size: fontSize, font: timesRomanFont, color: PDFLib.rgb(0, 0.53, 0.71) }); const pdfBytes = await pdfDoc.save(); this.saveByteArray("My PDF", pdfBytes); } saveByteArray(pdfName, byte) { var blob = new Blob([byte], { type: "application/pdf" }); var link = document.createElement("a"); link.href = window.URL.createObjectURL(blob); var fileName = pdfName; link.download = fileName; link.click(); } } |
Output
Checkout Complete video tutorial below
If you have any question please leave a comment below.
If you would like to add something to this post please leave a comment below.
Share this blog with your friends if you find it helpful somehow !
Thanks
Happy Coding :)
1 Comments
I am getting PDFLib is not defined
ReplyDelete