Wednesday 19 June 2019

Generate a PDF file with APEX Trigger in Salesforce

There was a requirement to generate a PDF file while inserting a new record in Account object and add it as an attachment (On-the-fly).

The main challenge was - when the record is saved, the apex trigger is fired on the account object, but at that time, we are unable to use the PageReference Class methods (generate PDF) within the trigger context, making it difficult to generate PDF with this OOTB Class/Method. 

To generate PDF, we can use out-of-the-box PageReference Class method and it works only if there is not APEX trigger associated with the object. But if Apex trigger is associated with object while inserting a new record, it won't work.

To overcome this limitation, we developed a custom solution which involved creating an apex class called PDFGenerator. This class contains the mechanism to accept the HTML content and renders the PDF accordingly to the HTML specified. It will also attach the PDF file to the record as an Attachment.

PDFGenerator Class :

public with sharing class PDFGenerator
    public static final String FORM_HTML_START = '<HTML><BODY>';
    public static final String FORM_HTML_END = '</BODY></HTML>';

    public static void PDFGenerator(Account account)
        String pdfContent = '' + FORM_HTML_START;

            pdfContent = '' + FORM_HTML_START;
            pdfContent = pdfContent + '<H2>Account Information in PDF</H2>';
            //Dynamically grab all the fields to store in the PDF
            Map<String, Schema.SObjectType> sobjectSchemaMap = Schema.getGlobalDescribe();
            Schema.DescribeSObjectResult objDescribe = sobjectSchemaMap.get('Account').getDescribe();
            Map<String, Schema.SObjectField> fieldMap = objDescribe.fields.getMap();
            //Append each Field to the PDF
            for(Schema.SObjectField fieldDef : fieldMap.values()) 
                Schema.Describefieldresult fieldDescResult = fieldDef.getDescribe();
                String name = fieldDescResult.getName();
                pdfContent = pdfContent + '<P>' + name + ': ' + account.get(name) + '</P>';

            pdfContent = pdfContent + FORM_HTML_END;

        }catch(Exception e)

            pdfContent = '' + FORM_HTML_START;
            pdfContent = pdfContent + '<P>THERE WAS AN ERROR GENERATING PDF: ' + e.getMessage() + '</P>';
            pdfContent = pdfContent + FORM_HTML_END;

    public static void attachPDF(Account account, String pdfContent)
            Attachment attachmentPDF = new Attachment();
            attachmentPDF.parentId = account.Id;
            attachmentPDF.Name = account.Name + '.pdf';
            attachmentPDF.body = Blob.toPDF(pdfContent); //This creates the PDF content
            insert attachmentPDF;

        }catch(Exception e)

Now, we would modify an Apex Trigger, on Account object which will initialize the above created PDFGenerator apex class on the record creation (after insertion).

Account Trigger:

trigger AccountTrigger on Account (after insert)
    if(trigger.isAfter && trigger.isInsert)
        for(Account ac :

This approach would generate a PDF within the context of the trigger, and help you overcome the challenge.

If you have any questions you can reach out our Salesforce Consulting team here.

Monday 17 June 2019

Brief introduction to Nodes used in Salesforce Analytics Data flow

Any manipulation done to the data can be referred as a transformation process. In order to manipulate the data, we can add transformations to a dataflow to extract data from Salesforce objects or datasets, transform them (Salesforce data or external data), and register those datasets.

Below is the glossary used in Dataflow Analytics describing the role/term in the process.
  • sfdcDigest node - Extracts data or generates a dataset from a Salesforce object to be used for queries and further transformation.
  • sfdcRegister node - is responsible for registering dataset to make them available to use them in queries.
  • augment - As the name suggests, it augments the related datasets. The left and right keys are the fields from each node that are used to match records (similar to JOIN operations from SQL).
  • digest - is used to extract data synced from the local Salesforce org, or data synced through an external connection.
  • computeExpression  - is useful to create calculated fields or derived fields and add those to the dataset.
  • update - As the name suggests, this transformation updates the specified field values in an existing dataset based on data from another dataset.
  • filter  - The filter transformation is used to filter the records from an existing data-set based on the condition.
  • edgemart  - The edgemart transformation is actually the collection of the datasets which include an existing, registered data-set, or which can contain Salesforce data, external data, or both.
  • sliceDataset - The sliceDataset transformation performs the slicing and dicing of fields from a dataset in your dataflow.
We can find on each node of Salesforce Analytics Dataflow here.

If you have any questions you can reach out our Salesforce Consulting team here.

Tuesday 11 June 2019

Embed a free Digital Signature to Salesforce Visualforce Page Using HTML5 Canvas

We had to provide an interface where the user could add a signature digitally (using mouse or touch, depending on the device) in Salesforce Visualforce Page, and embed that digital signature to the invoice generated only using out-of-the-box functionality and not using any 3rd-party vendor tools like Adobe eSign, DocuSign and other tools with premium license.

Using open-source and out-of-the-box functionalities of Salesforce and not using any 3rd-party vendor tool.

To achieve this, we have used a jQuery plug-in called 'Sketch.js' along with the common jQuery CDN. 

So, we have achieved the desired results by using HTML5 Canvas and JavaScript remoting. 

Now, we would be adding jQuery and Sketch.js file content in Salesforce Static resources repository.

Then, we need to setup JavaScript event listeners in the Visualforce (VF) page to capture the events like touch-start, touch-move, and touch-end performed on the canvas. The sketch.js will handle the touch/drag events performed on the canvas.

The purpose of using JavaScript remoting is to ensure that the Canvas content is properly passed to Apex Controller and can be saved. The canvas would be converted into Base64 String with the Canvas.toDataURI() method. This is how we would be pushing the converted data bytes from the Canvas into an Attachment.

Below is the source code to add digital signature in Visualforce Page & APEX class:

Visualforce Page:

<apex:page controller="SignDemo">

 <script type="text/javascript" >

    $( window ).load(function(){
        $('#Sign').sketch(); // associating sketch function with canvas.

// clear canvas on clear button.
function clearSketch(){          

        $('#Sign').replaceWith('<canvas id="Sign" style="border:2px solid; border-radius:10px 10px 10px 10px;height: 150px;width: 300px;background:white; border-color:lightgray"></canvas>');


function save(){
       // Get Data URL from the canvas i.e. signed by the user.
      var dataUrl = document.getElementById('Sign').toDataURL();

     // use Remote Action function to generate image.

           '{!$RemoteAction.SignDemo.GenerateImage}',dataUrl ,

            function(result, event) {

                if (event.status) {
                // Redirect to the attachment and open attachment as image.



    Draw your signature : 

        <canvas id="Sign" style="border:2px solid; border-radius:10px 10px 10px 10px;height: 150px;

                                    width: 300px;background:white; border-color:lightgray" ></canvas>

        <input type="button" value="Clear"  onclick="clearSketch()" /> 

    <input type='button' value='save' onclick='save()'/>


Apex Controller:

public class SignDemo{

    //Create attachment and return id of the attachment.
    public static string GenerateImage(string dataurl){

        Attachment myAttach = new Attachment(); = 'Sign.png';
        myAttach.ParentId ='';  //Add ID of the parent object for the attachment (Account,Contact,etc..)
        myAttach.body = ((Blob) EncodingUtil.base64Decode(dataurl.split(',')[1]));
        insert myAttach;
        return myAttach.Id;


Below is the illustration of the canvas board and signature, which can be performed by the user. 

Below is the sample invoice file generated containing the digital signature. 

If you have any questions you can reach out our Salesforce Consulting team here.