Digital E-Sign Signature In Salesforce

 Digital E-Sign Signature In Salesforce




----------------------------------------------

Step 1.  Create a Quick action button on object in which you want to add. 

Like this :-





----------------------------------------------

Step 2. Create a visual force page and call to aura cmp.

----------------------------------------------

<apex:page sidebar="false" showHeader="false">

<apex:includeLightning />

<!--Lightning Container-->

<div style="width:100% !important;height:!00% !important;" id="LightningContainer"/>

 

<script type="text/javascript">

//Create Lightning Component

$Lightning.use("c:GenerateLogSheetPreviewApp", function() {

$Lightning.createComponent("c:GenerateLogSheetPreviewCmp", { 

recordId : "{!$CurrentPage.parameters.id}" //Method to call from lightning  

},"LightningContainer", function(component) {

console.log('Component created'); 

});

});

</script>

</apex:page>

----------------------------------------------

Aura Cmp : 

----------------------------------------------

<aura:component controller="GenerateLogSheetPreviewCTR" implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction" access="global" >

    <aura:attribute name="onSelectValue" type="String" />

    <aura:attribute name="pdfExportURL" type="String" />

    <aura:attribute name="pdfDomesticURL" type="String" />

    <aura:attribute name="modal" type="boolean" default="FALSE"/>

    <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>

    <aura:attribute name="recordId" type="String" />

    <aura:attribute name="checkloom" type="Boolean" default="false"/>

    <aura:attribute name="checktap" type="Boolean" default="false"/>

    

    <aura:attribute name="checkBCS" type="Boolean" default="false"/>

    <aura:attribute name="checkConvsin" type="Boolean" default="false"/>

    <aura:attribute name="checkLemicoat" type="Boolean" default="false"/>

    <aura:attribute name="checkLofil" type="Boolean" default="false"/> 

    

    <aura:attribute name="checkPrinting" type="Boolean" default="false"/> 

    <aura:attribute name="checkValvomatic" type="Boolean" default="false"/> 

    <aura:attribute name="signatureModalShow" type="Boolean" default="false"/> 

    <aura:attribute name="spinner" type="boolean" default="false"/>

    

    <ltng:require styles="{!$Resource.ModalWidthCSS}"/>

    <aura:attribute name="isPhone" type="Boolean" />

    

    <div style="height:90% " >       

        <header class="slds-modal__header">

            <lightning:buttonIcon iconName="utility:close"

                                  onclick="{! c.closeModel }"

                                  alternativeText="close"

                                  variant="bare-inverse"

                                  class="slds-modal__close"/>

            <div >   <h2 id="modal-heading-01" class="slds-text-heading_medium slds-hyphenate slds-align_absolute-center">Log Sheet Preview</h2></div>

        </header>

        

        <aura:if isTrue="{!$Browser.isDesktop}">

            <div style="height:90% !important" >

                <aura:if isTrue="{!v.checkloom}">

                    <div  class="slds-align_absolute-center">

                        <iframe src="{! '/apex/NewLogSheetLoom?Id=' + v.recordId}" frameBorder="0" width="1000px" height="800px"/>

                    </div>

                </aura:if>

                <aura:if isTrue="{!v.checktap}">

                    <div  class="slds-align_absolute-center">

                        <iframe src="{! '/apex/LogsheetTapeline?Id=' + v.recordId}" frameBorder="0" width="1000px" height="800px"/>

                    </div>

                </aura:if>

                

                <aura:if isTrue="{!v.checkBCS}">

                    <div  class="slds-align_absolute-center">

                        <iframe src="{! '/apex/bCSLogSheet?Id=' + v.recordId}" frameBorder="0" width="1000px" height="800px"/>

                    </div>

                </aura:if>

                

                <aura:if isTrue="{!v.checkLemicoat}">

                    <div  class="slds-align_absolute-center">

                        <iframe src="{! '/apex/CoaetecLogSheet?Id=' + v.recordId}" frameBorder="0" width="1000px" height="800px"/>

                    </div>

                </aura:if>

                <aura:if isTrue="{!v.checkLofil}">

                    <div  class="slds-align_absolute-center">

                        <iframe src="{! '/apex/LogSheetLofil?Id=' + v.recordId}" frameBorder="0" width="1000px" height="800px"/>

                    </div>

                </aura:if>

                <aura:if isTrue="{!v.checkPrinting}">

                    <div  class="slds-align_absolute-center">

                        <iframe src="{! '/apex/PrintingLogSheet?Id=' + v.recordId}" frameBorder="0" width="1000px" height="800px"/>

                    </div>

                </aura:if>

                <aura:if isTrue="{!v.checkValvomatic}">

                    <div  class="slds-align_absolute-center">

                        <iframe src="{! '/apex/ValvomaticLogSheet?Id=' + v.recordId}" frameBorder="0" width="1000px" height="800px"/>

                    </div>

                </aura:if>

            </div>

        </aura:if>

        <aura:if isTrue="{!$Browser.isPhone}">

            <div style="height:85% !important" >

                <div  class="slds-align_absolute-center">

                    <iframe src="{! '/apex/generateEsignVFPage?Id=' + v.recordId}" frameBorder="0" width="1000px" height="800px"/>

                </div>

            </div>

        </aura:if>

        <aura:if isTrue="{!v.modal}">

            <div class="slds-grid slds-gutters">

                <div class="slds-col">

                    <aura:if isTrue="{!v.modal}">

                        <div class="modal">

                            <section role="dialog" tabindex="-1" aria-modal="true" aria-labelledby="modal-heading-01" class="slds-modal slds-fade-in-open">

                                <div class="slds-modal__container">

                                    <button class="slds-button slds-button_icon slds-modal__close slds-button_icon-inverse" onclick="{! c.closeModel }">

                                        X

                                    </button>

                                    <div class="slds-modal__header">

                                        <h1 id="modal-heading-01" class="slds-modal__title slds-hyphenate">Signature Pad</h1>

                                    </div>

                                    <div class="slds-modal__content slds-p-around_medium" id="modal-content-id-1">

                                        <c:e_sign_generate aura:id="lWCComponent2" recId="{!v.recordId}"></c:e_sign_generate>

                                    </div>

                                </div>

                            </section>

                            <div class="slds-backdrop slds-backdrop_open" role="presentation"></div>

                        </div>    

                    </aura:if>

                </div>

            </div>

        </aura:if>

    </div>

    <footer class="slds-modal__footer">

        <!--

 <c:e_sign_generate aura:id="lWCComponent2" recId="{!v.recordId}"></c:e_sign_generate>

  <aura:if isTrue="{!v.deas}">

            

            <lightning:button variant="neutral"

                              label="Send Email"

                              title="SendEmail" 

                              disabled="{!v.deas}"                                

                              onclick="{!c.SendEmail}"/>

        </aura:if>-->

        <lightning:button variant="neutral"

                          label="Add Signature"

                          title="Cancel"  

                          onclick="{! c.callChilLWCdMethod }"/>

        <aura:if isTrue="{!v.spinner}">

            <lightning:button variant="neutral"

                              label="Delete Signature"

                              title="Cancel"  

                              onclick="{! c.deleteSignature }"/>

        </aura:if>

        <lightning:button variant="neutral"

                          label="Cancel"

                          title="Cancel"  

                          onclick="{! c.closeModel }"/>

        

        <!-- <aura:if isTrue="{!!v.deas}">

            <lightning:button variant="brand"

                              label="Save"                                     

                              title="Save"

                              disabled="{!v.deas}"    

                              onclick="{!c.submitRecord}"/>

        </aura:if>-->

    </footer>

    

    <!--Modal/Popup Box Footer Starts here-->       

    <!--</div>

    </section>

    <div class="slds-backdrop slds-backdrop_open"></div>-->

    

