I have a renderAsPDF VF page that takes an object id parameter as part of the URL string. It returns a PDF with some textual data and some images (e.g.
<apex:image id="theImage" value="/servlet/servlet.FileDownload?file={!$CurrentPage.parameters.id}" />
that point to image/png Attachements ). Within a trigger, I’m attempting to download the VF page as PDF, but unable to do it.I asked on twitter and got some good suggestions, but none of them solved the problem. Here are some links from the conversation
The
PageReference.getContentAsPDF
can’t be called from a trigger
http://t.co/w9D8EZaQThe
PageReference
getContent
andgetContentAsPDF
methods can’t be used with the future annotation.
https://t.co/3KKKenxhHere’s a good discussion about it on the Force.com Discussion Boards
http://boards.developerforce.com/t5/Apex-Code-Development/Generate-PDF-with-apex-trigger/td-p/481325This clever idea linked out from the thread works for everything, but doesn’t handle images
http://corycowgill.blogspot.ch/2012/02/generating-pdf-in-apex-trigger.htmlI posted a this code which works, but not sure it’ll stand the test of time. Relies on grabbing session ids out of cookies, and following redirects.
Answer
If you’re open to using a visualforce email template* instead of a visualforce page to generate the PDF then you have a good option: generate the PDF on the fly as part of the template.
This is in fact fully supported via the use of the messaging:attachment tag, like so:
<messaging:attachment renderAs="pdf" filename="{!relatedTo.name}.pdf">content</messaging:attachment>
I’ve used this before and I know there are ISV applications that rely on this functionality so it should be supported and safe to use if your use case allows.
*caveats include:
- You cannot use a custom controller for the template (although you can use custom components with apex controllers).
- You cannot perform DML in an email template like you could in a page.
Attribution
Source : Link , Question Author : pfeilbr , Answer Author : ca_peterson