Code:
@AuraEnabled
public static void savePDF(id recordId){
Opportunity opps = [SELECT Invoice_Number__c FROM Opportunity WHERE Id = :recordId];
SendInvoice__c invoice=new SendInvoice__c();
invoice.ConName__c=[select Title from ContentVersion where Title=: opps.Invoice_Number__c].id;
if (invoice.ConName__c != null) {
Opportunity opp = [SELECT Invoice_Number__c FROM Opportunity WHERE Id = :recordId];
PageReference pdfPage = new PageReference('/apex/newPageVf');
pdfPage.getParameters().put('Id', recordId);
Blob pdfBlob = pdfPage.getContentAsPDF();
String fileName = opp.Invoice_Number__c;
Id contentDocumentId = [SELECT ContentDocumentId FROM ContentVersion WHERE Title =: fileName].ContentDocumentId;
ContentVersion cv = new ContentVersion();
cv.Title = fileName;
cv.PathOnClient = fileName + '.pdf';
cv.VersionData = pdfBlob;
cv.contentDocumentId = contentDocumentId;
INSERT cv;
}
else {
Opportunity opp = [SELECT Invoice_Number__c FROM Opportunity WHERE Id = :recordId];
PageReference pdfPage = new PageReference('/apex/newPageVf');
pdfPage.getParameters().put('Id', recordId);
Blob pdfBlob = pdfPage.getContentAsPDF();
String fileName = opp.Invoice_Number__c;
ContentVersion cv = new ContentVersion();
cv.Title = fileName;
cv.PathOnClient = fileName + '.pdf';
cv.VersionData = pdfBlob;
INSERT cv;
Id contentDocumentId = [SELECT ContentDocumentId FROM ContentVersion WHERE Id = :cv.Id].ContentDocumentId;
Id opportunId = [SELECT Id FROM Opportunity WHERE id =: recordId].Id;
ContentDocumentLink cdl = new ContentDocumentLink();
cdl.ContentDocumentId = contentDocumentId;
cdl.LinkedEntityId = opportunId;
cdl.ShareType = 'V';
INSERT cdl;
}
}