</aura:component>

-------------------------------------------------------

JS Controller 

-------------------------------------------------------

({

    doInit: function(component, event, helper) {

        var device = $A.get("$Browser.formFactor");

        component.set("v.device",device);

        var recordId = component.get('v.recordId');   

        var action = component.get('c.getBooleanValue');

        action.setParams({

            recordId: component.get('v.recordId')

        });

        action.setCallback(this, function(response) {

            var state = response.getState();

            if (state === "SUCCESS") {

                var storeResponse = response.getReturnValue();

                component.set("v.spinner", storeResponse);

            } 

        });

        $A.enqueueAction(action);

        var action=  component.get('c.getRecordTypeName');

        var recId = component.get('v.recordId');   

        //alert('recId'+ recId);

        action.setParams({'recordId':recId});

        action.setCallback(this,function(response)   // getting response back from apex method

                           {

                               console.log(response);

                               var state=response.getState();            // getting the state

                               if(state==="SUCCESS")

                               { 

                                   var res = response.getReturnValue(); 

                                   

                                   if(res=="Loom"){

                                       component.set('v.checkloom',true);                                      

                                       

                                   }else if(res=="Tapeline"){

                                       component.set('v.checktap',true);  

                                       

                                   }else if(res=="BCS"){

                                       component.set('v.checkBCS',true);  

                                   }else if(res=="Conversion"){

                                       component.set('v.checkConvsin',true); 

                                   }else if(res=="Lamicoat"){

                                       component.set('v.checkLemicoat',true); 

                                   }else if(res=="Lofil"){

                                       component.set('v.checkLofil',true); 

                                   }else if(res=="Printing"){

                                       component.set('v.checkPrinting',true); 

                                   }else if(res=="Valvomatic"){

                                       component.set('v.checkValvomatic',true); 

                                   }  

                               }

                           });

        $A.enqueueAction(action);

    },

    closeModel2: function(component, event, helper) {

        window.location  = '/apex/GenerateLogSheetPreviewPage?Id=' + component.get("v.recordId");

    },

    closeModel: function(component, event, helper) {

        window.location.href  = '/' + component.get("v.recordId");

    },

    callChilLWCdMethod : function(component, event, helper){ 

        component.set('v.modal',true);

        component.find('lWCComponent2').LWCFunction ();

    },

    deleteSignature: function(component, event, helper){ 

        var recordId = component.get('v.recordId');   

        var action = component.get('c.findRecordId');

        action.setParams({

            recordId: component.get('v.recordId')

        });

        action.setCallback(this, function(response) {

            var state = response.getState();

            if (state === "SUCCESS") {

                //component.set("v.spinner", true); 

                window.location='/apex/GenerateLogSheetPreviewPage?Id='+ component.get("v.recordId");

            } 

        });

        $A.enqueueAction(action);   

    }

})

