+ Start a Discussion

Open a PDf file attached to a Opportunity in VF on click of a file


On an Opportunity i have Files sections, where user can upload any file fr example PDF.

My usecase is that, when the user clicks on the file, the pdf opens in Visualforce page.

Is there any solution possible,

thank you in advance.

Best Answer chosen by Sandrine
Atish Pradeep 8Atish Pradeep 8
Saving a PDF is so simple with Visualforce  simply utilize
<apex:page> with the attribute renderAs=”pdf”. 
<apex:page controller="SaveAndOpenPDF" renderAs="{!renderAs}" action="{!saveAndOpenPDF}">

PDF Content Goes Here

Please check the following class .
public with sharing class SaveAndOpenPDF {
  public String recordId {
    get {
      return ApexPages.currentPage().getParameters().get('Id');

  // this is to make testing a lot easier -- simply append renderAs=html
  // to the url parameters to test, add displayOnly=1 if you don't want to save
  public String renderAs {
    get {
      if (String.isBlank(ApexPages.currentPage().getParameters().get('renderAs'))) {
        return 'pdf';
      } else {
        return ApexPages.currentPage().getParameters().get('renderAs');

  public PageReference saveAndOpenPDF() {
    if (String.isBlank(ApexPages.currentPage().getParameters().get('displayOnly'))) {
      Id attachmentId = savePDF();
      return openPDF(attachmentId);
    } else {
      return null;

  public Id savePDF() {
    Attachment attachment = new Attachment();
    attachment.ParentId = recordId;
    attachment.name = 'PDF_'+String.valueof(Datetime.now())+'.pdf';
    PageReference pdf = Page.SaveAndOpenPDF;
    pdf.getParameters().put('Id', recordId);
    pdf.getParameters().put('displayOnly', '1');
    try {
      attachment.Body = pdf.getContent();
    catch (VisualForceException e) {
      attachment.Body = Blob.valueof('There was an error.');
    attachment.ContentType = 'application/pdf';
    insert attachment;
    return attachment.Id;

  public PageReference openPDF(Id attachmentId) {
    PageReference ret = new PageReference('/servlet/servlet.FileDownload?file=' + attachmentId);
    return ret;