How to Convert HTML to PDF in Salesforce Apex
Converting a complex HTML file to the more manageable and user-friendly PDF format can be a tedious undertaking involving a lot of parsing and rendering before the actual operation can be performed. To save yourself a significant amount of time and energy, we will be covering how you can use an API in Salesforce Apex to convert standard HTML (with full support for CSS, JavaScript, images, and more) to PDF.
Diving right into the process, we will need to download and copy the /client folder into our Apex project:
Download Apex Client
Following the download and installation, we are going to call the conversion function with the following code:
SwagConvertDocumentApi api = new SwagConvertDocumentApi();
SwagClient client = api.getClient();// Configure API key authorization: Apikey
ApiKeyAuth Apikey = (ApiKeyAuth) client.getAuthentication('Apikey');
Apikey.setApiKey('YOUR API KEY');Map<String, Object> params = new Map<String, Object>{
'inputFile' => Blob.valueOf('Sample text file\nContents'),
'includeBackgroundGraphics' => true,
'scaleFactor' => 56
};try {
// cross your fingers
Blob result = api.convertDocumentHtmlToPdf(params);
System.debug(result);
} catch (Swagger.ApiException e) {
// ...handle your exceptions
}
In order for the operation to run smoothly, you will need to input your HTML file and API key; additional parameters concerning background features and scaling are available but optional.