0
PageReference pdf = 
    new PageReference('https://c.na35.visual.force.com/apex/ReimbursementVoucher');
Attachment attach = new Attachment();
Blob attachBody;

try {
    attachBody = pdf.getContent();
} catch (VisualforceException e) {
    attachBody = Blob.valueOf('Error attaching the right file.');
}
attach.Body = attachBody;
attach.Name = reimb.Employee_Name__r.name+'.pdf';
attach.contentType = 'pdf';

Messaging.Emailfileattachment efa = new Messaging.Emailfileattachment();
efa.setFileName(attach.Name);
efa.setBody(attach.Body);
fileAttachments.add(efa);
mail.setFileAttachments(fileAttachments);

How to send a pdf attachment from visualforce page?

  • Is your current code experiencing any specific issue that you would care to share? Please edit your question to make it clear what is wrong with your current attempt. – Adrian Larson Feb 13 '17 at 7:16
  • I am not getting any attachment in email – user40665 Feb 13 '17 at 7:17
  • In your code above, you are not setting the blob as the body of the EmailFileAttachment. I guess this is the problem. – Mahmood Feb 13 '17 at 8:20
  • 1
    Never hardcode URL, its really bad, use PageReference pdf = new PageReference(Page.ReimbursementVoucher); instead – Raul Feb 13 '17 at 8:29
0

There is a Salesforce article detailing something very similar to your requirement.

There are few pieces you need to take care of, make sure your vf page has render as attribute as shown below

<apex:page standardController="Account" renderAs="PDF">

and then you need to create EmailFileAttachment, something like

// Reference the attachment page, pass in the account ID
PageReference pdf = Page.attachmentPDF;
pdf.getParameters().put('id',(String)account.id);
pdf.setRedirect(true);

// Take the PDF content
Blob b = pdf.getContent();

// Create the email attachment
Messaging.EmailFileAttachment efa = new Messaging.EmailFileAttachment();
efa.setFileName('attachment.pdf');
efa.setBody(b);

Also, check-out best practices for redering PDF files in apex.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.