An effort to bring a revolution in Salesforce.

Wednesday 12 August 2015

How Rendering a Visualforce page as PDF and saving it as an attachement in salesforce

How can U render a VF (Visualforce ) page as PDF and have a button on the page that saves this PDF as an attachment ?


Apex Class Code:

public class PdfRender{
    public Account acc {get;set;}
    public List<Account> ListAcc {get;set;}
   
   
    public PdfRender(){
    ListAcc = new List<Account>();
    acc = new Account();
    ListAcc =[Select Name,AccountNumber from Account Limit 10 ];
    }
   
    // return 'pdf' if the parameter 'p' has been passed to the page, or null
    public String getSelectRender() {
        if(ApexPages.currentPage().getParameters().get('p') != null)
            return 'pdf';
        else
            return null;
    }
  

    public PageReference RenderedAsPDF() {
        PageReference pdf =  Page.RenderedAsPdf;
        pdf.getParameters().put('p','p');
       

  // Below code to Save Pdf in attachment

        Blob pdf1 = pdf.getcontentAsPdf();
        Document d = new Document();
        d.FolderId = UserInfo.getUserId();
        d.Body = Pdf1;
        d.Name = 'pdf_file.pdf';
        d.ContentType = 'application/pdf';
        d.Type = 'pdf';
        insert d;
    return pdf;
    }
    }

Visualforce Page Code:

<apex:page showHeader="false"  sidebar="false" renderAs="{!SelectRender}" controller="PdfRender" >
    <apex:pageBlock title="Demo Pdf View">
    <apex:pageBlockSection > 
    <apex:pageBlockTable value="{!ListAcc}" var="ac">
                <apex:column value="{!ac.name}"/>
                 <apex:column value="{!ac.AccountNumber}"/>
            </apex:pageBlockTable>
    </apex:pageBlockSection>
    </apex:pageBlock>
    <apex:form >
    <apex:commandButton action="{!RenderedAsPDF}" value="PDF View" id="theButton"/>
    </apex:form>
</apex:page>

,

No comments:

Post a Comment

Get Gmail, Docs, Drive, and Calendar for business