Adding Watermark to PDF In Lightning Web Component

Let see how to Adding Watermark to PDF Documents with Pdf-lib Library in Lightning Web Component. PDF documents are a widely used file format for sharing and storing important information. Adding watermarks to PDFs can help to protect the information contained in them from being copied or distributed without authorization. In this tutorial, we’ll show you how to add watermarks to PDFs using the Pdf-lib library in a Lightning Web Component (LWC) in Salesforce.

Prerequisites

To follow along with this tutorial, you should have a basic understanding of LWC and Salesforce development. You’ll also need to have a Salesforce Developer account and the Pdf-lib library uploaded as a static resource in your Salesforce org.

You can get the pdf-lib js file from here.

Steps Adding Watermark to PDF In Lightning Web Component

1: Uploading the Pdf-lib Library: We’ll upload the Pdf-lib library in our Salesforce org. To do this, we’ll need to add it as a static resource.

2: Now we will create a LWC component

  • Fetch pdf data attached to a record in base64 format using Apex controller. I have created a getData function which will receive recordId and return all pdf attached to that particular record.
 @AuraEnabled
    public static List<String> getData(String accountId){
        System.debug('ID is '+accountId);
        Map<String,String> mapOfData = new Map<String,String>();
        List<ContentDocumentLink> lsOfCDL = [SELECT Id, LinkedEntityId, ContentDocumentId FROM ContentDocumentLink WHERE LinkedEntityId=:accountId];
        List<Id> tempsId =new List<Id>();
        for(ContentDocumentLink tempLoop:lsOfCDL){
            tempsId.add(tempLoop.ContentDocumentId);
        }
        List<ContentVersion> lsOfCV = [SELECT Id,VersionData,FileExtension FROM ContentVersion WHERE ContentDocumentId=:tempsId];
        List<String> lsOfFiles = new  List<String>();
        for(ContentVersion tempLoopCv :lsOfCV){
            lsOfFiles.add(EncodingUtil.base64Encode(tempLoopCv.VersionData));
            System.debug('File Extension is  '+tempLoopCv.FileExtension);
            if((''+tempLoopCv.FileExtension).toLowerCase() == 'pdf'){
               mapOfData.put(''+tempLoopCv.Id+','+'PDF',EncodingUtil.base64Encode(tempLoopCv.VersionData));    
            }else{
                 mapOfData.put(''+tempLoopCv.Id+','+'PDF',EncodingUtil.base64Encode(tempLoopCv.VersionData));
            }
               
        }
        return lsOfFiles; 
    }
  • Load pdf-lib script in your component by importing pdf-lib from static resource and importing loadscript method from platformResouceLoader:
import pdflib from "@salesforce/resourceUrl/pdflib";
import { loadScript } from "lightning/platformResourceLoader";
  • Inside renderCallback load your script and call your apex controller method to fetch pdf data.
renderedCallback() {        
        if(this.firstCall){
            loadScript(this, pdflib).then(() => {
            });

            console.log('recode ud  ' + this.recordId)
            if (this.recordId) {
                getData({ accountId: this.recordId })
                    .then((result) => {
                        this.docData = JSON.parse(JSON.stringify(result));
                        console.log('Size of File are ' + this.docData.length)
                        this.error = undefined;
                        this.watermark()
                    })
                    .catch((error) => {
                        console.log('error while calling ' + error)
                    })
                 }
            }
    }
  • Now use pdf-lib methods to manipulate you pdf data.
async watermark(){
        var tempBytes = '';
        console.log('tempBytes', tempBytes)
        if (this.docData.length > 0) {
            for (let i = 0; i < this.docData.length; i++) {
                tempBytes = Uint8Array.from(atob(this.docData[i]), (c) => c.charCodeAt(0));
                console.log('tempBtes>> ', tempBytes)
                const usConstitutionPdf = await PDFLib.PDFDocument.load(tempBytes);
                const helveticaFont = await usConstitutionPdf.embedFont(await PDFLib.StandardFonts.Helvetica)
                const rgb = await PDFLib.rgb
                const degrees = await PDFLib.degrees
                console.log('After ', usConstitutionPdf, usConstitutionPdf.getPages())
                const pages = usConstitutionPdf.getPages();
                pages.forEach((firstPage)=>{
                    const { width, height } = firstPage.getSize()
                    firstPage.drawText('Document belongs to XYZ.Ltd', {
                     x: 5,
                     y: height / 2 + 300,
                     size: 50,
                     color: rgb(0.9, 0.2, 0.1),
                     rotate: degrees(-45),
                })

                })
                
            const pdfBytes = await usConstitutionPdf.save()
            this.saveByteArray("My PDF", pdfBytes);
            }
        }   
    }
  • Finally download converted pdf’s
  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();
    	  }

You can get full code here.

Output

Nishchal vashisht
Nishchal vashisht

Nishchal vashisht
5x certified, Developer at Yoti

Articles: 8

2 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *