function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Neeraj Sharma 103Neeraj Sharma 103 

Hi Experts i have a Simple vf page and in vf page some fields are input and a save button

Hi Experts i have a Simple vf page and in vf page some fields are input and a save button when user fill the form and then clicked on save button then the data will be stored as a pdf and download it 
So Any Example how to achieve this functionaliy 
Best Answer chosen by Neeraj Sharma 103
Ajay K DubediAjay K Dubedi
Hi Neeraj,

Try the following example it works according to your requirement:
 Apex-Page:
<apex:page showHeader="false" standardStylesheets="false"
    standardController="Account" extensions="SaveAsPdfExtension"
    contentType="{! renderedContentType }" renderAs="{! renderingService }">

    <!-- 
    This page must be called with an Account ID in the URL, e.g.:
    https://<salesforceInstance>/apex/AccountContactsPdf?id=001D000000JRBet
    -->
        
    <apex:form rendered="{! renderingService != 'PDF' }"
               style="text-align: right; margin: 10px;">
        <apex:commandLink action="{! saveToPdf }" value="Save to PDF">
            <apex:param assignTo="{! renderedFileName }" value="Contact-List.pdf"/>
        </apex:commandLink>
        <hr/>
    </apex:form>
    
    <h1>Contacts for {! Account.Name}</h1>
    
    <apex:dataTable value="{! Account.Contacts }" var="contact">
        <apex:column headerValue="Name"  value="{! contact.Name  }"/>
        <apex:column headerValue="Title" value="{! contact.Title }"/>
        <apex:column headerValue="Phone" value="{! contact.Phone }"/>
        <apex:column headerValue="Email" value="{! contact.Email }"/>
    </apex:dataTable>

    <hr/>
    <!-- A little bit of info about the page's rendering; 
         see how it changes when saved as a PDF. -->
    contentType: <apex:outputText value=" {! renderedContentType }"/><br/>
    renderingService: <apex:outputText value=" {! renderingService }"/><br/>
</apex:page>

Controller:
public class SaveAsPdfExtension {

    // Required extension constructor (empty, no-op)
    public SaveAsPDFExtension(ApexPages.StandardController controller) {}
    
    // Determines what kind of rendering to use for the page request
    public String renderingService { get; private set; }
    
    // Allow the page to set the PDF file name
    public String renderedFileName { 
        get; 
        set { renderedFileName = this.sanitizeFileName(value); }
    }

    // Rendered content MIME type, used to affect HTTP response
    public String renderedContentType {
        get {
            String renderedContentType = 'text/html'; // the default
            
            if( ! this.renderingAsHtml() ) {
                // Provides a MIME type for a PDF document 
                renderedContentType = 'application/pdf';
                
                // Add a file name for the PDF file
                if( this.renderedFileName != null) {
                    // This is supposed to set the file name, but it doesn't work
                    renderedContentType += '#' + this.renderedFileName;
                    
                    // This is a work-around to set the file name
                    ApexPages.currentPage().getHeaders().put(
                        'content-disposition', 'attachment; filename=' + 
                         this.renderedFileName);
                }
            }
            
            return renderedContentType;
        }
    }
    
    // Are we rendering to HTML or PDF?
    public Boolean renderingAsHtml() {
        return ( (renderingService == null) || 
                 ( ! renderingService.startsWith('PDF')) );
    }

    // Action method to save (or "print") to PDF
    public PageReference saveToPdf() {
        renderingService = 'PDF';
        return null;
    }
    
    // Private helper -- basic, conservative santization
    private String sanitizeFileName(String unsafeName) {
        String allowedCharacters = '0-9a-zA-Z-_.';
        String sanitizedName = 
            unsafeName.replaceAll('[^' + allowedCharacters + ']', '');
        // You might also want to check filename length, 
        // that the filename ends in '.pdf', etc.
        return(sanitizedName);
    }
}



I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.

Thanks,
Ajay Dubedi

All Answers

Vikash Kumar MandalVikash Kumar Mandal
Hi Neeraj,
You can go through this link. It will help you

https://developer.salesforce.com/docs/atlas.en-us.pages.meta/pages/pages_output_pdf_renderas.htm

Thanks!
Ajay K DubediAjay K Dubedi
Hi Neeraj,

