Link Search Menu Expand Document

Delete Text From PDF - Salesforce

PDF Search and Delete Text from PDF sample in Salesforce demonstrating ‘Delete Text From PDF’

DeleteTextFromPDF.cls
public class DeleteTextFromPDF {

    String API_KEY = '*************************';
    string DestinationFile = 'DeleteTextFromPDF'; 
    string endPointUrl = 'https://api.pdf.co/v1/pdf/edit/delete-text';
    
    public void deleteTextFromPdfFile()
    {
        try
        {  
            String jsonBody = '{ "url": "https://pdfco-test-files.s3.us-west-2.amazonaws.com/pdf-search-and-replace/sample-agreement-template-signature-page-1.pdf", "searchStrings": [ "[CLIENT-NAME]", "[CLIENT-COMPANY]", "[CLIENT-SIGNATURE]" ], "replacementLimit": 1, "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());
                    String resultFileUrl =(String)json.get('url');
                    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); 
        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;
            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());
        }
    }
}
DeleteTextFromPDFTest.cls
@isTest
private class DeleteTextFromPDFTest {

    static testmethod void testDeleteTextFromPDF()
    {
        Test.startTest();
        Test.setMock(HttpCalloutMock.class, new DeleteTextFromPDFTest.DeleteTextFromPDFMock());
        DeleteTextFromPDF deleteTxt = new DeleteTextFromPDF();
        deleteTxt.deleteTextFromPdfFile();
        Test.stopTest();
    }
    
    static testmethod void testDeleteTextFromPDFForCatch()
    {
        Test.startTest();
        DeleteTextFromPDF deleteTxt = new DeleteTextFromPDF();
        deleteTxt.deleteTextFromPdfFile();
        Test.stopTest();
    }
    
    public class DeleteTextFromPDFMock implements HttpCalloutMock {
        public HttpResponse respond(HTTPRequest req) {
            HttpResponse res = new HttpResponse();
            String testBody = '{"url":"https://pdf-temp-files.s3.us-west-2.amazonaws.com/ESRNUYPYS5RJIOJ8MT5DL8QLNOWMT3SG/sample-agreement-template-signature-page-1.pdf?X-Amz-Expires=3600\u0026X-Amz-Security-Token=FwoGZXIvYXdzEG0aDHKmifPGIYK8lSM0gyKCAUpezMRqX46NuUtPXmG01%2F36PDGpPjXHDmQF53pRl%2Bu9DjbpnNUp0iwxssel1HzjZNklih1l1C9BXEdEKn3Zea9N3mcADliD7g6Mxb8hr1rRz79U8GI6VlHIZZVJXbPRVyUyGrY%2BiwhfgarRg%2B5lln8jHMxPiHO66HUwGGkz04G4Iaoo0pOXoAYyKHe1LuYDaSM5gunLIezTYMm2wYrjgcOTQ%2F%2B07VwIFeBRaZFclBGBqk4%3D\u0026X-Amz-Algorithm=AWS4-HMAC-SHA256\u0026X-Amz-Credential=ASIA4NRRSZPHBI7XR2FE/20230306/us-west-2/s3/aws4_request\u0026X-Amz-Date=20230306T155547Z\u0026X-Amz-SignedHeaders=host\u0026X-Amz-Signature=e7d7005e0de47b9d065339883fd54f92f1eb18e14ae836c1c84eed56838fc29c","pageCount":1,"error":false,"status":200,"name":"sample-agreement-template-signature-page-1.pdf","credits":21,"duration":255,"remainingCredits":1165585}';
            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 Search and Delete Text from PDF endpoint