-------------------------------------------------------

CSS(Style)

-------------------------------------------------------

@media screen and (min-width: 600px) {

  .THIS .slds-modal__container{

    width:35% !important;

  }

}

.THIS slds-modal__header{    

}

.THIS .selectOption{ 

    width:20% !important;

}

.THIS .slds-modal__container{

    /*max-width: 35rem !important;

    width:40% !important;

    max-height: 35rem !important;

    height:180% !important;*/

}

-------------------------------------------------------

Apex Contoller

-------------------------------------------------------

public class GenerateLogSheetPreviewCTR {

    @AuraEnabled 

    public static boolean getBooleanValue(String recordId){

        Visit_Logsheet_Detail__c vstObj = [select id, RecordType.name from Visit_Logsheet_Detail__c where id =: recordId];

        String matchRecTypName = 'Record Type Name = '+ vstObj.RecordType.name + ' '+ vstObj.Id;

        List<Attachment> attchMentRecLst = [select id, name, parentId from Attachment where name =: matchRecTypName AND parentId =: recordId order by CreatedDate desc];

        if(attchMentRecLst.size() > 0){

            System.debug('true');

        return true;  

        }

        return false;

    }

    

    @AuraEnabled 

    public static string findRecordId(String recordId) {

        System.debug('recordId :'+ recordId);

        Visit_Logsheet_Detail__c vstObj = [select id, RecordType.name from Visit_Logsheet_Detail__c where id =: recordId];

        String matchRecTypName = 'Record Type Name = '+ vstObj.RecordType.name + ' '+ vstObj.Id;

        List<Attachment> attchMentRecLst = [select id, name, parentId from Attachment where name =: matchRecTypName AND parentId =: recordId order by CreatedDate desc];

        System.debug('Size : '+ attchMentRecLst.size());

        List<Attachment> deletedList = new List<Attachment>();

        for(Integer i = 0 ; i <attchMentRecLst.size(); i++){

            deletedList.add(attchMentRecLst[i]);

        }

        if(!deletedList.isEmpty()){

            System.debug('deletedList '+ deletedList);

            Delete deletedList;

        }

        System.debug('attchMentRecLst size '+ attchMentRecLst.size());

        return null;

    }

    

