I have a simple Contact creationg VF page with bunch of input fields. Clicking on the Submit button would create a Contact record and shows a confirmation message on the screen. Now, I would like to generate a PDF file (format doesn't really matter) by capturing all the labels and respective values and attach it under the Notes and Attachments section of the Contact record, for audit purposes.

Is it possible to achieve this? Are there any standard functions I can make use of?

Note: I am not having renderAs = pdf tag as this is just an intake form.


You will need a separate VF page with renderAs=pdf that contains all content you need. You would pass the newly created contact ID to this page so you can retrieve the appropriate fields (you might need an Apex controller to do this). However, you won't display this page to the user.

Instead, your save process will instantiate a PageReference to that separate VF page and use the getContentAsPDF() method to create a Blob object. Then you can use the Blob for your attachment.

Note that getContentAsPDF() will fail in unit tests, so you have check Test.isRunningTest() and put in a dummy value for testing.

PageReference pg = Page.MyPageForPDFDownload;
pg.getParameters().put('id', theContactId);
Blob b;
if (!Test.isRunningTest()) {
    b = pg.getContentAsPDF();
} else {
    b = Blob.valueOf('dummy content');
  • Actually, I would like to get the data that is being inputted along with the labels. I am not sure, if I can achieve this with your implementation. – Austin Evans Sep 6 '19 at 19:09
  • Since your submit process creates a contact record, you can pass the ID to the separate page so it can pull the data from the new record. I updated my answer. – David Cheng Sep 6 '19 at 19:23
  • Sounds good to me. But, if the test class fails, how can I handle it? Are there any workarounds to make it testable? – Austin Evans Sep 6 '19 at 19:25
  • 1
    updated answer. – David Cheng Sep 6 '19 at 20:32
  • Great! One question: Should I create a separate apex controller class for the VF page that rendered as PDF? If you don't mind, can you show me how can I pass the ID, call the Apex ctrl method to retrieve data and display? I really appreciate your efforts. – Austin Evans Sep 6 '19 at 20:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.