0

I am trying to generate a PDF and attach it to an object.

I read online that you can set a page in apex and get the content as a blob, then set that as an attachment... is there a way to pass some context variables to the page?

For example if I wanted to pass an account id to the controller... how would I do that?

pageReference pdfPage = Page.VFPageName;
blob pdfBody;
pdfBody = pdfPage.getContentAsPDF();

But how to generate the page in a certain context where accountId='a00blahblahblah'?

The long term goal is to be able to call this pdf conversion/attachment process from a variety of different objects via invocable apex in flow, passing in an id and type to give the controller context on what info to display on the pdf.

2 Answers 2

2

You can do that by using a string as your page reference, for example:

PageReference pdfPage = new PageReference( 'vfpagename?Id=' + objectId );

This assumes that your page renders the correct output when passing in the id. Then, the getContentAsPDF method simply converts what your page renders to a pdf.

1

If you want to maintain your hard link (for metadata reporting) to the Visualforce page, you can add parameters to the PageReference via its parameters map:

PageReference pdfPage = Page.VFPageName;
pdfPage.getParameters().put('id','a00blahblahblah');
blob pdfBody = pdfPage.getContentAsPDF();

This has the advantage of taking care of automatic serialization of the parameters (URL encoding), which you don't necessarily need here, but might be useful for future projects.

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.