Link Search Menu Expand Document

Add Text Image Signature to PDF With Simplified Parameter - Salesforce

PDF Add Text, Signatures and Images to PDF sample in Salesforce demonstrating ‘Add Text Image Signature to PDF With Simplified Parameter’

AddTextImageSignatureWithParamToPDF.cls
public class AddTextImageSignatureWithParamToPDF {
    
    String API_KEY = '********************************';    
    string DestinationFile = 'AddTxtImageSignWithParameter';    
    string endPointUrl = 'https://api.pdf.co/v1/pdf/edit/add';   
    
    public void addTextImageSignatureToPdf()
    {
        try
        {
            String jsonBody = '{ "async": false, "encrypt": false, "inline": true, "name": "f1040-form-filled", "url": "bytescout-com.s3-us-west-2.amazonaws.com/files/demo-files/cloud-api/pdf-form/f1040.pdf", "annotationsString": "250;20;0-;PDF form filled with PDF.co API;24+bold+italic+underline+strikeout;Arial;FF0000;www.pdf.co;true", "imagesString": "100;180;0-;bytescout-com.s3-us-west-2.amazonaws.com/files/demo-files/cloud-api/pdf-edit/logo.png|400;180;0-;bytescout-com.s3-us-west-2.amazonaws.com/files/demo-files/cloud-api/pdf-edit/logo.png;www.pdf.co;200;200", "fieldsString": "1;topmostSubform[0].Page1[0].f1_02[0];John A. Doe|1;topmostSubform[0].Page1[0].FilingStatus[0].c1_01[1];true|1;topmostSubform[0].Page1[0].YourSocial_ReadOrderControl[0].f1_04[0];123456789" }';
            // Create HTTP client instance
            Http http = new Http();
            HttpRequest request = new HttpRequest();            
            request.setHeader('x-api-key', API_KEY);
            request.setEndpoint(endPointUrl);            
            request.setHeader('Content-Type', 'application/json');
            request.setMethod('POST');            
            request.setBody(jsonBody);            
            HttpResponse response =  http.send(request);
            // Parse JSON response
            Map<String, Object> json = (Map<String, Object>)JSON.deserializeUntyped(response.getBody());            
            if(response.getStatusCode() == 200) 
            {
                if ((Boolean)json.get('error') == false)
                {
                    System.debug('response.getBody() :: '+response.getBody());
                    // Get URL of generated PDF file
                    String resultFileUrl =(String)json.get('url');
                    // Download generated PDF file
                    downloadFile(resultFileUrl, DestinationFile);
                    System.debug('Generated PDF file saved as \'{0}\' file.'+ DestinationFile);
                }
            }
            else
            {
                System.debug('Error Response ' + response.getBody());
                System.Debug(' Status ' + response.getStatus());
                System.Debug(' Status Code' + response.getStatusCode());
                System.Debug(' Response String' + response.toString());
            }
        }
        catch(Exception ex)
        {
            String errorBody = 'Message: ' + ex.getMessage() + ' -- Cause: ' + ex.getCause() + ' -- Stacktrace: ' + ex.getStackTraceString();
            System.Debug(errorBody);
        }
    }
    
    @TestVisible
    private static void downloadFile(String extFileUrl, String DestinationFile)
    {
        Http h = new Http(); 
        HttpRequest req = new HttpRequest(); 
        extFileUrl = extFileUrl.replace(' ', '%20'); 
        req.setEndpoint(extFileUrl); 
        req.setMethod('GET'); 
        req.setHeader('Content-Type', 'application/pdf');
        req.setCompressed(true); 
        req.setTimeout(60000); 
        //Now Send HTTP Request
        HttpResponse res  = h.send(req); 
        if(res.getStatusCode() == 200) 
        {
            blob fileContent = res.getBodyAsBlob();
            ContentVersion conVer = new ContentVersion();
            conVer.ContentLocation = 'S'; // to use S specify this document is in Salesforce, to use E for external files
            conVer.PathOnClient = DestinationFile + '.pdf'; // The files name, extension is very important here which will help the file in preview.
            conVer.Title = DestinationFile; // Display name of the files
            conVer.VersionData = fileContent;
            insert conVer;
            System.Debug('Success');
        }
        else
        {
            System.debug('Error Response ' + res.getBody());
            System.Debug(' Status ' + res.getStatus());
            System.Debug(' Status Code' + res.getStatusCode());
            System.Debug(' Response String' + res.toString());
        }
    }
}
AddTextImageSignatureWithParamToPDFTest.cls
@isTest
private class AddTextImageSignatureWithParamToPDFTest {

    private testmethod static void testAddTxtImgSignToPdf()
    {
        Test.setMock(HttpCalloutMock.class, new AddTextImageSignatureWithParamToPDFTest.AddTxtSignMock());
        Test.startTest();
        AddTextImageSignatureWithParamToPDF addSign = new AddTextImageSignatureWithParamToPDF();
        addSign.addTextImageSignatureToPdf();
        Test.stopTest();
        List<ContentVersion> cv = [select Id, VersionData from ContentVersion];
        System.assertEquals(1, cv.size());
        //String strt1 = cv[0].VersionData.toString();
        //System.assert(strt1.contains('John A. Doe'));
    }
    
    private testmethod static void testAddTxtImgSignToPdfForException()
    {
        Test.startTest();
        AddTextImageSignatureWithParamToPDF addSign = new AddTextImageSignatureWithParamToPDF();
        addSign.addTextImageSignatureToPdf();
        Test.stopTest();        
    }
    
    public class AddTxtSignMock implements HttpCalloutMock {
        public HTTPResponse respond(HTTPRequest req) {
            HttpResponse res = new HttpResponse();
            String testBody = '{ "url": "https://pdf-temp-files.s3.amazonaws.com/03c5c55183c74f8d94a4ec952e4e32ad/f1040-form-filled.pdf", "pageCount": 3, "error": false, "status": 200, "name": "f1040-form-filled", "remainingCredits": 60822 } ';
            res.setHeader('Content-Type', 'application/json');
            res.setBody(testBody);
            res.setStatusCode(200);
            return res;
        }
    }
}

PDF.co Web API: the Web API with a set of tools for documents manipulation, data conversion, data extraction, splitting and merging of documents. Includes image recognition, built-in OCR, barcode generation and barcode decoders to decode bar codes from scans, pictures and pdf.

Get your PDF.co API key here!

Download Source Code (.zip)

return to the previous page explore PDF Add Text, Signatures and Images to PDF endpoint