    @AuraEnabled  

    public static String getRecordTypeName(String recordId){

        String recordType;

        Visit_Logsheet_Detail__c vistLogSheet =[select id,RecordTypeId from Visit_Logsheet_Detail__c where Id=:recordId];

        recordType= Schema.SObjectType.Visit_Logsheet_Detail__c.getRecordTypeInfosById().get(vistLogSheet.RecordTypeId).getName();

        System.debug(recordType);

        return recordType;

    }

}

-------------------------------------------------------

Step 3 - Create a LWC Cmp 

-------------------------------------------------------

<template>   

    <lightning-card if:true={oldSignVisible}>

        <div style="margin-top:-20px;">

            <canvas style="border:0px solid black;" data-id="canvas" margin-top="-50px" width="720px" height="220px" lwc:dom="manual"></canvas>

        </div>

        <!--<div class="slds-p-around_x-small"><iframe class="frame" src={oldSign}></iframe></div>-->

        <!--<lightning-button variant="brand" class="slds-float_left slds-m-top_small slds-m-right_small" label="Add Signature" onclick={handleAfterNext}></lightning-button>

        --></lightning-card>

        <div class="slds-modal__footer">        

                        <button class="slds-button slds-button_neutral" onclick={cancelBtn} aria-label="Cancel and close">Cancel</button>

                        <button class="slds-button slds-button_brand" disabled={isSignaturePresent} onclick={handleAfterNext}>Save Signature</button>

                    </div>

        <div class="exampleHolder" if:true={spinner}>

        <lightning-spinner alternative-text="Loading" size="medium"></lightning-spinner>

        </div>

</template>

-------------------------------------------------

JS Part LWC 

-------------------------------------------------

import { LightningElement, wire, api, track } from 'lwc';

import { loadScript } from 'lightning/platformResourceLoader';

import fabricJS from '@salesforce/resourceUrl/fabricJsFile';

import createAttachment from '@salesforce/apex/EsignCtrl.createAttachment';

import getAttachmentId from '@salesforce/apex/EsignCtrl.getAttachmentId';

export default class E_sign_generate extends LightningElement {

   // isCanvasChanged = false;

    signatureCanvas;

  isSignaturePresent = false;

    btnEditable = false;

    @api recId; 

    DisplayText = false;

    @api id;

    spinner = false;

    @api img;

    canvas;

    @api myBooleanValue = false;

    showImg;

    showBeforePreview = true;

    showSign = false;

    showAfterPreview = false;

    canvasLoaded = false;

    img = ''; 

    @api myBooleanVariable = false;

    

    @api myBoolean = false;


    //@api recordId;

    @track oldSignVisible = true;

    //@track oldSign;

    

  @wire(getAttachmentId, { recordId: '$recId' })

  wiredGetAttachmentId({ error, data }) {

    if (data) {

        //this.oldSignVisible = true;

      //this.oldSign = data;

      //console.log('abc '+ oldSign);

    } else if (error) {

        console.log('err');

      console.error(error);

    }

  }

    

    

    connectedCallback() { 

   /* this.canvas.on('path:created', () => {

this.isCanvasChanged = true;

});  */

        // Load the Fabric JS library

        loadScript(this, fabricJS)

            .then(() => {

                const canvasEl = this.template.querySelector('[data-id="canvas"]');

                console.log('abc'+canvasEl);

                // Create a Fabric JS canvas

                this.canvas = new fabric.Canvas(canvasEl);


                // Enable free drawing mode

                this.canvas.isDrawingMode = true;

                this.canvas.freeDrawingBrush.color = 'black';

                this.canvas.freeDrawingBrush.width = 5;

                this.canvas.freeDrawingLineWidth = 5;

                console.log('loaded...');

            })

            .catch((error) => {

                console.log('error: ' + error);

            });

    }

