You need to sign in to do that
Don't have an account?
Andrew Echevarria
Generating PDF from Apex via PageReference
Hello all,
I'm calling an Apex class called AHelper from the Developer Console, that initializes the class and sets an variable. Next, I call a funciton to generate a PDF page using the same controller, but it seems that the PDF page's controller is re-initialized (local variable is reset to null).
The debug logs show this value is successfully set when I set it.
Apex class:
VF Page:
Execution:
Debug Log:
Help would be much appreciated, I've been stuck on this for weeks.
I'm calling an Apex class called AHelper from the Developer Console, that initializes the class and sets an variable. Next, I call a funciton to generate a PDF page using the same controller, but it seems that the PDF page's controller is re-initialized (local variable is reset to null).
The debug logs show this value is successfully set when I set it.
Apex class:
public class AHelper{ public String word; public String getTemplate(){ System.debug('returning template: ' + word); return word; } public Blob generatePDF(){ System.debug('generating: ' + word); PageReference pageRef = new PageReference('/apex/UnitCertGenerator'); pageRef.setRedirect(false); Blob PDF = pageRef.getContent(); return PDF; } }
VF Page:
<apex:page renderAs="pdf" cache="true" showHeader="false" sidebar="false" controller="AHelper" applyHtmlTag="false" applyBodyTag="false" > <head> <style> @page{ margin-top:1cm; margin-bottom:0cm; } </style> </head> <apex:outputPanel rendered="{!template != null}"> <apex:outputtext value="{!template}" escape="false" /> </apex:outputPanel> </apex:page>
Execution:
AHelper generator = new AHelper(); generator.word = 'hello, world'; generator.generatePDF();
Debug Log:
generating: hello, world returning template: null
Help would be much appreciated, I've been stuck on this for weeks.
You can use the PageReference.getContentAsPDF() method in Apex to render a Visualforce page as PDF data. Then use Apex code to convert that PDF data to an email attachment, a document, a Chatter post, and so on.
Please refer the below link for reference.
- https://developer.salesforce.com/docs/atlas.en-us.pages.meta/pages/pages_output_pdf_render_in_apex.htm
Hope it will be helpful.Please mark it as best answer if the information is informative.so that question is removed from an unanswered question and appear as a proper solution.
Thanks
Rahul Kumar