Link Search Menu Expand Document

Convert Images To PDF From Url - Salesforce

PDF from Images (JPG to PDF and PNG to PDF) sample in Salesforce demonstrating ‘Convert Images To PDF From Url’

ImagesToPDF.cls
public class ImagesToPDF {
    static String API_KEY = '***********************************';
    static String DestinationFileName = 'result';
    
    public static void addImageToPDF()
    {
        Map<string, Object> parameters = new Map<string, Object>();
        parameters.put('name', DestinationFileName);

        // You can also upload your own file into PDF.co and use it as url. Check "Upload File" samples for code snippets: https://github.com/bytescout/pdf-co-api-samples/tree/master/File%20Upload/    
        String SourceFileUrl = 'https://bytescout-com.s3.amazonaws.com/files/demo-files/cloud-api/image-to-pdf/image1.png,https://bytescout-com.s3.amazonaws.com/files/demo-files/cloud-api/image-to-pdf/image2.jpg';
        parameters.put('url', SourceFileUrl);
        
        string jsonPayload = Json.serialize(parameters);
        System.debug('jsonPayload = '+jsonPayload);
        try
        {
            string url = 'https://api.pdf.co/v1/pdf/convert/from/image';
            HttpRequest req = new HttpRequest();
            req.setBody(jsonPayload);
            req.setHeader('x-api-key', API_KEY);
            req.setHeader('Content-Type', 'application/json');
            req.setEndpoint(url);
            req.setMethod('POST');
            req.setTimeout(60000);
            Http http = new Http();
            HTTPResponse res = http.send(req);
            if(res.getStatusCode() == 200) 
            {
                System.Debug('res ' + res);
                Map<String, Object> deserializedBody =  (Map<String, Object>)JSON.deserializeUntyped(res.getBody());
                String urlVal = (String)deserializedBody.get('url');
                downloadPDFAndStore(urlVal, DestinationFileName);
            }
            else
            {
                System.debug('Success Response ' + res.getBody());
                System.Debug(' Status ' + res.getStatus());
                System.Debug(' Status Code ' + res.getStatusCode());
                System.Debug(' Status String ' + res.toString());
            }
            
        }
        catch(Exception ex)
        {
            String errorBody = 'Message: ' + ex.getMessage() + ' -- Cause: ' + ex.getCause() + ' -- Stacktrace: ' + ex.getStackTraceString();
            System.Debug(errorBody);
        }
    }
    
    @TestVisible
    private static void downloadPDFAndStore(String extFileUrl, String DestinationFile)
    {
        try
        {
            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('Success Response ' + res.getBody());
                System.Debug(' Status ' + res.getStatus());
                System.Debug(' Status Code' + res.getStatusCode());
                System.Debug(' Status String' + res.toString());
            }
        }
        catch(Exception ex)
        {
            String errorBody = 'Message: ' + ex.getMessage() + ' -- Cause: ' + ex.getCause() + ' -- Stacktrace: ' + ex.getStackTraceString();
            System.Debug(errorBody);
        }
    }
}
ImagesToPDFTest.cls
@isTest
private class ImagesToPDFTest {
    private static testMethod void testaddImageToPDF(){
        Test.setMock(HttpCalloutMock.class, new ImagesToPDFMock());
        Test.startTest();
        ImagesToPDF.addImageToPDF();
        Test.stopTest();
    }
    
    private static testMethod void testaddImageToPDFForCatch(){
        Test.startTest();
        ImagesToPDF.addImageToPDF();
        Test.stopTest();
    }
    
    private static testMethod void testaddImageToPDFForDownloadMehtod(){
        Test.setMock(HttpCalloutMock.class, new ImagesToPDFMock());
        Test.startTest();
        ImagesToPDF.downloadPDFAndStore('https://api.pdf.co/v1/pdf/convert/from/image', 'result');
        Test.stopTest();
    }
    
    public class ImagesToPDFMock implements HttpCalloutMock {
        public HTTPResponse respond(HTTPRequest req) {
            HttpResponse res = new HttpResponse();
            res.setHeader('Content-Type', 'application/json');
            res.setBody('{"example":"test"}');
            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 from Images (JPG to PDF and PNG to PDF) endpoint