Skip to content

Instantly share code, notes, and snippets.

@rdehler
Last active August 29, 2015 14:01
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save rdehler/53ca87d727970af661b8 to your computer and use it in GitHub Desktop.
Save and Open PDF template with Apex
/apex/SaveAndOpenPDF?id={!Contact.Id}
<apex:page controller="SaveAndOpenPDF" renderAs="{!renderAs}" action="{!saveAndOpenPDF}">
PDF Content Goes Here
</apex:page>
// Created by Ray Dehler, 2014-05-07
public with sharing class SaveAndOpenPDF {
public String recordId {
get {
return ApexPages.currentPage().getParameters().get('Id');
}
}
// this is to make testing a lot easier -- simply append renderAs=html
// to the url parameters to test, add displayOnly=1 if you don't want to save
public String renderAs {
get {
if (String.isBlank(ApexPages.currentPage().getParameters().get('renderAs'))) {
return 'pdf';
} else {
return ApexPages.currentPage().getParameters().get('renderAs');
}
}
}
public PageReference saveAndOpenPDF() {
if (String.isBlank(ApexPages.currentPage().getParameters().get('displayOnly'))) {
Id attachmentId = savePDF();
return openPDF(attachmentId);
} else {
return null;
}
}
public Id savePDF() {
Attachment attachment = new Attachment();
attachment.ParentId = recordId;
attachment.name = 'PDF_'+String.valueof(Datetime.now())+'.pdf';
PageReference pdf = Page.SaveAndOpenPDF;
pdf.getParameters().put('Id', recordId);
pdf.getParameters().put('displayOnly', '1');
pdf.setRedirect(true);
try {
attachment.Body = pdf.getContent();
}
catch (VisualForceException e) {
attachment.Body = Blob.valueof('There was an error.');
}
attachment.ContentType = 'application/pdf';
insert attachment;
return attachment.Id;
}
public PageReference openPDF(Id attachmentId) {
PageReference ret = new PageReference('/servlet/servlet.FileDownload?file=' + attachmentId);
ret.setRedirect(true);
return ret;
}
}
@isTest
private class SaveAndOpenPDF_Tests {
private static testMethod void testSaveAndOpenPDF() {
Account a = new Account(Name = 'Test');
insert a;
ApexPages.currentPage().getParameters().put('Id', a.Id);
SaveAndOpenPDF con = new SaveAndOpenPDF();
con.savePDF();
con.saveAndOpenPDF();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment