1

I have a VF page(renderAs=pdf) when I clicked on the custom button its generates pdf and saves that pdf in the attachment-related list. Now I want to save that pdf in File related list how to do this.

The below method save the pdf in Attachment related list

public PageReference attachPDF() {
       

        PageReference pdfPage = Page.File_save;
         
        
        Blob pdfBlob; 
        pdfPage.getParameters().put('id',a.Id);
        
        if (!Test.isRunningTest()) { 
            pdfBlob = pdfPage.getContent(); 
        } else { 
            pdfBlob = Blob.valueOf('Some Text for a boring PDF file...');
        }
        Attachment attach = new Attachment(parentId = a.Id, Name = 'Test'+'.pdf', body = pdfBlob);
        insert attach;

Does anyone have an idea for the File?

0

1 Answer 1

2

You will need to first create a Content Version Record and then a ContentDocumentLink record.

ContentVersion fileToUpload = new ContentVersion();
    fileToUpload.ContentLocation = 'S'; // Salesforce. The other option is: 'E'
    fileToUpload.pathOnClient ='samplefile.pdf';
    fileToUpload.title = 'Sample File';
    fileToUpload.versionData = Blob.valueOf('Some Text for a boring PDF file...');
    Database.SaveResult saveResult;
    try {
        saveResult = Database.insert(fileToUpload);
    } catch (DmlException DMLE) {
        system.debug(
            'Failed to insert fileToUpload, error is: ' + dmle.getMessage()
        );
    }

 // Create a ContentDocument Link Record
 // First get the content document Id from ContentVersion
 Id contentDocumentId = [SELECT ContentDocumentId FROM ContentVersion WHERE Id =:fileToUpload.Id].ContentDocumentId;

//Create ContentDocumentLink
ContentDocumentLink linkToRecord = new ContentDocumentLink();
linkToRecord.ContentDocumentId = contentDocumentId;
linkToRecord.LinkedEntityId = a.Id; // RecordID of the patent
linkToRecord.ShareType = 'I'; // Inferred permission

ContentDocumentLink object for more details linkToRecord.Visibility = 'InternalUsers'; insert linkToRecord;

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .