Be Good & Do Good!

How to define filename for a Visualforce generated PDF (renderAsPdf) ?

When rendering a visualforce page as a PDF, the filename of the PDF (by default) is the name of the page which may be annoying at times. Annoying as every time the file is generated, it will be generated with same name and will lead to cause confusion with the user. If opened multiple times, files will be saved as invoice.pdf, invoice[1].pdf, invoice[2].pdf … and so on. Ideally you should be able to define the name of the generated PDF but that’s not something well documented anywhere.

To rescue (as always) comes Salesforce blogs/forums [1][2].

In order to set filename for generated PDF you need to set the Content-Disposition header. In constructor of the Visualforce controller use below code:

Apexpages.currentPage().getHeaders().put('content-disposition', 'attachment; filename=AccountReport.pdf'); //In case you want to download pdf

or
Apexpages.currentPage().getHeaders().put('content-disposition', 'inline; filename=AccountReport.pdf'); //In case you want to open pdf in browser

Please Note : If you want to make the file name dynamic you will need to refer to several RFCs on how to correctly encode the filename. E.g. if it contains spaces it will need to be quoted. If there are non-ASCII characters or it is longer than 78 characters it needs to be Hex encoded (RFC 2184).

References
[1] https://salesforce.stackexchange.com/questions/4118/how-can-i-specify-a-file-name-for-a-visualforce-generated-pdf
[2] https://developer.salesforce.com/forums/ForumsMain?id=906F000000095BPIAY

2 Comments

  1. Shalabh Sharma

    content-disposition as inline does not work in IE and Firefox

  2. Hajir

    Hello Chirag,

    I found you on Stackoverflow looking through Salesforce answers. I couldn’t find your email address so I’m leaving a comment.

    We are looking for experts like yourself to expand our network and collaborate with. We would like to discuss with you possible opportunity in Salesforce Development.

    We are a Canadian web development company and you can learn more about us at http://bsup.ca

    Please feel free to reply me back at hajir@bsup (dot) ca to discuss this further.

    Regards,
    Hajir

Leave a Reply

Your email address will not be published. Required fields are marked *