    handleClick(){

        console.log(this.canvas.toDataURL());

    }

    textValue='LWC Function Invoked through Aura Component'  

    @api LWCFunction()

    {

        //alert(oldSignVisible);

        console.log('isVisible '+this.oldSignVisible);

        //this.oldSignVisible = false; 

    }


    handleAfterNext() {

        this.spinner = true;

        /*

if (!this.isCanvasChanged) {

// Display an error message and return without generating the base64 code

alert('Please draw something on the canvas before saving your signature.');

this.spinner = false;

return;

}

*/

        this.signatureCanvas = this.template.querySelector('[data-id="canvas"]');

        this.signatureCanvas.addEventListener('mousemove', this.captureSignature);

        console.log('btn '+ this.signatureCanvas);

        this.img = '';

        this.img = this.canvas.toDataURL().split(',')[1];

        console.log('this.img'+this.img);

        //if(this.img != ''){

        createAttachment({baseImg: this.img, recordID: this.recId})

            .then(result => {

                this.showImg = result;

                //alert('showImg '+ showImg);

                window.location='/apex/GenerateLogSheetPreviewPage?Id='+this.recId;

                //window.location='https://lohiacorplimited--qa.sandbox.lightning.force.com/lightning/r/Visit_Logsheet_Detail__c/'+this.recId+'/view'; return false;

                /*this.showAfterPreview = true;

                this.oldSign2 = true;

                

                if(this.showImg != ''){

                    const evt = new ShowToastEvent({

                        title: 'Toast Success',

                        message: 'Signature added on PDF Document',

                        variant: 'success',

                        mode: 'dismissable'

                    });

                    this.dispatchEvent(evt);

                }*/

            })

            .catch(error => {

            });

        this.showBeforePreview = false;

        this.showSign = false;

    }


   // }

    showSuccessToast() {

    const evt = new ShowToastEvent({

        title: 'Toast Success',

        message: 'Opearion sucessful',

        variant: 'success',

        mode: 'dismissable'

    });

    this.dispatchEvent(evt);

    }

    changeSignature(){

        this.spinner = true;

    }

    cancelBtn(){

        this.spinner = true;

        window.location='/apex/GenerateLogSheetPreviewPage?Id='+this.recId; 

        //window.location='https://lohiacorplimited--qa.sandbox.lightning.force.com/lightning/r/Visit_Logsheet_Detail__c/'+this.recId+'/view'; return false;

    }

}

----------------------------------------

Apex class of LWC

--------------------------

public class EsignCtrl {

    public Attachment attachment { get; set; }

    public String myInput { get; set; }

    public String myOutput { get; set; }

    public String pdfContent { get; set; }

    public Boolean isPdf { get; set; }

    Public Id urlImg { get; set; }

    Public String MstrID { get; set; }

    public EsignCtrl(ApexPages.StandardController stdController){

        MstrID =  stdController.getId();

        System.debug('MstrID '+ MstrID);

    }

    @AuraEnabled(cacheable = true)

    public static string getAttachmentId(string recordId){

        String urlImg;

        System.debug('Hello'+ recordId);

        Visit_Logsheet_Detail__c vstObj = [select id, RecordType.name from Visit_Logsheet_Detail__c where id =: recordId];

        String matchRecTypName = 'Record Type Name = ' + vstObj.RecordType.name + ' '+ vstObj.Id;

        System.debug('matchRecTypName : '+ matchRecTypName);

        List<Attachment> attchMentRec = [select id, name, parentId from Attachment where name =: matchRecTypName AND parentId =: vstObj.Id order by CreatedDate desc limit 1];

        if(!attchMentRec.isEmpty()){

            System.debug('YES');

            urlImg = URL.getSalesforceBaseUrl().toExternalForm() + '/servlet/servlet.FileDownload?file=' + attchMentRec[0].Id;

            System.debug('urlImg : '+ urlImg);

            System.debug('parentid '+ attchMentRec[0].parentId);

            return urlImg;

        }

        return null;//getDetails.contactCount;

    }

    

