[SalesForce] How to save Renderas=’pdf’ in files folder

Is it possible to save a visualforce page with renderas='pdf' to the files folder so I can attacht the files to an email in lightning? Something like

files f = new files( FolderId = UserInfo.getUserId(), Body = pdfBlob, Name = 'pdf_file.pdf', ContentType = 'application/pdf', Type = 'pdf'); insert f;

Best Answer

By using getContentAsPDF, you can get a visualforce's page content as a pdf, regardless of the pages renderAs attribute.

You won't be able to perform DML on the file object directly, since its a label for the ContentDocument & ContentVersion objects. You'll need to create one of those records instead.

Id someID = '000000000000000';

PageReference ref = new PageReference('/somepage?id=' + someID);

ContentVersion cont = new ContentVersion();

cont.Title = 'Title for this contentVersion';
cont.PathOnClient = 'file.pdf';
cont.VersionData = ref.getContentAsPdf();
cont.Origin = 'H';

insert cont;