Are you looking for converting jpg or png images into PDF files in salesforce? do you want this functionality using Lighting web components? but we don’t have any existing methods/Libraries in LWC.
So Thinking about how to develop it? What is the design architecture?
yes, We don’t have any existing standard methods/Libraries in lwc for converting files into pdf so we have to write our custom logic to achieve it.
Design :
1) In Lwc component we have to upload the file
2) that file needs to pass into Apex class.
3) we have to create visualforce page and we have to pass that file to visualforce using page reference.
4) That visualforce convert file into Pdf file using render as.
5) we have to read that pdf file again into apex from page reference and insert it. thinking about how read page reference into apex ? don’t worry look below code.
Convert File into PDF
ConvertFiletoPdf.html
<template>
<lightning-card title=”Lightning File Upload”>
<div class=”slds-p-around_medium”>
<lightning-file-upload
label=”Upload single/multiple files”
name=”fileUploader”
accept={acceptedFormats}
record-id={recordId}
onuploadfinished={handleUploadFinished}
multiple>
</lightning-file-upload>
</div>
</lightning-card>
</template>
ConvertFiletoPdf.js
import { LightningElement, wire, api, track } from ‘lwc’;
import { ShowToastEvent } from ‘lightning/platformShowToastEvent’;
import getData from ‘@salesforce/apex/FileConvertor.uploadFile’;
export default class FileConvertor extends LightningElement {
@api recordId;
// You can add more file formats to accept files
get acceptedFormats() {
return [‘.png’, ‘.PNG’, ‘.jpg’, ‘.JPG’];
}
// this method should be loaded after file is loaded
handleUploadFinished(event) {
let arraydata = [];
const uploadedFiles = event.detail.files;
uploadedFiles.forEach(function(item){
arraydata.push(item.documentId);
});
getData({
recordids: arraydata
})
this.showNotification(uploadedFiles.length + ‘ files are Uploaded Successfully’, ‘success’);
}
showNotification(message, variant) {
const evt = new ShowToastEvent({
‘message’: message,
‘variant’: variant
});
this.dispatchEvent(evt);
}
}
FileConvertor.cls
public with sharing class FileUploaderClass {
@AuraEnabled
public static void uploadFile(List<id> recordids) {
list<attachment> insertattachment = new list<attachment>();
for(ContentVersion recid : [SELECT id,Title FROM ContentVersion WHERE ContentDocumentId IN: recordids]){
PageReference pageReference = new PageReference(‘/apex/envelope?FileId=’+recid.id);