    @AuraEnabled

    public static String getDocuments(String recordId){

        Contact con = [SELECT id FROM Contact WHERE id = :recordId];

        List<ESignDocumentListWrapper> docLst = new List<ESignDocumentListWrapper>();

        for(ContentDocumentLink doc:[SELECT Id,ContentDocumentId,ContentDocument.Title, LinkedEntityId,ContentDocument.FileExtension FROM ContentDocumentLink WHERE ContentDocument.FileExtension = 'pdf' and LinkedEntityId = :con.id]){

            ESignDocumentListWrapper obj = new ESignDocumentListWrapper();

            obj.docId = doc.Id;

            obj.docTitle = doc.ContentDocument.Title;

            obj.LinkedEntityId = doc.LinkedEntityId;

            obj.ContentDocumentId = doc.ContentDocumentId;

            obj.docExt = doc.ContentDocument.FileExtension;

            obj.url = '/sfc/servlet.shepherd/version/download/'+doc.ContentDocumentId;

            docLst.add(obj);

        }

        return JSON.serialize(docLst);

    }

    

    @AuraEnabled

    public static String createAttachment(String baseImg,String recordID){

        Visit_Logsheet_Detail__c vstObj = [select id, RecordType.name from Visit_Logsheet_Detail__c where id =: recordID];

        Blob imageBlob = EncodingUtil.base64Decode(baseImg);

        Attachment attachment = new Attachment();

        attachment.Name = 'Record Type Name = '+ vstObj.RecordType.name + ' '+ vstObj.Id;

        String matchRecTypName = attachment.Name;

        attachment.Body = imageBlob;

        attachment.ContentType = 'image/png; charset=UTF-8'; // change this to match the image type

        attachment.ParentId = recordID;

        insert attachment;

        System.debug('attachment :'+attachment);

        List<Attachment> attchMentRecLst = [select id, name, parentId from Attachment where name =: matchRecTypName AND parentId =: recordId order by CreatedDate desc];

        System.debug('Size : '+ attchMentRecLst.size());

        if(attchMentRecLst.size() > 1){

            List<Attachment> deletedList = new List<Attachment>();

            for(Integer i = 1 ; i <attchMentRecLst.size(); i++){

                deletedList.add(attchMentRecLst[i]);

            }

            if(!deletedList.isEmpty()){

                System.debug('deletedList '+ deletedList);

                Delete deletedList;

            }

System.debug('attchMentRecLst size '+ attchMentRecLst.size());

}

        String url = URL.getSalesforceBaseUrl().toExternalForm() + '/servlet/servlet.FileDownload?file=' + attachment.Id;

        /*PageReference savepage ;

        savepage = Page.logSheetLofil;

        savepage.getParameters().put('id',recordID);

        system.debug('id:- '+recordID);

        Blob conVfBlob;

        if (!Test.isRunningTest()) {

            System.debug('If');

            conVfBlob = savepage.getContent();

        }

        if(conVfBlob != Null){

            System.debug('Yesssss');

            Attachment attachment1 = new Attachment();

            attachment1.Name = vstObj.RecordType.Name +' Document PDF Attachment';

            attachment1.Body = conVfBlob;

            attachment1.ContentType = 'application/pdf'; // change this to match the image type

            attachment1.ParentId = recordID;

            insert attachment1;    

        }*/

        return url;

        }       

    }

-------------------------------------------------------

For mobile view beacause RenderAs Not support in SF mobile

-------------------------------------------------------

Step 4. Create a visualforce page for mobile view 

-------------------------------------------------------

 <apex:page standardController="Visit_Logsheet_Detail__c" action="{!pdfAction}" extensions="GenerateESignCtrl" showHeader="false" title="Quotation PDF" >

    <apex:outputPanel >

        <apex:iframe height="700px"  width="390px" src="{!attachmentLink}"/>

    </apex:outputPanel>

</apex:page>


-------------------------------------------

Apex controller for mobile

-------------------------------------------

public class GenerateESignCtrl {

    Public String MstrID { get; set; }

    public String attachmentLink{get;set;}

