[SalesForce] Facing problem with PDF Attachment

I have employee record where I am having a custom Button "GeneratePayslip" after clicking on which I have written a VF page "GeneratePayslip" and on that VF page I select a Month and click generate button, on that click a new VF page is displayed as PDF – "GeneratePayslipPDF".
I want to attach that generated PDF to the selected Employee after the Payslip is generated. How can I achieve this please guide me to get this problem solve.

I am almost written everything – Attachment, Blob, etc.
Initially i was facing problem of .getContent() method of attachment object, but its solved by putting that code in TRY-Catch.
Now there is no error messages but I did not Found the Attachment.

Best Answer

That's because try{} catch{} block didn't solved your problem, it just catch exception and handle it...

About code, try:

PageReference thePage = Page./*your page*/;
        thePage.setRedirect(false);
        thePage.getParameters().put(/*your atribute*/ , /*value of atribute*/);
        blob body = null;
        if (!Test.isRunningTest()){
            body = thePage.getContentAsPDF(); 
        }
        // It is here for testing purposes - as you cant call ".getContentAsPDF()" methode in test
        else{
            body = Blob.valueof('Some random String');
        }     
        attachment pdf = new attachment();
        pdf.name = /*name of your attachment*/;
        pdf.body = body;
        pdf.ParentId = /*Id of parent object */;
        pdf.isPrivate = false;

        insert pdf;
Related Topic