Introduction
You are working on a web application and the business need is to display all kinds of file formats (e.g. Word, Excel, PDF, Presentation, MSG, EML, PSD, CAD) to the client. The restriction or limitation is not to install native applications on the server. This is because installing MS Office, Autodesk, Adobe Acrobat will surely require a lot of resources (e.g. space and RAM). Let's discuss a one-stop solution for this requirement.
Proposed Solution
What about a
stand-alone API (.NET Core compatible) that takes any supported file
format as input, renders it to PDF, HTML, or Image file format (depending on the use-case). Later, these resultant files could be displayed in the browser or any other application (e.g. Windows Forms, Mobile).
Key Features
- Extract source document information (e.g. file type, page count)
- Document transformation (for example you can add textual watermark, page rotation, and reordering)
- Increase rendering performance by caching rendering results
- Load document from the local driver or from cloud storage (e.g. FTP, Azure Blob, Amazon S3, URL, Stream)
- Specify document encoding while rendering
- Load a password-protected file
Implementation
In your HomeController/Index, you will get the source file. Convert it to byte[] and pass byte[] to MemoryStream. After that, you will pass the MemoryStream to the Razor View using ViewData.
- public class HomeController : Controller
- {
- private readonly ILogger<HomeController> _logger;
- public HomeController(ILogger<HomeController> logger)
- {
- _logger = logger;
- }
- public IActionResult Index()
- {
- string pageContent = $"This content is passed through ViewData.";
- byte[] pageBytes = Encoding.UTF8.GetBytes(pageContent);
- MemoryStream outputStream = new MemoryStream(pageBytes);
-
- ViewData["PageContent"] = outputStream;
-
- return View();
- }
- public IActionResult Page(int pageNumber)
- {
- string pageContent = $"This is page {pageNumber}.";
- byte[] pageBytes = Encoding.UTF8.GetBytes(pageContent);
- MemoryStream outputStream = new MemoryStream(pageBytes);
-
- return File(outputStream, "text/html");
- }
- [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
- public IActionResult Error()
- {
- return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
- }
- }
In View, you have to Encode (UTF8) the stream and display it using
Html.Raw. Have a look at the output (I tried to display a Word document).
Conclusion
Using this standard web application, you can display any (top and mostly used) file formats in the browser without third party tool or software dependency. The best thing about this API is that it's UI-Independent. Hence, you can develop customized tool-bars or even page previews (thumbnails) in your application. You can post
here, in case of any API related issue(s).