In this article we will learn about how to generate and store file in Salesforce using apex.We will use the Content Version, Content Document and Content Document Link object to generate and store files in salesforce. If you are someone who understand better via a video tutorial then scroll down and watch the video on Youtube.
Content Document
These are documents uploaded to a library in Salesforce CRM content or Salesforce files. It automatically gets created when you create a ContentVersion, which is child of ContentDocument. Learn about various fields of Content Document from here.
Content Version
It represents a specific version of a document in Salesforce CRM Content or Salesforce files. This means that this object stores document information similar to Attachment. Check out various fields here.
Content Document Link
This object will share the files with Users, Records, Groups, etc. You can create multiple records to attach the same files between various records. This object store files parent id in the LinkedEntityId field. Check out the fields of this object from here.
ContentDocumentId & VersionId
When you load a document to ContentVersion, Salesforce will create a record in ContentDocument. However, if you upload a new version of the document, a new record will be created for Content Version, but not for ContentDocument.
Code Time
Below is the code in which we are trying to generate and store pdf file in salesforce using the object mentioned above. To get a better understanding of each fields watch the youtube video.
pubkic class DocumentController { public static void generateAndStoreFile(){ String testData = 'This is to be stored in a PDF'; ContentVersion cVersion = new ContentVersion(); cVersion.ContentLocation = 'S'; cVersion.Title = 'TestFile'; cVersion.PathOnClient = cVersion.title +'.pdf'; cVersion.VersionData = Blob.toPdf(testData); insert cVersion; id conDocumentId = [Select ContentDocumentId from ContentVersion where Id=:cVersion.Id].ContentDocumentId; ContentDocumentLink cDocLink = new ContentDocumentLink(); cDocLink.ContentDocumentId = conDocumentId; cDocLink.LinkedEntityId = '0035j000006XRkvAAG'; cDocLink.Visibility = 'AllUsers'; cDocLink.ShareType = 'V'; insert cDocLink; } }
Here is the Youtube video.
I hope this article and video helped you in learning how to generate and store PDF in Salesforce using Apex (Content Version and Content Document). Let me know on which topic I should write next.
Nicely written. Thanks for sharing!