分享

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

 quasiceo 2015-01-15

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
   5.00 (7 votes)
Using this tip, we easily create Thumbnail of “txt, doc, docx, xls, xlsx, ppt, pptx, rtf” files in ASP.NET MVC
Is your email address OK? You are signed up for our newsletters but your email address is either unconfirmed, or has not been reconfirmed in a long time. Please click here to have a confirmation email sent so we can confirm your email address and start sending you newsletters again. Alternatively, you can update your subscriptions.

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.

Collapse | Copy Code
   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:

Collapse | Copy Code
@{ 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.

Collapse | Copy Code
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.

Collapse | Copy Code
[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.

Collapse | Copy Code
   <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 .

Collapse | Copy Code
//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.

Collapse | Copy Code
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 .

Collapse | Copy Code
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.

Collapse | Copy Code
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).

Collapse | Copy Code
 //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.

Collapse | Copy Code
   //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.

Collapse | Copy Code
     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

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多