You will need the following:
1. A visualforce page which is rendered as PDF (I believe you already have it)
2. Create a new VF Page and a Controller. The Controller will do a getContentAsPDF for your PDF page. The blob that it gets from the PDF page, it will store it as an Attachment under the record.
3. Add a button on your object which will the call the VF page in point 2.
You can read this in more details at the following links:
http://raydehler.com/cloud/clod/apex-pattern-save-and-open-pdf-from-button.html
https://blog.jeffdouglas.com/2010/07/14/attach-a-pdf-to-a-record-in-salesforce/

I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.

Thanks,
Ajay Dubedi
Neeraj Sharma 103Neeraj Sharma 103
Hi Ajay Dubedi
 
<apex:page applyHtmlTag="false" showHeader="false" applyBodyTag="false" docType="html-5.0" standardStylesheets="false" controller="FromData">
    <apex:image value="{!URLFOR($Resource.image,'image.jpg')}"/>
<apex:pageBlock>
    &nbsp;
     <center>
         For good and valuable consideration, the receipt and sufficiency of which are hereby<br/>
         acknowledged,I hereby consent and agree to the following:
    </center>
    &nbsp;
       <center>
           I hereby grant to Nevada Blind Children’s Foundation (NBCF), and others working for NBCF or on<br/>        
           its behalf, and each of its respective licensees, successors and assigns (each a “Releasee”), the<br/>     
           irrevocable, royalty-free, perpetual, unlimited right and permission to use, distribute, publish,<br/>     
           exhibit, digitize, broadcast, display, modify, create derivative works of, reproduce or otherwise<br/>     
           exploit my name, picture, likeness and voice (including any video footage of the same) <br/>    
           (collectively, “Media”), or to refrain from so doing, anywhere in the world, by any persons or <br/>    
           entities deemed appropriate by NBCF, for any purpose (except defamatory) including, without<br/>     
           limitation, any use for educational, advertising, non-commercial or commercial purposes in any<br/>     
           manner or media whatsoever (whether known or hereafter devised) including, without <br/>    
           limitation, on the internet, in print campaigns, in-store and via television. I agree that I have no<br/>     
           interest or ownership in any of the Media.         
   </center>
      
    <br/>
    <center>
    I shall have no right of approval, no claim to compensation and no claim (including, without<br/>     
    limitation, claims based upon invasion of privacy, defamation or right of publicity) arising out of<br/>     
    any use, alteration, blurring, illusionary effect or use in any composite form of my name, picture,<br/>     
    likeness and voice. I agree that nothing in this Release will create any obligation on NBCF to make<br/>     
    any use of the Media or the rights granted in this Release. I hereby release and hold harmless<br/>     
    Releasees from any claim for injury, compensation or negligence resulting or arising from any <br/>    
    activities authorized by this Release and any use of the Media by NBCF.   
   </center>
    &nbsp;
     <apex:form style="margin-left:30rem;">
         NAME OF PARTICIPANT(please print)&nbsp;<apex:input type="text" style="width:20rem;"/>
         <br/>
         <br/>
         ADDRESS: &nbsp;<apex:input type="text" style="width:33rem;"/>
         <br/>
          <br/>
            &nbsp;CITY<apex:input type="text"/>
            &nbsp;STATE<apex:input type="text"/>
          &nbsp;ZIP<apex:input type="number" value="{!dataNumber}"/><br/>
          <br/>
         &nbsp;HOMEPHONE <apex:input type="number" value="{!dataNumber}"/>
         &nbsp;CELLPHONE <apex:input type="number" value="{!dataNumber}" style="width:17rem;"/>
         <br/>
         <br/>
         &nbsp;EMAIL ADDRESS <apex:input type="email" value="{!email}" style="width:33rem;"/>
         <p>
           Release for Minors (those under the age of eighteen): I, the undersigned, being a parent or<br/>
           guardian of the minor, hereby consent to the foregoing conditions and warrant that I have the<br/> 
           authority to give such consent.                           
         </p>
          DATE &nbsp;<apex:input type="date" value="{!datadate}"/>
         <br/>
         <br/>
        &nbsp;NAME OF PARENT/LEGAL GUARDIAN(print)<apex:input type="text" style="width:21rem;"/>
         <br/>
         <br/>
         &nbsp;PARENT/LEGAL GUARDIAN EMAIL<apex:input type="email" value="{!email}" style="width:25rem;"/>
          <br/>
         <br/>
          <apex:commandButton value="Save" action="{!savepdf}"/>
         
    </apex:form>
