Generate a PDF from VF in Apex with object context

apexvisualforce

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.

Best Answer

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.