+ Start a Discussion
BB 

How to save instantly my pdf visualforcepage as a file/attachment

Here is my vf 

<apex:page standardController="Opportunity" standardStylesheets="false" applyHtmlTag="false" showHeader="false" renderAs="PDF">

    <head>
     ...style..    
   </head>
<body>
   .... information generated based on the opportunity fields..
</body>
</apex:page>

The vf is linked to a detailed buton.
When i click  the button  it opens vf page but in the same time i want to be saved as an attachment/file in the opportunity  

Any suggested implementations ? 
 
Best Answer chosen by B
Raj VakatiRaj Vakati
Use code like below

https://blog.webnersolutions.com/salesforce-attach-pdf-from-visualforce-page-as-an-email-attachment

http://www.terrasky.com/create-a-render-a-visualforce-page-as-pdf-button/
http://www.interactiveties.com/blog/2015/visualforce-button-pdf.php
https://developer.salesforce.com/docs/atlas.en-us.pages.meta/pages/pages_output_pdf_render_in_apex.htm 
 
PageReference PDf =  Page.templateCOI;//Replace attachmentPDf with the page you have rendered as PDF
PDf.getParameters().put('Id',Id);
PDf.setRedirect(true);
Attachment attach = new Attachment();
Blob b ;
b = PDf.getContent();
attach.Body = b;
attach.Name = 'Confirmation of product';
attach.IsPrivate = false;
attach.ParentId = Id;
insert attach;

 

All Answers

JayantJayant
Use getContentAsPDF() method to get the PDF as a blob, and save the blob in attachments.
I would prefer first saving the PDF in attachment and then opening the attachment on top of current window rather than opening the PDF first and saving a copy in attachment.
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_System_PageReference_getContentAsPDF.htm
Raj VakatiRaj Vakati
Use code like below

https://blog.webnersolutions.com/salesforce-attach-pdf-from-visualforce-page-as-an-email-attachment

http://www.terrasky.com/create-a-render-a-visualforce-page-as-pdf-button/
http://www.interactiveties.com/blog/2015/visualforce-button-pdf.php
https://developer.salesforce.com/docs/atlas.en-us.pages.meta/pages/pages_output_pdf_render_in_apex.htm 
 
PageReference PDf =  Page.templateCOI;//Replace attachmentPDf with the page you have rendered as PDF
PDf.getParameters().put('Id',Id);
PDf.setRedirect(true);
Attachment attach = new Attachment();
Blob b ;
b = PDf.getContent();
attach.Body = b;
attach.Name = 'Confirmation of product';
attach.IsPrivate = false;
attach.ParentId = Id;
insert attach;

 
This was selected as the best answer
BB
I have a problem when i insert attachment is inserted multiple times 
Here is the code 

public with sharing class PdfSaverController {
    
  public Opportunity opp {get;set;}
  public Account acc {get;set;}
   public Boolean initialised = true;

  
   public PdfSaverController (ApexPages.StandardController controller) {
    
         Opportunity  oppId = new Opportunity();
          initialised = false; 
    try{   
         oppId = (Opportunity)controller.getRecord();
        
         opp = [Select id,Name, AccountId  , Auto_Deal_Number__c from 
                         Opportunity where id =: oppId.Id  LIMIT: 1];
         acc = [Select id,Name from 
                         Account where id =: opp.AccountId  LIMIT: 1];

    }catch(Exception e){
        e.getMessage();  
    }    
   
         
    
  }

    public void savePDF(){
        
    if (initialised == false && opp!=NULL) {
        initialised = true;
        PageReference pdf = Page.CreateSportsmanPDF;
    // add parent id to the parameters for standardcontroller
    pdf.getParameters().put('id',opp.Id);

    // create the new attachment
    Attachment attach = new Attachment();
    
    // the contents of the attachment from the pdf
    Blob body;
    
    try {
        
        // returns the output of the page as a PDF
        body = pdf.getContent();
        
    // need to pass unit test -- current bug    
    } catch (VisualforceException e) {
        body = Blob.valueOf('Error');
    }

    attach.Body = body;
    // add the user entered name
    attach.Name = 'SPORTSMAN ' +acc.Name + '-' + opp.Auto_Deal_Number__c + '.pdf';
    attach.IsPrivate = false;
    // attach the pdf to the opportunity
    attach.ParentId = opp.Id;   
    insert attach;
   

    }else{ system.debug('tried to run twice');}
   }
    

}



 
BB
Found the solution 

