Split PDF By Page Number - Salesforce
PDF Split sample in Salesforce demonstrating ‘Split PDF By Page Number’
SplitPDFByPageNumber.cls
public class SplitPDFByPageNumber {
String API_KEY = '***********************';
string DestinationFile = 'SplitPDFByPageNo_Result';
string endPointUrl = 'https://api.pdf.co/v1/pdf/split';
public void splitPdfUsingPage()
{
List<ContentVersion> toBeInserted = new List<ContentVersion>();
try
{
String jsonBody = '{"url": "https://pdfco-test-files.s3.us-west-2.amazonaws.com/pdf-split/sample.pdf", "pages": "1-2,3-", "inline": true, "name": "result.pdf", "async": false }';
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);
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());
List<Object> resultFileUrl =(List<Object>)json.get('urls');
Integer count=1;
for(Object fileUrl : resultFileUrl)
{
downloadFile(String.valueOf(fileUrl), DestinationFile+'_'+count, toBeInserted);
count++;
}
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());
}
if(toBeInserted.size() > 0)
insert toBeInserted;
}
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, List<ContentVersion> toBeInserted)
{
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);
HttpResponse res = h.send(req);
if(res.getStatusCode() == 200)
{
blob fileContent = res.getBodyAsBlob();
ContentVersion conVer = new ContentVersion();
conVer.ContentLocation = 'S';
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;
toBeInserted.add(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());
}
}
}
SplitPDFByPageNumberTest.cls
@isTest
private class SplitPDFByPageNumberTest {
static testMethod void testSplitPdfUsingPage()
{
Test.startTest();
Test.setMock(HttpCalloutMock.class, new SplitPDFByPageNumberTest.SplitPDFByPageNoMock());
SplitPDFByPageNumber splitPdf = new SplitPDFByPageNumber();
splitPdf.splitPdfUsingPage();
Test.stopTest();
}
static testMethod void testSplitPdfUsingPageforCatch()
{
Test.startTest();
SplitPDFByPageNumber splitPdf = new SplitPDFByPageNumber();
splitPdf.splitPdfUsingPage();
Test.stopTest();
}
public class SplitPDFByPageNoMock implements HttpCalloutMock {
public HTTPResponse respond(HTTPRequest req) {
HttpResponse res = new HttpResponse();
String testBody = '{ "urls": [ "https://pdf-temp-files.s3.us-west-2.amazonaws.com/YPG46FWTZPJA0XOYS4WW9REHCHLO659Y/result_page1-2.pdf?X-Amz-Expires=3600&X-Amz-Security-Token=FwoGZXIvYXdzEG8aDNkg0DYoVoCyvF88aSKCAYgbOizJoYULBIgYUdfJgJG5Tw7PlcNavOD6q4JNwLz5wT89pkTBS%2FPbnykQjNrJeh%2B6njlDmjcLqAjt2RApVDtXFJrb%2F%2B67T43qQZJXCj83zIugG2oTGsA1tK2q7KmD8YV%2FWM%2FUEXEhiiKYXtae2GQAsMPowLTWCrw6%2BUhX8AQQjPIor42nnwYyKDAWzJatWBqURnasvqtS10U2A4EaRxD%2BrpU5dwOqWN47Dkqzq9TBfug%3D&X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=ASIA4NRRSZPHCRJF34GF/20230213/us-west-2/s3/aws4_request&X-Amz-Date=20230213T054449Z&X-Amz-SignedHeaders=host&X-Amz-Signature=8f5a5c43ab6aecde4deef658d5f8d93deca1cca19487453cc9fc75a09f918b8b" ], "pageCount": 4, "error": false, "status": 200, "name": "result.pdf", "credits": 8, "duration": 359, "remainingCredits": 1166375 }';
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 Split endpoint
Copyright © 2016 - 2024 PDF.co