Java client for advanced pdf conversion using a Salesforce org

All we know renderAs=”pdf”. nThe good news is now Salesforce has an advanced pdf converter:

renderAs=”advanced_pdf”

<apex:page sidebar="false" showHeader="false" renderAs="advanced_pdf">
  <html lang="en-US" >
    <head>
      <meta charset="UTF-8" />
    </head>
    <body>
      <h1>Hello, world!</h1>
    </body>
  </html>
</apex:page>

Still this functionality is a pilot what It means that you need to create a case and someone from support will activate It in your org.

“Advanced PDF renders Visualforce pages as PDF files with broader support for modern HTML standards, such as CSS3, JavaScript, and HTML5. This change applies to both Lightning Experience and Salesforce Classic.” Read more

In some projects I had to convert html to pdf. Some solutions like iText did not work well in complex html so I needed a better solution. One of them is take advantage of advanced_pdf rendering from Salesforce so with a simple web service should be easy.

This Apex class exposes a RESTful webservice that receives an html string an return a pdf as base64

@RestResource(urlMapping='/htmltopdf')
global class HtmlToPdf {
  @HttpPost
  global static PdfResponse convertToPdf(String html) {
    browser.RenderRequest request = new browser.RenderRequest();
    request.setPageContent(html);
    Blob blobVal = browser.Browser.renderToPdf(request);
    PdfResponse resp = new PdfResponse();
    resp.base64Content = EncodingUtil.base64Encode(blobVal);
    return resp;
}

  global class PdfResponse {
    String base64Content;
  }
}

Then all you need is this Java client to consume that web service.

Important: by default remote css, images and any other resource won’t work. I recommend you upload
all in a static resource and do references using relative path.

If you want to use remote resources you must create a Remote Setting in your org and of course pdf conversion will be slower.

See the full example in my Github account https://github.com/andrescanavesi/salesforce-pdf-converter

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s