Showing posts with label Webservice. Show all posts
Showing posts with label Webservice. Show all posts

Wednesday, March 28, 2012

Create PDF Attachment Dynamically using Apex Trigger

Ever wondered how we could create a PDF dynamically and store it as an attachment using a trigger in Salesforce. I know, this is quite easy if it would have been the case of New/Edit button override or if it would have been the case of a new custom visualforce page. But, to achieve this using a trigger is a little bit tricky. This is  because getContent() and getContentasPDF() methods are not available for use in a trigger or @future method due to the salesforce governor limits. So is the case with Batch and scheduled apex class.

After a bit research I was able to get a couple of workarounds to achieve the above mentioned requirement:

1. Using the webservice method: 
  1. Expose a method as a webservice, which dynamically creates & stores a PDF as an attachment record.
  2. Generate the wsdl  for this webservice and consume it in the same Org.
  3. Now call the webservice method in the generated stub class from the trigger via @future method by passing the sessionID.
  4. This will generate the desired pdf.
2. You can also try generating the PDF using Email Service class. Process is as follow:  
  1. Create an Email Service class as well as an Visualforce page template.
  2. Send an inbound email to Salesforce through workflow with parent Salesforce id in subject line.
  3. Email service class will render the Visualforce page and PDF can be saved in attachment object.
Hope the solutions will help you. Please write to me if you have any suggestion or a better solution on the same.