+ Start a Discussion
Andrew EchevarriaAndrew 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:
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');
       Blob PDF = pageRef.getContent();
       return PDF;

VF Page:
<apex:page renderAs="pdf" cache="true" showHeader="false" sidebar="false" controller="AHelper" applyHtmlTag="false" applyBodyTag="false"  >

    <apex:outputPanel rendered="{!template != null}">
       <apex:outputtext value="{!template}" escape="false" />

AHelper generator = new AHelper();
generator.word = 'hello, world';

Debug Log:
generating: hello, world
returning template: null

Help would be much appreciated, I've been stuck on this for weeks.​ 
Rahul KumarRahul Kumar (Salesforce Developers) 
Hi, Andrew Echevarria

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. 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.

Rahul Kumar