Hello friends, In this tutorial, I am providing a working example to set the user-defined filename of PDF when its rendered from a Visualforce page.

After completing this tutorial, you’ll able to:
  • Set PDF filename as per your consideration.

So let’s begin,

When you render a Visualforce Page as a PDF, the name of PDF file and name of the Visualforce page will same that lead to cause confusion with the user. To solve this problem you have to define the name of generated PDF. So I provide here pictorial solution with sample code that helps you a lot.

1. Navigate to Developer Console| New | Apex Class and create an apex controller and replace the following code.

Apex Controller:
 public class MyTestHandler {
 
    //Constructor
    public MyTestHandler(){
        
    }
 }
2. Navigate to Developer Console| New | Visualforce Page and create a visualforce page and replace the following code.

Visualforce Page: 
 <apex:page controller="MyTestHandler" renderAs="pdf">
    <h1>
        This is visualforce page render as PDF.
    </h1>
 </apex:page>
 After saving the visualforce page, when you preview it. Output will be:




3. Click on Download icon or hit Ctrl+S on the keyboard to save the pdf.


Now, you can see you Visualforce page and Save dialog box file name is same.


Note: In your case, it will display your created Visualforce page name and PDF file name.

4. To solve this problem we have to modified our apex class and add some magical code. So, here is the updated class.
 public class MyTestHandler {
 
    //Constructor
    public MyTestHandler(){
       String myGeneratedFileName = 'SalesforceScool.pdf';
       Apexpages.currentPage().getHeaders().put('content-disposition', 'inline; filename='+myGeneratedFilename); 
    }
 }

5. After saving the class, reload your visualforce page and click on Download icon or hit Ctrl+s on the keyboard. You can see, Save dialog box shows the file name as per your declared variable in the apex class.




If you want PDF file automatically downloaded with your defined name, so you have to make a small change in your apex class as per the below sample code.
 public class MyTestHandler {
 
    //Constructor
    public MyTestHandler(){
       String myGeneratedFileName = 'SalesforceScool.pdf';
       Apexpages.currentPage().getHeaders().put('content-disposition', 'attachment; filename='+myGeneratedFilename); 
    }
 }

After saving apex class reload the visualforce page, PDF file will automatically downloaded.



See also:

Conclusion 
Hope you like this tutorial, Please comment if you have any query or suggestion.
Thank you