So i have this task where i have to convert the image uploaded in Notes and Attachment object to PDF. For that i created a trigger(before insert) on Attachment object and used the below mentioned code,

I used the standard EncodingUtil to convert the image Body in the proper format,

I tried this code

attachmentObj.Body = blob.toPdf(attachmentObj.Body.toString());

But i get the error message "BLOB is not a valid UTF-8 string",

So after some research i also used tried this,

String encodeStringBody = EncodingUtil.base64Encode(attachmentObj.Body);

attachmentObj.Body = blob.toPdf(encodeStringBody);

But the attachment created have ineligible body. I cannot see anything when i 'view file' in the attachment object.

I expect the file to be converted to PDF but both the code i used have problems.

Please help me with this if anyone find solution to the problem.

  • Method 1 won't work because binary data can't be directly converted to a string. Method 2 won't work because toPDF expects an HTML string to render in to a PDF. As far as I can tell, you can't convert the image directly to a PDF without an intermediate Visualforce page to perform the translation, and it probably should not be done in a trigger for performance reasons, and because Visualforce calls are considered callouts, and can only be done asynchronously. You will need to go down a different path.
    – sfdcfox
    Aug 31, 2019 at 8:00

1 Answer 1


Recently I faced similar challenge and here is way to do in native Apex with intermediate Visualforce page.

The logic is to take the base64 format of image file and save it as a attachment on Case, any case will do, you can even create a temporary case and delete it afterwards, then use intermediate VF Page to render it as PDF using renderAs='pdf' Then using @future(Callout=true) get the contents on the Page. Here is an example.

But as you are doing this on a trigger level, just change the logic to suit your needs. I was having a client trigger (From UI), so this logic worked fine.

Click Here

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .