View/Open a file in Document Object

Hi Folks

This post will help you to view or download (if its a word doc) a file in Visualforce page from the Document objects.

I had a requirement that when i click on a link in Visualforce page, it should open a file from Document Object in new tab. For example - Click on Terms&Conditions link. 

Follow the steps to do this:

Step 1: Add a pdf file in Document Object in Salesforce Org. For Eg: Add a pdf file in Document Object in the name of Terms And Conditions.

Step 2: Query the Document Record by Name and pass the document record id in page redirection URL.This method will refer in VF page to open a file in Document Object Record. Place this code in Apex Controller.

public Document reDirectToPdf(){
    Document doc = [select Id, Name, body ,Description from Document WHERE Name = 'Terms And Conditions' Limit 1];
    PageReference pageRef = new PageReference('/servlet/servlet.FileDownload?file='+doc.Id);
    return pageRef;    

Step 3: Add a Link in VF page to open a file in Document (Salesforce Standard Object) Record in new tab.

<apex:commandlink value="Terms and Conditions" action="{!reDirectToPdf}" target="_blank" />

When you click on this link, it will open a pdf file in new tab.

Happy Coding :)



Average: 4.3 (3 votes)