December 1, 2010

Using Images (e.g. Google Charts) in Visualforce PDFs

Recently one of my colleagues was attempting to save a PDF version of a page which included Google chart images (for those that don't know the mighty G have a chart API where you can send data and get a nice image back), but when the generated PDF was viewed the images were always missing.

We thought at first it may simply be a case of the images not loading quickly enough and the renderer not bothering to wait for them, but then after a bit more googling we eventually discovered the solution and frankly I was astounded that the penny hadn't dropped earlier.

Anytime when you want to make a callout from apex code you have to ensure that you have the end point specified in the Remote Site Settings (Setup -> Administration Setup -> Security Controls -> Remote Site Settings), otherwise the callout is blocked. Of course when displaying a Visualforce page to a user containing an image it's their browser making the request, when the PDF renderer it is code on the org making the request and as such gets denied access if you've not expressly allowed it.

A side note regarding callouts: for some reason when writing batch apex code be aware that although you get a fresh set of governor limits for each invocation of the execute method, the one limit that appears to be different to the standard environment is the number of callouts allowed - you're only allowed to make one each time meaning you'll want to run the class with the optional batch size parameter set to 1.