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
AbAb 

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

Hello,

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 Ab
Atish Pradeep 8Atish Pradeep 8
Hai,
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


</apex:page>
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');
    pdf.setRedirect(true);
    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);
    ret.setRedirect(true);
    return ret;
  }
}