PDF LWC (Link for pdf liabrary)

Link for pdf liabrary

https://automationchampion.com/2024/05/27/a-step-by-step-guide-to-merging-and-displaying-pdfs-in-salesforce-2/


public class QuoteFileService {

    @AuraEnabled(cacheable=true)

    public static List<Map<String, String>> getPdfFilesWithIdsAsBase64(Id opportunityId) {

        // List of statuses in the required order

        List<String> statusOrder = new List<String>{'Accepted','Denied','Rejected','Approved','In Review','Needs Review','Draft'};

                    

        // Find all quotes related to the given opportunity

        List<Quote> quotes = [SELECT Id, Status FROM Quote WHERE OpportunityId = :opportunityId];

        

        // Collect all quote IDs

        Set<Id> quoteIds = new Set<Id>();

        Map<Id, String> quoteStatusMap = new Map<Id, String>();

        for (Quote quote : quotes) {

            quoteIds.add(quote.Id);

            quoteStatusMap.put(quote.Id, quote.Status);

        }

        

        // Find all content document links related to the quotes

        List<ContentDocumentLink> contentDocumentLinks = [

            SELECT ContentDocumentId, LinkedEntityId

            FROM ContentDocumentLink

            WHERE LinkedEntityId IN :quoteIds

        ];

        

        // Collect all content document IDs from the links

        Set<Id> contentDocumentIds = new Set<Id>();

        for (ContentDocumentLink cdl : contentDocumentLinks) {

            contentDocumentIds.add(cdl.ContentDocumentId);

        }

        

        // Find all content versions based on the content document IDs

        List<ContentVersion> contentVersions = [

            SELECT ContentDocumentId, VersionData, CreatedDate

            FROM ContentVersion

            WHERE ContentDocumentId IN :contentDocumentIds

            ORDER BY CreatedDate DESC

        ];

        

        // Map content document ID to its content versions

        Map<Id, List<ContentVersion>> documentVersionsMap = new Map<Id, List<ContentVersion>>();

        for (ContentVersion version : contentVersions) {

            if (!documentVersionsMap.containsKey(version.ContentDocumentId)) {

                documentVersionsMap.put(version.ContentDocumentId, new List<ContentVersion>());

            }

            documentVersionsMap.get(version.ContentDocumentId).add(version);

        }

        

        // Prepare the list of files with their IDs and base64 data

        List<Map<String, String>> pdfFilesWithIds = new List<Map<String, String>>();

        for (String status : statusOrder) {

            for (Quote quote : quotes) {

                if (quote.Status == status) {

                    List<ContentVersion> allVersionsForQuote = new List<ContentVersion>();

                    for (ContentDocumentLink link : contentDocumentLinks) {

                        if (link.LinkedEntityId == quote.Id && documentVersionsMap.containsKey(link.ContentDocumentId)) {

                            allVersionsForQuote.addAll(documentVersionsMap.get(link.ContentDocumentId));

                        }

                    }

                    allVersionsForQuote.sort();

                    

                    for (ContentVersion version : allVersionsForQuote) {

                        Map<String, String> pdfData = new Map<String, String>();

                        pdfData.put('ContentDocumentId', version.ContentDocumentId);

                        pdfData.put('Base64Data', EncodingUtil.base64Encode(version.VersionData));

                        pdfFilesWithIds.add(pdfData);

                    }

                }

            }

        }

        

        return pdfFilesWithIds;

    }

}



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


<template>

    <lightning-card title="Merged PDF Viewer">

        <template if:true={mergedPdfUrl}>

            <iframe src={mergedPdfUrl} width="100%" height="1400px"></iframe>

        </template>

        <template if:false={mergedPdfUrl}>

            <lightning-spinner alternative-text="Hang tight, merging magic in progress..."></lightning-spinner>

        </template>

    </lightning-card>

</template>


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


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

import getPdfFilesWithIdsAsBase64 from '@salesforce/apex/QuoteFileService.getPdfFilesWithIdsAsBase64';

import pdfLib from '@salesforce/resourceUrl/pdfLib';

import { loadScript } from 'lightning/platformResourceLoader';


export default class MergePdfs extends LightningElement {

    @api recordId;

    isLibLoaded = false;

    mergedPdfUrl;

    pdfLibInstance;


    renderedCallback() {

        if (this.isLibLoaded) {

            return;

        }

        loadScript(this, pdfLib + '/pdf-lib.min.js')

            .then(() => {

                if (window['pdfLib'] || window['PDFLib']) {

                    this.isLibLoaded = true;

                    this.pdfLibInstance = window['pdfLib'] || window['PDFLib'];

                    this.loadPdfs();

                } else {

                    console.error('PDF-LIB not loaded correctly.');

                }

            })

            .catch(error => {

                console.error('Error loading PDF-LIB:', error);

            });

    }


    @wire(getPdfFilesWithIdsAsBase64, { opportunityId: '$recordId' })

    wiredPdfs({ error, data }) {

        if (this.isLibLoaded && data) {

            this.mergePDFs(data);

        } else if (error) {

            console.error('Error fetching PDFs:', error);

        }

    }


    async mergePDFs(pdfFiles) {

        if (!this.pdfLibInstance) {

            console.error('PDF-LIB instance is not defined.');

            return;

        }


        const { PDFDocument } = this.pdfLibInstance;


        const mergedPdf = await PDFDocument.create();

        for (let pdfFile of pdfFiles) {

            const pdfBytes = Uint8Array.from(atob(pdfFile.Base64Data), c => c.charCodeAt(0));

            const pdfDoc = await PDFDocument.load(pdfBytes);

            const copiedPages = await mergedPdf.copyPages(pdfDoc, pdfDoc.getPageIndices());

            copiedPages.forEach(page => mergedPdf.addPage(page));

        }


        const mergedPdfBytes = await mergedPdf.save();

        this.mergedPdfUrl = URL.createObjectURL(new Blob([mergedPdfBytes], { type: 'application/pdf' }));

    }

}


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


<?xml version="1.0" encoding="UTF-8"?>

<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">

    <apiVersion>60.0</apiVersion>

    <isExposed>true</isExposed>

    <targets>

        <target>lightning__RecordAction</target>

    </targets>

    <targetConfigs>

        <targetConfig targets="lightning__RecordAction">

            <objects>

                <object>Opportunity</object>

            </objects>

        </targetConfig>

    </targetConfigs>

</LightningComponentBundle>


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



Comments

Popular posts from this blog

Custom List View Button In Salesforce

Get Record Id RecordId in LWC