</apex:pageBlock>
    
   
</apex:page>

this is my vf page when i clicked on save button then the values input by users in field will download as pdf
 
public class FromData {
    public Integer dataNumber { get; set; }
    
    public String email{get;set;}
    
    public Date datadate{get;set;}
    
    
    public void savepdf()
    {
   
    }
    
    

}

​​​​​​​
Ajay K DubediAjay K Dubedi
Hi Neeraj,

Try the following code of vfPage ,Convert a page to PDF by changing the <apex:page> tag to <apex:page renderAs="pdf">.
So try the following code:
 
<apex:page applyHtmlTag="false" showHeader="false" applyBodyTag="false" docType="html-5.0" standardStylesheets="false" controller="FromData" renderAs="pdf">
    <apex:image value="{!URLFOR($Resource.image,'image.jpg')}"/>
<apex:pageBlock>
    &nbsp;
     <center>
         For good and valuable consideration, the receipt and sufficiency of which are hereby<br/>
         acknowledged,I hereby consent and agree to the following:
    </center>
    &nbsp;
       <center>
           I hereby grant to Nevada Blind Children’s Foundation (NBCF), and others working for NBCF or on<br/>        
           its behalf, and each of its respective licensees, successors and assigns (each a “Releasee”), the<br/>     
           irrevocable, royalty-free, perpetual, unlimited right and permission to use, distribute, publish,<br/>     
           exhibit, digitize, broadcast, display, modify, create derivative works of, reproduce or otherwise<br/>     
           exploit my name, picture, likeness and voice (including any video footage of the same) <br/>    
           (collectively, “Media”), or to refrain from so doing, anywhere in the world, by any persons or <br/>    
           entities deemed appropriate by NBCF, for any purpose (except defamatory) including, without<br/>     
           limitation, any use for educational, advertising, non-commercial or commercial purposes in any<br/>     
           manner or media whatsoever (whether known or hereafter devised) including, without <br/>    
           limitation, on the internet, in print campaigns, in-store and via television. I agree that I have no<br/>     
           interest or ownership in any of the Media.         
   </center>
      
    <br/>
    <center>
    I shall have no right of approval, no claim to compensation and no claim (including, without<br/>     
    limitation, claims based upon invasion of privacy, defamation or right of publicity) arising out of<br/>     
    any use, alteration, blurring, illusionary effect or use in any composite form of my name, picture,<br/>     
    likeness and voice. I agree that nothing in this Release will create any obligation on NBCF to make<br/>     
    any use of the Media or the rights granted in this Release. I hereby release and hold harmless<br/>     
    Releasees from any claim for injury, compensation or negligence resulting or arising from any <br/>    
    activities authorized by this Release and any use of the Media by NBCF.   
   </center>
    &nbsp;
     <apex:form style="margin-left:30rem;">
         NAME OF PARTICIPANT(please print)&nbsp;<apex:input type="text" style="width:20rem;"/>
         <br/>
         <br/>
         ADDRESS: &nbsp;<apex:input type="text" style="width:33rem;"/>
         <br/>
          <br/>
            &nbsp;CITY<apex:input type="text"/>
            &nbsp;STATE<apex:input type="text"/>
          &nbsp;ZIP<apex:input type="number" value="{!dataNumber}"/><br/>
          <br/>
         &nbsp;HOMEPHONE <apex:input type="number" value="{!dataNumber}"/>
         &nbsp;CELLPHONE <apex:input type="number" value="{!dataNumber}" style="width:17rem;"/>
         <br/>
         <br/>
         &nbsp;EMAIL ADDRESS <apex:input type="email" value="{!email}" style="width:33rem;"/>
         <p>
           Release for Minors (those under the age of eighteen): I, the undersigned, being a parent or<br/>
           guardian of the minor, hereby consent to the foregoing conditions and warrant that I have the<br/> 
           authority to give such consent.                           
         </p>
          DATE &nbsp;<apex:input type="date" value="{!datadate}"/>
         <br/>
         <br/>
        &nbsp;NAME OF PARENT/LEGAL GUARDIAN(print)<apex:input type="text" style="width:21rem;"/>
         <br/>
         <br/>
         &nbsp;PARENT/LEGAL GUARDIAN EMAIL<apex:input type="email" value="{!email}" style="width:25rem;"/>
          <br/>
         <br/>
          <apex:commandButton value="Save" action="{!savepdf}"/>
         
    </apex:form>
