Legacy - Add Image To PDF From Uploaded File - Salesforce
PDF Add Text, Signatures and Images to PDF sample in Salesforce demonstrating ‘Legacy - Add Image To PDF From Uploaded File’
AddImageToTheExistingPDF.cls
public class AddImageToTheExistingPDF {
static String API_KEY = '******************************';
String[] fileName = new String[] {'samplePDF', 'logo_byte'}; // File name which is available in salesforce Files.
static String DestinationFileName = 'result';
List<String> urlList = new List<String>();
public void startProcessing()
{
try
{
for(String fname : fileName)
{
ContentVersion cv = [select Title, VersionData from ContentVersion where Title = :fname limit 1];
Blob SourceFile = cv.VersionData;
//1. Prepare URL for "Get Presigned URL" API call
string url = 'https://api.pdf.co/v1/file/upload/get-presigned-url?contenttype=application/octet-stream&name=:fname';
HttpRequest req = new HttpRequest();
req.setHeader('x-api-key', API_KEY);
req.setEndpoint(url);
req.setMethod('GET');
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());
Boolean isError = Boolean.ValueOf(deserializedBody.get('error'));
if(isError == false)
{
// Get URL to use for the file upload
String uploadUrl = String.ValueOf(deserializedBody.get('presignedUrl'));
// Get URL of uploaded file to use with later API calls
String uploadedFileUrl = String.ValueOf(deserializedBody.get('url'));
SYstem.debug('uploadedFileUrl :: '+uploadedFileUrl);
// 2. UPLOAD THE FILE TO CLOUD.
if(uploadFile(API_KEY, uploadUrl, SourceFile))
{
urlList.add(uploadedFileUrl);
System.debug('urlList ' + urlList);
//System.assert(false, ' urlList ' + urlList);
}
}
}
else
{
System.debug('Error Response ' + res.getBody());
System.Debug(' Status ' + res.getStatus());
System.Debug(' Status Code' + res.getStatusCode());
System.Debug(' Response String' + res.toString());
}
}
if (urlList.size() > 0)
{
addImageToPDF(urlList);
}
}
catch(Exception ex)
{
String errorBody = 'Message: ' + ex.getMessage() + ' -- Cause: ' + ex.getCause() + ' -- Stacktrace: ' + ex.getStackTraceString();
System.Debug(errorBody);
}
}
@TestVisible
public static boolean uploadFile(String API_KEY, String url, Blob sourceFile)
{
HttpRequest req = new HttpRequest();
req.setHeader('x-api-key', API_KEY);
req.setHeader('Content-Type', 'application/octet-stream');
req.setEndpoint(url);
req.setMethod('PUT');
req.setTimeout(60000);
req.setBodyAsBlob(sourceFile);
Http http = new Http();
HTTPResponse res = http.send(req);
if(res.getStatusCode() == 200)
{
System.Debug(res.getBody());
return true;
}
else
{
System.debug('Error Response ' + res.getBody());
System.Debug(' Status ' + res.getStatus());
System.Debug(' Status Code' + res.getStatusCode());
System.Debug(' Response String' + res.toString());
return false;
}
}
public static void addImageToPDF(List<String> uploadedFileUrl)
{
string Pages = '';
string Password = '';
string SourceFileUrl = uploadedFileUrl[0];
string Type1 = 'image';
Integer X = 400;
Integer Y = 600;
Integer Width1 = 119;
Integer Height1 = 32;
String ImageUrl = uploadedFileUrl[1];
Map<string, Object> parameters = new Map<string, Object>();
parameters.put('name', DestinationFileName);
parameters.put('password', Password);
parameters.put('pages', Pages);
parameters.put('url', SourceFileUrl);
parameters.put('type', Type1);
parameters.put('x', X);
parameters.put('y', Y);
parameters.put('width', Width1);
parameters.put('height', Height1);
parameters.put('urlimage', ImageUrl);
string jsonPayload = Json.serialize(parameters);
try
{
string url = 'https://api.pdf.co/v1/pdf/edit/add';
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);
}
}
}
AddImageToTheExistingPDFTest.cls
@isTest
public class AddImageToTheExistingPDFTest
{
private testmethod static void testaddImageToPDF()
{
List<ContentVersion> cvList = new List<ContentVersion>();
ContentVersion con = new ContentVersion();
con.Title = 'samplePDF';
con.VersionData=Blob.valueOf('images-and-documents');
con.PathOnClient = 'samplePDF.pdf';
cvList.add(con);
ContentVersion con1 = new ContentVersion();
con1.Title = 'logo_byte';
con1.VersionData=Blob.valueOf('image');
con1.PathOnClient = 'logo_byte.png';
cvList.add(con1);
insert cvList;
Test.startTest();
Test.setMock(HttpCalloutMock.class, new AddImageToTheExistingPDFTest.DocumentCreationMockForUpload());
AddImageToTheExistingPDF addImageToPdf = new AddImageToTheExistingPDF();
addImageToPdf.startProcessing();
List<ContentVersion> cv = [select Id from ContentVersion];
Test.stopTest();
System.assertEquals(3, cv.size());
}
public class DocumentCreationMockForUpload implements HttpCalloutMock {
public HTTPResponse respond(HTTPRequest req) {
HttpResponse res = new HttpResponse();
String testBody = '{"presignedUrl":"https://pdf-temp-files.s3-us-west-2.amazonaws.com/0c72bf56341142ba83c8f98b47f14d62/test.pdf?X-Amz-Expires=900&X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAIZJDPLX6D7EHVCKA/20200302/us-west-2/s3/aws4_request&X-Amz-Date=20200302T143951Z&X-Amz-SignedHeaders=host&X-Amz-Signature=8650913644b6425ba8d52b78634698e5fc8970157d971a96f0279a64f4ba87fc","url":"https://pdf-temp-files.s3-us-west-2.amazonaws.com/0c72bf56341142ba83c8f98b47f14d62/test.pdf?X-Amz-Expires=3600&x-amz-security-token=FwoGZXIvYXdzEGgaDA9KaTOXRjkCdCqSTCKBAW9tReCLk1fVTZBH9exl9VIbP8Gfp1pE9hg6et94IBpNamOaBJ6%2B9Vsa5zxfiddlgA%2BxQ4tpd9gprFAxMzjN7UtjU%2B2gf%2FKbUKc2lfV18D2wXKd1FEhC6kkGJVL5UaoFONG%2Fw2jXfLxe3nCfquMEDo12XzcqIQtNFWXjKPWBkQEvmii4tfTyBTIot4Na%2BAUqkLshH0R7HVKlEBV8btqa0ctBjwzwpWkoU%2BF%2BCtnm8Lm4Eg%3D%3D&X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=ASIA4NRRSZPHEGHTOA4W/20200302/us-west-2/s3/aws4_request&X-Amz-Date=20200302T143951Z&X-Amz-SignedHeaders=host;x-amz-security-token&X-Amz-Signature=243419ac4a9a315eebc2db72df0817de6a261a684482bbc897f0e7bb5d202bb9","error":false,"status":200,"name":"test.pdf","remainingCredits":98145}';
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.
Download Source Code (.zip)
return to the previous page explore PDF Add Text, Signatures and Images to PDF endpoint
Copyright © 2016 - 2024 PDF.co