Dynamically choose whether a Visualforce page is rendered as a PDF or not-useful when creating invoices and so on also can email that page using a little Apex code.
public class EmailingVisual { public PageReference getDeliverAsPDF() {
// Reference the page, pass in a parameter to force PDF
PageReference pdf = Page.EmailPage;
pdf.getParameters().put('p','p');
pdf.setRedirect(true);
// Grab it!
Blob b = pdf.getContent();
// Create an email
Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
email.setSubject('From getDeliverAsPDF!');
String [] toAddresses = new String[] {'youremailaddress'};
email.setToAddresses(toAddresses);
email.setPlainTextBody('Here is the body of the email');
// Create an email attachment
Messaging.EmailFileAttachment efa = new Messaging.EmailFileAttachment();
efa.setFileName('MyPDF.pdf'); // neat - set name of PDF
efa.setBody(b); //attach the PDF
email.setFileAttachments(new Messaging.EmailFileAttachment[] {efa});
// send it, ignoring any errors (bad!)
Messaging.SendEmailResult [] r =
Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});
return null;
}}
Then the EmailPage Looks like this and Make sure give your email address in the controller to test this
<apex:page renderAs="{!if($CurrentPage.parameters.p == null, null, 'pdf')}"
controller="EmailingVisual">
<apex:pageBlock title="My Dual-Rendering Invoice">
<apex:pageBlockSection title="Section 1"> Text </apex:pageBlockSection>
<apex:pageBlockSection title="Section 2"> Text </apex:pageBlockSection>
</apex:pageBlock>
<apex:form >
<apex:commandLink rendered="{!$CurrentPage.parameters.p == null}" value="PDF" action="{!getDeliverAsPDF}" ></apex:commandLink>
</apex:form>
</apex:page>
No comments:
Post a Comment