[SalesForce] Apex class to generate pdf and save it in attachement

I had created an apex class to generate a pdf and store the pdf into the attachment object.

I had called this apex class using a trigger. When the status is correction requested than the trigger will run and call the apex class.

But when I am changing the status to correction requested than at the same time two pdf is attached with the same name in attachment object.

I want to attach only one pdf at a time. And inside the pdf HTML tags, CSS tags and bootstrap is not working tags are printed as it is in pdf.

Below is the code for that:

public with sharing class MergePDF_Controller {
    @future
    public static void save(Id caseId) {
        PageReference pdf = new PageReference('/apex/MergePDF?id=' + caseId);
        Attachment attach = new Attachment();
        Case cs = [select Correction_file_number__c,Corrections_needed__c,CaseNumber, Household__c,PropertyCase__c from Case where Id = :caseId];
        System.debug('File Number' + cs.Correction_file_number__c);
        Blob bodyData;
        String htmlBody = '<html><title>Example</title>'
                + '<head><h1>Example page</h1></head>';
        try {
            bodyData = Blob.valueOf(htmlBody);
        } catch (VisualforceException e) {
        }
        double fileNumber = cs.Correction_file_number__c;
        System.debug('File Number' + fileNumber);
        attach.Body = bodyData;
        attach.Name = 'CorrectionCounter_' + fileNumber + '.pdf';
        attach.IsPrivate = false;
        attach.contentType = 'pdf';
        attach.ParentId = caseId;
        insert attach;
    }
}

Below is the trigger code:

trigger Correction_Counter on Case (before update) {
    Case cs = Trigger.New[0];
    if (cs.Status == 'Correction Requested') {
        if (Trigger.oldMap.get(cs.Id).Status != Trigger.newMap.get(cs.Id).Status) {
            MergePDF_Controller.Save(cs.Id);
        }
    }
}

Best Answer

Yes I got the solution add the code after attach.ParentId = caseId;

List <Attachment> listOfAttachment =[ select Name from Attachment where ParentId =: caseId];
    boolean temp = false;
    for(Attachment a : listOfAttachment){
        if(a.Name == 'CorrectionCounter_'+fileNumber +'.pdf'){
            temp = true;
            break;
        } 
    }