</apex:pageBlock>
    
   
</apex:page>



I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.

Thanks,
Ajay Dubedi
Neeraj Sharma 103Neeraj Sharma 103
Hi  Ajay Dubedi
When i  preview a vf page in developer console then its show as a pdf when i used  renderAs="pdf" but my requirement is user input the record in fields and then clicked on save button then the values fill up in the field will be download as pdf after clicked on save buton

Thanks
Neeraj
Ajay K DubediAjay K Dubedi
Hi Neeraj,

Try the following example it works according to your requirement:
 Apex-Page:
<apex:page showHeader="false" standardStylesheets="false"
    standardController="Account" extensions="SaveAsPdfExtension"
    contentType="{! renderedContentType }" renderAs="{! renderingService }">

    <!-- 
    This page must be called with an Account ID in the URL, e.g.:
    https://<salesforceInstance>/apex/AccountContactsPdf?id=001D000000JRBet
    -->
        
    <apex:form rendered="{! renderingService != 'PDF' }"
               style="text-align: right; margin: 10px;">
        <apex:commandLink action="{! saveToPdf }" value="Save to PDF">
            <apex:param assignTo="{! renderedFileName }" value="Contact-List.pdf"/>
        </apex:commandLink>
        <hr/>
    </apex:form>
    
    <h1>Contacts for {! Account.Name}</h1>
    
    <apex:dataTable value="{! Account.Contacts }" var="contact">
        <apex:column headerValue="Name"  value="{! contact.Name  }"/>
        <apex:column headerValue="Title" value="{! contact.Title }"/>
        <apex:column headerValue="Phone" value="{! contact.Phone }"/>
        <apex:column headerValue="Email" value="{! contact.Email }"/>
    </apex:dataTable>

    <hr/>
    <!-- A little bit of info about the page's rendering; 
         see how it changes when saved as a PDF. -->
    contentType: <apex:outputText value=" {! renderedContentType }"/><br/>
    renderingService: <apex:outputText value=" {! renderingService }"/><br/>
</apex:page>

Controller:
public class SaveAsPdfExtension {

    // Required extension constructor (empty, no-op)
    public SaveAsPDFExtension(ApexPages.StandardController controller) {}
    
    // Determines what kind of rendering to use for the page request
    public String renderingService { get; private set; }
    
    // Allow the page to set the PDF file name
    public String renderedFileName { 
        get; 
        set { renderedFileName = this.sanitizeFileName(value); }
    }

    // Rendered content MIME type, used to affect HTTP response
    public String renderedContentType {
        get {
            String renderedContentType = 'text/html'; // the default
            
            if( ! this.renderingAsHtml() ) {
                // Provides a MIME type for a PDF document 
                renderedContentType = 'application/pdf';
                
                // Add a file name for the PDF file
                if( this.renderedFileName != null) {
                    // This is supposed to set the file name, but it doesn't work
                    renderedContentType += '#' + this.renderedFileName;
                    
                    // This is a work-around to set the file name
                    ApexPages.currentPage().getHeaders().put(
                        'content-disposition', 'attachment; filename=' + 
                         this.renderedFileName);
                }
            }
            
            return renderedContentType;
        }
    }
    
    // Are we rendering to HTML or PDF?
    public Boolean renderingAsHtml() {
        return ( (renderingService == null) || 
                 ( ! renderingService.startsWith('PDF')) );
    }

    // Action method to save (or "print") to PDF
    public PageReference saveToPdf() {
        renderingService = 'PDF';
        return null;
    }
    
    // Private helper -- basic, conservative santization
    private String sanitizeFileName(String unsafeName) {
        String allowedCharacters = '0-9a-zA-Z-_.';
        String sanitizedName = 
            unsafeName.replaceAll('[^' + allowedCharacters + ']', '');
        // You might also want to check filename length, 
        // that the filename ends in '.pdf', etc.
        return(sanitizedName);
    }
}



I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.

Thanks,
Ajay Dubedi
This was selected as the best answer