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.

2 Answers 2


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.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
            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;
  • Thank You ! for the reply but i have tried the same and one more time I did, but still it doesn't work. Jun 4, 2014 at 11:48
  • I am getting "System.VisualforceException: system.security.NoDataFoundException: Unable to retrieve object" exception for pg.getContent() Jun 4, 2014 at 12:52
  • I guess that is issue of page, are you sure you set all required paramethers? Jun 4, 2014 at 13:02
  • Ya, I got the Attachment now, but just its field values are not coming, i might be missing something and I am working on it, let you know if there is any problem again! Thank You ! Jun 4, 2014 at 13:17
  • See here, what could be possible situation ---salesforce.stackexchange.com/questions/38756/… Jun 5, 2014 at 11:17

There are a number of ways to accomplish this. Shameless self promotion for a simple pattern to accomplish this: http://raydehler.com/cloud/clod/apex-pattern-save-and-open-pdf-from-button.html

Your code will look something like this:

Attachment attachment = new Attachment();
attachment.ParentId = recordId; // you have to fill in the value of the parent here
attachment.name = 'PDF_'+String.valueof(Datetime.now())+'.pdf';
PageReference pdf = Page.GeneratePayslipPDF;
try {
  attachment.Body = pdf.getContent();
catch (VisualForceException e) {
  attachment.Body = Blob.valueof('There was an error.');
attachment.ContentType = 'application/pdf';
insert attachment;

You must log in to answer this question.

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