    public GenerateESignCtrl(ApexPages.StandardController stdController){

        MstrID =  stdController.getId(); 

    }

    public PageReference pdfAction(){ 

        PageReference savepage ;

        Visit_Logsheet_Detail__c vstObj = [select id, RecordType.name from Visit_Logsheet_Detail__c where id =: MstrID];

        if(vstObj.RecordType.name == 'Lofil'){

            savepage = Page.logSheetLofil;

            savepage.getParameters().put('id',MstrID);

            system.debug('id:- '+MstrID);

        }else if(vstObj.RecordType.name == 'Lamicoat'){

            savepage = Page.CoaetecLogSheet;

            savepage.getParameters().put('id',MstrID);

            system.debug('id:- '+MstrID);

        }else if(vstObj.RecordType.name == 'Tapeline'){

            savepage = Page.LogsheetTapeline;

            savepage.getParameters().put('id',MstrID);

            system.debug('id:- '+MstrID);

        }else if(vstObj.RecordType.name == 'Loom'){

            savepage = Page.NewLogSheetLoom;

            savepage.getParameters().put('id',MstrID);

            system.debug('id:- '+MstrID);

        }else if(vstObj.RecordType.name == 'Valvomatic'){

            savepage = Page.ValvomaticLogSheet;

            savepage.getParameters().put('id',MstrID);

            system.debug('id:- '+MstrID);

        }else if(vstObj.RecordType.name == 'Printing'){

            savepage = Page.PrintingLogSheet;

            savepage.getParameters().put('id',MstrID);

            system.debug('id:- '+MstrID);

        }else if(vstObj.RecordType.name == 'BCS'){

            savepage = Page.bCSLogSheet;

            savepage.getParameters().put('id',MstrID);

            system.debug('id:- '+MstrID);

        }

        blob pdfBlob;

        if (!Test.isRunningTest()) {

            System.debug('If');

            pdfBlob = savepage.getContent();

        }

        if(pdfBlob != Null){

            ContentVersion newContentVersion = new ContentVersion();

            newContentVersion.ContentLocation = 'S'; // S indicates that the file is stored in Salesforce

            newContentVersion.PathOnClient = 'file_name.pdf'; // set the file name

            newContentVersion.Title = 'File Title'; // set the file title

            newContentVersion.VersionData = pdfBlob; // set the file content

            insert newContentVersion;

            attachmentLink = createCDLink(newContentVersion.Id,'test');

            System.debug('createCDLink: '+attachmentLink);    

        }

        return null;

    }  

    

    

    private String createCDLink(String contentVersionId,String name){

        Visit_Logsheet_Detail__c vstObj = [select id, RecordType.name from Visit_Logsheet_Detail__c where id =: MstrID];

        String pdfUrl = '';

        ContentDistribution cd = new ContentDistribution();

        cd.ContentVersionId = contentVersionId;

        // Set the desired sharing options

        cd.PreferencesAllowViewInBrowser = true;

        cd.PreferencesAllowOriginalDownload = true;

        cd.Name = name + MstrID + vstObj.RecordType.name;

        String machedStr = name +''+ vstObj.RecordType.name;

        System.debug('machedStr : '+ machedStr);

        System.debug('CD Name : '+ cd.Name);

        insert cd;

        pdfUrl = [select DistributionPublicUrl from ContentDistribution where id =:cd.id AND Name=: cd.Name limit 1].DistributionPublicUrl;

        List<ContentDistribution> conDisLst = [Select Id, DistributionPublicUrl from ContentDistribution Where Name =: cd.Name Order by CreatedDate desc];

        List<ContentDistribution> deletedLst = new List<ContentDistribution>();

        System.debug('conDisLst Size :'+ conDisLst.size());

        if(conDisLst.size() > 1){

            for(Integer i = 1; i < conDisLst.size(); i++){

                deletedLst.add(conDisLst[i]);

            }

            System.debug('deletedLst'+ deletedLst);

            Delete deletedLst;

        }

        return pdfUrl;

    }

}



Comments

Popular posts from this blog

Custom List View Button In Salesforce

Get Record Id RecordId in LWC

PDF LWC (Link for pdf liabrary)