I want to have a button that dowload a pdf page as a file related to the record from where I pressed the button. My page is working well, but I had to add a controller so clicking on the button download the page instead of showing me the page. I know that A way to do it is to creating a second VF page that will call the "real" page I want. But I prefered to find a way where I only needed to add a parameter to the page for the problem where the getContent() method call a new page that calls a new page and so on.
here is the code of my controller I greatly inspired myself from this question for my code
public class certificateDownloader {
public ApexPages.StandardController stdController {get; set;}
public certificateDownloader(ApexPages.StandardController controller){
stdController = controller;
}
public pageReference downloadPdf2() {
if (!Test.isRunningTest()) {//when accessing by a record
if (ApexPages.currentPage().getParameters().get('doNotSavePDF') == null) {
ApexPages.currentPage().getParameters().put('doNotSavePDF', 'true');
Blob certificatePdf = ApexPages.currentPage().getContent();
Attachment file = new Attachment(parentId = stdController.getId(), Name='test.pdf', body=certificatePdf);
insert file;
}
PageReference page = stdController.view();
page.setRedirect(true);
return page;
}
else {return null;}
}
}
here is the VF page:
<apex:page standardController="WorkOrder" renderAs="pdf" showHeader="false" standardStylesheets="false" extensions="certificateDownloader" action="{!downloadPdf2}">
stuff
</apex:page>
but for some reason the pdf downloaded as an Attachment is not working and seems corrupted each time I try opening it. I don't think the problem is with my VFpage, since it works well when I emove the action
parameter from the <apex:page>
EDIT : using getContentAsPdf() method isn't working either, the pdf it gives me is blank, and it doesn't change if I change the renderAs
parameter in <apex:page>
.
getContentAsPDF()
?getConentAsPDF()
is the expected way to this.