Click here to Skip to main content
12,302,376 members (23,795 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as

Stats

22.4K views
2.1K downloads
19 bookmarked
Posted

Upload Any File (“txt, doc, docx, xls, xlsx, ppt, pptx, rtf”) and Show the Thumbnail of First Page of Uploaded File in MVC

, 12 Mar 2014 CPOL
Rate this:
Please Sign up or sign in to vote.
Using this tip, we easily create Thumbnail of “txt, doc, docx, xls, xlsx, ppt, pptx, rtf” files in ASP.NET MVC

Introduction

In this tip, I've covered a brief introduction about creating Thumbnail of "txt, doc, docx, xls, xlsx, ppt, pptx, rtf" Files in ASP.NET MVC. This can be a good 'Beginner's Guide' to creating Thumbnail of txt, doc, docx, xls, xlsx, ppt, pptx, rtf.

Concept

This project converts "txt, doc, docx, xls, xlsx, ppt, pptx, rtf" extension files into PDF and then converts the created "pdf" into "jpg" extension. When a user uploads the file and clicks on Submit button, then first page of the uploaded file is converted into image file and shown on the browser without postback. For converting "doc, docx, xls, xlsx, ppt, pptx & rtf" format, Microsoft Office 2007 or later should be installed in your system. The uploaded file and the converted "pdf" file will be stored in Attachments Folder and the converted "jpg" file will be stored in Preview Folder of this project.

Using the Code

First of all, open Visual Studio 2010 or later and then select new project and click on ASP.NET MVC3 Application in Visual C#, name the project FileUploader. Then, add the following folders in your project.

  • Classes
  • UploadBooks
  • Attachments (inside the UploadBooks folder)
  • Preview (inside the Attachments folder)

Create a controller named HomeController and in this controller, create an ActionResult method named FileUploader.

namespace FileUploader.Controllers
 public class HomeController : Controller
 {
     //
     // GET: /Home/
     public ActionResult FileUploader()
     {
         return View();
     }

Now create a view, right click on the Fileuploader() and select Add View and then click OK. Create a view, right click on the Fileuploader() and select Add View and then click OK. Write the following code in this view:

@{ ViewBag.Title = "FileUploader";
    Layout = "~/Views/Shared/_Layout.cshtml";}
<h2>
    FileUploader</h2>
@using (Html.BeginForm())
{
    <div>
        <img src="" width="100" height="100" id="msg" />
    </div>
    <div>
        <p id="message">
        </p>
    </div>
    <input type="file" name="file" id="file" />
    <input type="button" class="clickClass" value="submit" id="submit" />
}

Create a model named FileUploaderModel.cs and add the following code in this. Also, add the class file "PdfConvert.cs" in Classes folder, add the "gsdll32.dll" i.e., Ghost Script in bin folder of your project and the reference file "TextPdf.dll". This code converts the "pdf" file into single "jpg" file. Download the required files from the link in the last.

namespace FileUploader.Models
{
    public class FileUploaderModel
    {
        //public string guid { get; set; }

        PdfToImage.PDFConvert PdfConverter = new PdfToImage.PDFConvert();
        //Convert the pdf into Single Image.
        public void ConvertSingleImage(string filename)
        {
            try
            {
                PdfConverter.RenderingThreads = 5;
                PdfConverter.TextAlphaBit = 4;
                PdfConverter.OutputToMultipleFile = false;
                PdfConverter.FirstPageToConvert = -1;
                PdfConverter.LastPageToConvert = -1;
                PdfConverter.FitPage = false;
                PdfConverter.JPEGQuality = 10;
                PdfConverter.OutputFormat = "jpeg";
                System.IO.FileInfo input = new FileInfo(filename);

                string[] str = input.Name.Split('.');
                string output = string.Format("{0}\\{1}{2}", input.Directory + "\\Preview", str[0].ToString(), ".jpg");

                while (System.IO.File.Exists(output))
                {
                    File.Delete(output);
                    output = string.Format("{0}\\{1}{2}", input.Directory + "\\Preview", str[0].ToString(), ".jpg");
                }
                PdfConverter.Convert(input.FullName, output);
            }
            catch (Exception ex)
            {
            }
            return;
        }
    }
}

For Converting the "text" file into "jpg" File

Add the following code in your controller to convert the "text" file that will come from the FileUploader view into "pdf" and then into "jpg" format and at last pass the converted "jpg" file path back to the FileUploader view.

[HttpPost]
        public ActionResult FileUploader(FileUploaderModel upload)
        {
            string guid = Guid.NewGuid().ToString();
            //upload.guid = guid;

            string msg = "Something went wrong, Your file was not uploaded.";

            HttpPostedFileBase file = Request.Files[0];
            string FinalPath = "";
            if (file != null && file.ContentLength > 0)
            {
                var fileName = Path.GetFileName(file.FileName);             // extract only the fielname
                var ext = Path.GetExtension(fileName.ToLower());            //extract only the extension of filename and then convert it into lower case.

                //var fileNameWithoutExt = Path.GetFileNameWithoutExtension(fileName);
                var path = Server.MapPath("~/UploadBooks/Attachments/" + guid + ext);
                file.SaveAs(path);

                if (ext == ".txt")                          //If the file is a "text" file.
                {
                    string filePath = "";
                    string filePath12 = "";
                    filePath = Server.MapPath("~/UploadBooks/Attachments/" + guid + ext);
                    filePath12 = Server.MapPath("~/UploadBooks/Attachments/");
                    FinalPath = Server.MapPath("~/UploadBooks/Attachments/" + guid + ".pdf");

                    TextPDF.PdfWriter pdfWriter = new TextPDF.PdfWriter(842.0f, 1190.0f, 10.0f, 10.0f);
                    pdfWriter.Getfilename(guid, filePath12);      //Convert the "txt" file into "pdf" file
                    if (filePath.Length > 0)
                        pdfWriter.Write(filePath);                              //Store the converted pdf file into Attachments folder

                    upload.ConvertSingleImage(FinalPath);               //Convert the pdf file into "jpg" file, the code is written in FileUploaderModel.cs
                    string str = "../../UploadBooks/Attachments/Preview/" + guid + ".jpg";
                    return Content(str);
                }

Now, add the following JavaScript to your view that will pass the file information to your controller and then return the path of the image that will built from your controller HTTPPOST FileUploader method.

   <script type="text/javascript">
    document.getElementById('submit').onclick = function () {
        var formdata = new FormData(); //FormData object
        var fileInput = document.getElementById('file');
        //Iterating through each files selected in fileInput
        for (i = 0; i < fileInput.files.length; i++) {
            //Appending each file to FormData object
            formdata.append(fileInput.files[i].name, fileInput.files[i]);
        }
        //Creating an XMLHttpRequest and sending
        var xhr = new XMLHttpRequest();
        xhr.open('POST', '/Home/FileUploader');
        xhr.send(formdata);
        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4 && xhr.status == 200) {
                var msg = "Your file was successfully uploaded";
                $("#msg").attr('src', xhr.responseText);
                $("#message").text(msg)
            }
        }
        return false;
    }
</script>

For Converting the "xls, xlsx" file into "jpg" file.

Add the following method code to your model to convert the "xls, xlsx" into "pdf" file and also add the reference file, i.e., Microsoft.Office.Interop.Excel.dll .

//Method to convert the Excel file into Pdf
        public bool ExportWorkbookToPdf(string workbookPath, string outputPath)
        {
            // If either required string is null or empty, stop and bail out
            if (string.IsNullOrEmpty(workbookPath) || string.IsNullOrEmpty(outputPath))
            {
                return false;
            }
            // Create COM Objects
            Microsoft.Office.Interop.Excel.Application excelApplication;
            Microsoft.Office.Interop.Excel.Workbook excelWorkbook;

            excelApplication = new Microsoft.Office.Interop.Excel.Application();        // Create new instance of Excel
            excelApplication.ScreenUpdating = false;                                    // Make the process invisible to the user
            excelApplication.DisplayAlerts = false;                                     // Make the process silent
            excelWorkbook = excelApplication.Workbooks.Open(workbookPath);          // Open the workbook that you wish to export to PDF
            // If the workbook failed to open, stop, clean up, and bail out
            if (excelWorkbook == null)
            {
                excelApplication.Quit();
                excelApplication = null;
                excelWorkbook = null;
                return false;
            }
            var exportSuccessful = true;
            try
            {
                // Call Excel's native export function (valid in Office 2007 and Office 2010, AFAIK)
                excelWorkbook.ExportAsFixedFormat(Microsoft.Office.Interop.Excel.XlFixedFormatType.xlTypePDF, outputPath);
            }
            catch (System.Exception ex)
            {
                // Mark the export as failed for the return value...
                exportSuccessful = false;
                // Do something with any exceptions here, if you wish...
                // MessageBox.Show...        
            }
            finally
            {
                // Close the workbook, quit the Excel, and clean up regardless of the results...
                excelWorkbook.Close();
                excelApplication.Quit();
                excelApplication = null;
                excelWorkbook = null;
            }
            return exportSuccessful;
        }

Add the following code in your controller to convert the "xls, xlsx" file that will come from the FileUploader view into "pdf" and then into "jpg" format and at last pass the converted "jpg" file back to the FileUploader view.

else if (ext == ".xls" || ext == ".xlsx")
                {
                    string inputFilePath = ""; string outputFilePath = "";
                    inputFilePath = Server.MapPath("~/UploadBooks/Attachments/" + guid + ext);
                    outputFilePath = Server.MapPath("~/UploadBooks/Attachments/" + guid + ".pdf");
                    FinalPath = Server.MapPath("~/UploadBooks/Attachments/" + guid + ".pdf");
                    upload.ExportWorkbookToPdf(inputFilePath, outputFilePath);      //Convert the Excel file into "pdf" file
                    upload.ConvertSingleImage(FinalPath);                //Convert the pdf file into "jpg" file, the code is written in FileUploaderModel.cs
                    string str = "../../UploadBooks/Attachments/Preview/" + guid + ".jpg";
                    return Content(str);
                }

For converting the "doc, docx, rtf" file into "jpg" file

Add the following method code to your model to convert the "doc, docx, rtf" into "pdf" file and also add the reference file i.e. Microsoft.Office.Interop.Word.dll .

public Microsoft.Office.Interop.Word.Document wordDocument { get; set; }
        public bool ExportWordFileToPdf(string workbookPath, string outputPath)
        {
            Microsoft.Office.Interop.Word.Application appWord = new Microsoft.Office.Interop.Word.Application();
            wordDocument = appWord.Documents.Open(workbookPath);
            var exportSuccessful = true;
            try
            {
                wordDocument.ExportAsFixedFormat(outputPath, WdExportFormat.wdExportFormatPDF);
            }
            catch (System.Exception ex)
            {
                exportSuccessful = false;
            }
            finally
            {
                ((_Document)wordDocument).Close();
                ((_Application)appWord).Quit();
                appWord = null;
                wordDocument = null;
            }
            return exportSuccessful;
        }

Add the following code in your controller to convert the "doc, docx, rtf" file that will come from the FileUploader view into "pdf" and then into "jpg" format and at last pass the converted "jpg" file back to the FileUploader view.

else if (ext == ".doc" || ext == ".docx" || ext == ".rtf")
                {
                    string inputFilePath = ""; string outputFilePath = ""; 
                    inputFilePath = Server.MapPath("~/UploadBooks/Attachments/" + guid +ext);
                    outputFilePath = Server.MapPath("~/UploadBooks/Attachments/" + guid + ".pdf");
                    FinalPath = Server.MapPath("~/UploadBooks/Attachments/" + guid + ".pdf"); 
                    upload.ExportWordFileToPdf(inputFilePath, outputFilePath);
                    upload.ConvertSingleImage(FinalPath);
                    string str = "../../UploadBooks/Attachments/Preview/" + guid + ".jpg";
                    return Content(str);
                }

For Converting the "ppt, pptx" file into "jpg" File

Add the following code in your controller to convert the "ppt, pptx" file that will come from the FileUploader view directly into "jpg" format and at last pass the converted "jpg" file back to the FileUploader view. For this, add the reference file Microsoft.Office.Interop.PowerPoint.dll and Office.dll(Microsoft Office 12.0 Object Library COM File).

//If the file is a "Power Point" file.
               else if (ext == ".ppt" || ext == ".pptx")
               {
                   string inputFilePath = "";

                   inputFilePath = Server.MapPath("~/UploadBooks/Attachments/" + guid + ext);
                   //outputFilePath = Server.MapPath("~/UploadBooks/Attachments/" + guid + ".pdf");
                   FinalPath = Server.MapPath("~/UploadBooks/Attachments/Preview" + guid + ".jpg");

                   string ExportLocation = Server.MapPath("~/UploadBooks/Attachments/Preview/");
                   Microsoft.Office.Interop.PowerPoint.Application ppApp = new Microsoft.Office.Interop.PowerPoint.Application();
                   //ppApp.Visible = MsoTriState.msoTrue;               //To open the ppt file.
                   //ppApp.WindowState = PpWindowState.ppWindowMinimized;         //To minimise the opened ppt file.
                   Microsoft.Office.Interop.PowerPoint.Presentations oPresSet = ppApp.Presentations;
                   Microsoft.Office.Interop.PowerPoint._Presentation oPres = oPresSet.Open(inputFilePath,
                               MsoTriState.msoFalse, MsoTriState.msoFalse,
                               MsoTriState.msoFalse);
                   ppApp.ShowWindowsInTaskbar = MsoTriState.msoFalse;  //Hiding the application; But it will be displayed always
                   try
                   {
                       Slides objSlides = oPres.Slides;    //Getting all the slides
                       for (int i = 1; i < 2; i++)    //If you want to convert all the slides into jpg then use "i < objSlides-1" in for loop.
                       {
                           string files = Path.Combine(ExportLocation, string.Format("{0}.{1}", guid, "jpg"));
                           oPres.Slides[i].Export(files, "jpg", 800, 600);
                       }
                   }
                   finally
                   {
                       ppApp.Quit();   //Closing the Powerpoint application. Sometimes it won't work too.
                   }

                   string str = "../../UploadBooks/Attachments/Preview/" + guid + ".jpg";
                   return Content(str);
               }

For Converting the "pdf" file into "jpg" file.

Add the following code in your controller to convert the "pdf" file that will come from the FileUploader view directly into "jpg" format and at last pass the converted "jpg" file back to the FileUploader view.

//If the file is a "PDF" file.
             else if (ext == ".pdf")
             {
                 FinalPath = Server.MapPath("~/UploadBooks/Attachments/" + guid + ext);

                 upload.ConvertSingleImage(FinalPath);           //Convert the pdf file into "jpg" file, the code is written in FileUploaderModel.cs
                 string str = "../../UploadBooks/Attachments/Preview/" + guid + ".jpg";
                 return Content(str);
             }

For Converting the "htm/html" file into "jpg" file

Add the following code in your controller to convert the "htm/html" file that will come from the FileUploader view into "pdf" and then into "jpg" format and at last pass the converted "jpg" file back to the FileUploader view. For this, add the class file Html2PDF.cs in classes folder and add the reference itextsharp.dll file.

else if (ext == ".htm" || ext == ".html")
           {
               string inputFilePath = ""; string outputFilePath = "";

               inputFilePath = Server.MapPath("~/UploadBooks/Attachments/" + guid+ext);
               outputFilePath = Server.MapPath("~/UploadBooks/Attachments/" + guid + ".pdf");
               FinalPath = Server.MapPath("~/UploadBooks/Attachments/" + guid + ".pdf");

               Html2PDF.Convert(inputFilePath, outputFilePath);    //Convert the html file into "pdf" file using Html2PDF.cs

               upload.ConvertSingleImage(FinalPath);   //Convert the pdf file into "jpg" file, the code is written in FileUploaderModel.cs
               string str = "../../UploadBooks/Attachments/Preview/" + guid + ".jpg";
               return Content(str);
           }

Points of Interest

The benefit of this project is when we upload any txt, pdf, ppt, html, etc. files, then it automatically creates an image thumbnail of the uploaded file and is displayed to the user without reloading the page or we can say without postback?

History

  • 13th March 2014

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Yogesh Kumar Tyagi
Software Developer Pure Diets India Limited
India India
No Biography provided

You may also be interested in...

Comments and Discussions

 
QuestionSource Code Pin
Member 1029200717-Mar-14 4:59
memberMember 1029200717-Mar-14 4:59 
AnswerRe: Source Code Pin
Yogesh Kumar Tyagi17-Mar-14 5:05
professionalYogesh Kumar Tyagi17-Mar-14 5:05 
GeneralRe: Source Code Pin
Member 1029200717-Mar-14 5:13
memberMember 1029200717-Mar-14 5:13 
GeneralNice article. keep it up Pin
Vinit_Jain12-Mar-14 22:53
memberVinit_Jain12-Mar-14 22:53 
GeneralRe: Nice article. keep it up Pin
Yogesh Kumar Tyagi12-Mar-14 23:04
professionalYogesh Kumar Tyagi12-Mar-14 23:04 
QuestionVery Good article... Pin
Member 1039340212-Mar-14 22:50
professionalMember 1039340212-Mar-14 22:50 
AnswerRe: Very Good article... Pin
Yogesh Kumar Tyagi12-Mar-14 23:03
professionalYogesh Kumar Tyagi12-Mar-14 23:03 
Questionnice dear Pin
rajveersingh12-Mar-14 18:10
memberrajveersingh12-Mar-14 18:10 
Questionwhere is gsdll32.dll" i.e. Ghost Script in bin folder of your project and the reference file "TextPdf.dll". Pin
Asutosha12-Mar-14 8:35
memberAsutosha12-Mar-14 8:35 
AnswerRe: where is gsdll32.dll" i.e. Ghost Script in bin folder of your project and the reference file "TextPdf.dll". Pin
Yogesh Kumar Tyagi12-Mar-14 18:22
professionalYogesh Kumar Tyagi12-Mar-14 18:22 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.160530.1 | Last Updated 12 Mar 2014
Article Copyright 2014 by Yogesh Kumar Tyagi
Everything else Copyright © CodeProject, 1999-2016
Layout: fixed | fluid