Display A Document From SQL Server To A Web Page In ASP.NET MVC

Introduction 

 
In this blog post, I'll discuss a useful yet easy to implement document viewer API. Using that you can display a source file (e.g. Word, Presentation, Diagram, PSD) from your server to your browser without downloading it.
 
Some Use-Cases
  • Display a Word resume to a user in a web browser
  • Render a Visio Diagram on the web page
  • View a Presentation or a Slide online without downloading it
Implementation 
 
Now as the use-cases are clear, we will dive into the API implementation. It'll be an ASP.NET MVC application. We'll pull data/documents from the database and save it to a stream. You have to specify the file format in order to render it correctly. The source document will be then rendered to HTML. Eventually, our controller will return this stream to the View/browser.  
  1. public ActionResult Index()  
  2. {  
  3.      License lic = new License();  
  4.      lic.SetLicense(@"D:/GD Licenses/Conholdate.Total.NET.lic");  
  5.      MemoryStream outputStream = new MemoryStream();  
  6.      //specify just the file name if you are pulling the data from database   
  7.      string fileName = "sample.pdf";  
  8.   
  9.      FileType fileType = FileType.FromExtension(Path.GetExtension(fileName));  
  10.   
  11.      using (Viewer viewer = new Viewer(() => GetSourceFileStream(fileName), () => new LoadOptions(fileType)))  
  12.      {  
  13.            HtmlViewOptions Options = HtmlViewOptions.ForEmbeddedResources(  
  14.                 (pageNumber) => outputStream,  
  15.                 (pageNumber, pageStream) => { });  
  16.            viewer.View(Options);  
  17.      } 
  18.      outputStream.Position = 0;  
  19.      return File(outputStream, "text/html");  
  20.                
  21. }  
  22. private Stream GetSourceFileStream(string fileName) =>  
  23.             new MemoryStream(GetSourceFileBytesFromDb(fileName));  
  24.   
  25. //TODO: If you want to pull the data from the DB  
  26. private byte[] GetSourceFileBytesFromDb(string fileName) =>  
  27.             System.IO.File.ReadAllBytes(fileName);  
Have a look at this image/screenshot. We displayed a PDF from Server to Browser. 
 
Display A Document From SQL Server To A Web Page In ASP.NET MVC 
You can download the demo project here. In the case of any issue, you can post a thread here.