public void savePDF()
{ if(ApexPages.currentPage().getParameters().containsKey('generatepdf')) { return; }
PageReference pdf = ApexPages.currentPage();
pdf.getParameters().put('generatepdf','true');
Blob file = pdf.getContent(); // Rest of code here }
Eric Latreille 8Eric Latreille 8
Hi Guys, I need some help here. I created a button on the Account Object called SavePDF. I saw many threads (old one) but nothing very new and this is probably why I am not able to make this work.
Case scenario:
When I click on Save PDF button, I want that pdf created and saved in the File and Attachment of that specific record. Pretty simple right?!
I used Interactive Ties example (http://www.interactiveties.com/blog/2015/visualforce-button-pdf.php) and it does most of it. The issue is, his example do not return any data from an object.

Here is my code, hoping someone can help
APEX CLASS:

public class attachPDFToAccount {
    
    private final Account a; //Account object
    
    //constructor
    public attachPDFToAccount(ApexPages.StandardController standardPageController) {
        a = (Account)standardPageController.getRecord(); //instantiate the Account object for the current record
    }
    
    //method called from the Visualforce's action attribute
    public PageReference attachPDF() {
        
        //generate and attach the PDF document
        PageReference pdfPage = Page.pdfDemo;
        
        Blob pdfBlob; //create a blob for the PDF content
        if (!Test.isRunningTest()) { //if we are not in testing context
            pdfBlob = pdfPage.getContent(); //generate the pdf blob
        } else { //otherwise, we are in testing context and getContent() gets funky so create the blob manually
            pdfBlob = Blob.valueOf('Some Text for a boring PDF file...');
        }
        Attachment attach = new Attachment(parentId = a.Id, Name = 'Test.pdf', body = pdfBlob); //create the attachment object
        insert attach; //insert the attachment
        
        //redirect the user
        PageReference pageWhereWeWantToGo = new ApexPages.StandardController(a).view(); //we want to redirect the User back to the Account detail page
        pageWhereWeWantToGo.setRedirect(true); //indicate that the redirect should be performed on the client side
        return pageWhereWeWantToGo; //send the User on their way
    }

}

VF PAGE - pdfDemo (This is the page that is rendered as a PDF with the data of the account that is currently NOT working!)
<apex:page standardController="Account" extensions="attachPDFToAccount" renderAs="pdf">

<apex:form >
    <apex:pageBlock >             
        <apex:pageBlockTable value="{!account}" var="a">
            <apex:column value="{!a.Id}" />
            <apex:column value="{!a.Name}" />     
        </apex:pageBlockTable>             
    </apex:pageBlock>
   </apex:form>
    
</apex:page>

VF PAGE: attachPDFToAccount
<apex:page action="{!attachPDF}" standardController="Account" extensions="attachPDFToAccount">
    <apex:pageMessages ></apex:pageMessages>
    <apex:detail inlineEdit="true" relatedList="true"></apex:detail>
</apex:page>

From my button, if I call the pdfDemo Page directly, the data is showing but when I call the attachPDFToAccount, the data is empty.

Thanks for your help!
Eric Latreille 8Eric Latreille 8
Found it!
Added that line right over the Blob pdfBlob: pdfPage.getParameters().put('id',a.Id);
Meggan Landis 2Meggan Landis 2
Hey Eric,
I am trying to do this exact thing...how do you write your VF page to include all fields on the record itself? I used the code you added to a sandbox and the generated (and attached) pdf, but there wasn't any content on the pdf. Is there an easy way to include all fields on the layout?

Thanks!

Megg