This article will demonstrate how to create a thumbnail image from live Microsoft Office documents and PDF documents.
![]()
Getting thumbnails from images is not a very tough task; we can directly convert our image to Bitmap type and generate a thumbnail. So, it’s very simple and lots of articles are available there already on the Internet.
But getting thumbnails from live URLs (Docx, Xls, and PDF) is not tough but tricky. We have to make some extra effort to complete the thumbnail generation from these URLs.
For this demonstration, I am going to use ASP.NET MVC project and we are going to create the thumbnails from Microsoft Office Documents and PDF as well. These documents can be Microsoft Word document or Microsoft Excel worksheets or even PDF docs.
To create a new project, just follow the following instructions.
- Open Visual Studio 2013/2015/2017
- Go to File >> New >> Project.
- From the "New Project" window, select “ASP.NET Web Application”.
- Browse the location to save the project and provide a suitable name and click "OK".
- From the next window, select MVC as a template and click "OK".
The project is ready for demonstration. To generate a thumbnail from the live URL, we will follow the given instructions.
- Download file in PDF format on temp location.
- Convert PDF file to a Bitmap image.
- Generate a thumbnail as Bitmap from the original Bitmap image.
- Save it to the preferred location.
- To show on View, convert it to Base64String and bind with the <img> tag.
Above, we have defined a couple of things which need to be completed to generate a thumbnail from the live URL and save it to any location or show it on the View.
It’s very easy to convert a PDF file into the image rather than converting any Microsoft Office file. So, here, we will first download these files at a temporary location and then convert these into PDF forms. Once the PDF is available, we can generate the image from that.
If you try to convert Microsoft Office files to PDF directly without Microsoft.Office.Interop, then it will be corrupted and the thumbnail will not be generated. So, basically, we cannot directly convert a live URL content to Bytes or Stream. To do that, we have to generate a PDF and perform the thumbnail task.
Here, we are going to generate a thumbnail from three different types of file - DOCX, XLSX, and PDF. To download and generate PDF from DOCX and XLSX, we will use the “Microsoft.Office.Interop”.
Following is the class name as “TypeConversion” which will help us to download and convert the file type from DOCX, XLSX to PDF at the temporary location from the live URL.
- using System;
- using Word = Microsoft.Office.Interop.Word;
- using Excel = Microsoft.Office.Interop.Excel;
- using System.IO;
- using System.Net;
- namespace GenerateThumbnails.Conversion
- {
- public class TypeConversion
- {
- private string _tempLocation = Path.GetPathRoot(Environment.SystemDirectory) + "WBTemp";
- Word.Application wordApp = null;
- Word.Documents wdDocuments = null;
- Word.Document wdDocument = null;
- Excel.Application excelApp = null;
- Excel.Workbooks xlBooks = null;
- Excel.Workbook xlBook = null;
- public bool WordToPdf(string _sourcePath, out string _outputTempFilePath)
- {
- wordApp = new Word.Application();
- wdDocuments = wordApp.Documents;
- try
- {
- //Read word document file
- wdDocument = wdDocuments.Open(_sourcePath);
- _outputTempFilePath = string.Empty;
- if (wdDocument != null)
- {
- _outputTempFilePath = GetTempTargetFilePath(_tempLocation);
- //Export word document file to pdf format
- wdDocument.ExportAsFixedFormat(_outputTempFilePath, Word.WdExportFormat.wdExportFormatPDF);
- return true;
- }
- }
- catch (Exception ex)
- {
- _outputTempFilePath = string.Empty;
- return false;
- }
- finally
- {
- // Cleanup
- GC.Collect();
- GC.WaitForPendingFinalizers();
- wdDocument.Close(false);
- NAR(wdDocument);
- NAR(wdDocuments);
- wordApp.Quit();
- NAR(wordApp);
- }
- return false;
- }
- public bool ExcelToPdf(string _sourcePath, out string _outputTempFilePath)
- {
- excelApp = new Excel.Application();
- try
- {
- //Read word document file
- xlBooks = excelApp.Workbooks;
- xlBook = xlBooks.Open(_sourcePath);
- _outputTempFilePath = string.Empty;
- if (xlBook != null)
- {
- _outputTempFilePath = GetTempTargetFilePath(_tempLocation);
- //Export word document file to pdf format
- xlBook.ExportAsFixedFormat(Excel.XlFixedFormatType.xlTypePDF, _outputTempFilePath);
- return true;
- }
- }
- catch (Exception ex)
- {
- _outputTempFilePath = string.Empty;
- return false;
- }
- finally
- {
- // Cleanup
- GC.Collect();
- GC.WaitForPendingFinalizers();
- xlBook.Close(false);
- NAR(xlBook);
- NAR(xlBooks);
- excelApp.Quit();
- NAR(excelApp);
- }
- return false;
- }
- public bool PdfURLToPdf(string _sourcePath, out string _outputTempFilePath)
- {
- using(var client = new WebClient())
- {
- _outputTempFilePath = GetTempTargetFilePath(_tempLocation);
- client.DownloadFile(_sourcePath, _outputTempFilePath);
- return true;
- }
- }
- private void NAR(object o)
- {
- try
- {
- while (System.Runtime.InteropServices.Marshal.ReleaseComObject(o) > 0) ;
- }
- catch { }
- finally
- {
- o = null;
- }
- }
- public static string GetTempTargetFilePath(string _targetTempPath)
- {
- string _tempFilePath = string.Empty;
- //Check temp directory exists or not
- if (!Directory.Exists(_targetTempPath))
- {
- //Create new temp directory
- Directory.CreateDirectory(_targetTempPath);
- }
- var _fileName = "temp.pdf";
- _tempFilePath = _targetTempPath + "/" + _fileName;
- if (File.Exists(_tempFilePath))
- {
- File.Delete(_tempFilePath);
- }
- return _tempFilePath;
- }
- }
- }
As you can see here, in the following class, we have three methods - WordToPdf, ExcelToPdf, and PdfURLtoPdf. These methods basically take two parameters as source path and output temp path. The source path is basically a live URL of the documents and the temp path is where a PDF is generated at a temporary location.
To create temp location, first, we are creating a temporary folder using the following code.
- private string _tempLocation = Path.GetPathRoot(Environment.SystemDirectory) + "WBTemp";
And before downloading the file on this location, we should check if the folder location exists or not. If the folder doesn’t exist, then it should be created.
- public static string GetTempTargetFilePath(string _targetTempPath)
- {
- string _tempFilePath = string.Empty;
- //Check temp directory exists or not
- if (!Directory.Exists(_targetTempPath))
- {
- //Create new temp directory
- Directory.CreateDirectory(_targetTempPath);
- }
- var _fileName = "temp.pdf";
- _tempFilePath = _targetTempPath + "/" + _fileName;
- if (File.Exists(_tempFilePath))
- {
- File.Delete(_tempFilePath);
- }
- return _tempFilePath;
- }
For Microsoft Word document, we should first open the document and then export it to PDF format as following.
- //Export word document file to pdf format
- wdDocument.ExportAsFixedFormat(_outputTempFilePath, Word.WdExportFormat.wdExportFormatPDF);
And, for Microsoft Excel, we should open the workbook of the Excel document and then export it to PDF format.
NOTE
Be careful when using Microsoft.Office.Interop COM components because it generates memory overhead. So, leaving the method, be sure you have disposed of non-required COM component instances as we do in the "Finally" block.
We should release all the memory objects until all the referenced COM components disposed of, as follows. This is a best practice and it’s recommended by Microsoft.
- private void NAR(object o)
- {
- try
- {
- while (System.Runtime.InteropServices.Marshal.ReleaseComObject(o) > 0) ;
- }
- catch { }
- finally
- {
- o = null;
- }
- }
NOTE
When using COM component, always follow the rule “don’t use double dots”.
NOTE
Using WebClient, we can download any type of file in the same format.
Above, we are done converting our live URLs of DOCX, XLSX, and PDF to a local file as PDF. Now, we can move to generate thumbnails from the temp PDF file.
Now, we have a PDF file saved locally at a temp location. To generate thumbnails from these PDF files, we have created one more class as “Thumbnails” which has a method “GetThumbnail” that takes the source path of temporarily saved PDF file and returns a Bitmap image as a thumbnail. Here, we are using the default width and height of the thumbnail image as 150px and 180px respectively. You can customize this code and pass the width and height as a parameter.

nilesh makadiyaPosted Jan 26, 2022, 6:23 AM
Hello Mukesh, I created the MVC application as you described above. When I created a thumbnail image for "Excel" and "pdf" file that time thumbnail image was created but when I open that file and display the only logo of pdf. not display the content of the first page of pdf and excel file. When I created a thumbnail image for the "word" file, that time I got an error. I attached a screenshot of the thumbnail image. Please check the snapshot (https://prnt.sc/26jfxh4). I attached the source code of the project. Check snapshot for Thumbnail.cs (https://prnt.sc/26jg1jf). Check snapshot of TypeConversion.cs (https://prnt.sc/26jg5y0). Check snapshot of ThumbnailController.cs (https://prnt.sc/26jg7o4). Please provide your feedback. Thanks Nilesh