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
{
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
{
PdfToImage.PDFConvert PdfConverter = new PdfToImage.PDFConvert();
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();
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);
var ext = Path.GetExtension(fileName.ToLower());
var path = Server.MapPath("~/UploadBooks/Attachments/" + guid + ext);
file.SaveAs(path);
if (ext == ".txt")
{
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);
if (filePath.Length > 0)
pdfWriter.Write(filePath);
upload.ConvertSingleImage(FinalPath);
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();
var fileInput = document.getElementById('file');
for (i = 0; i < fileInput.files.length; i++) {
formdata.append(fileInput.files[i].name, fileInput.files[i]);
}
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 .
public bool ExportWorkbookToPdf(string workbookPath, string outputPath)
{
if (string.IsNullOrEmpty(workbookPath) || string.IsNullOrEmpty(outputPath))
{
return false;
}
Microsoft.Office.Interop.Excel.Application excelApplication;
Microsoft.Office.Interop.Excel.Workbook excelWorkbook;
excelApplication = new Microsoft.Office.Interop.Excel.Application();
excelApplication.ScreenUpdating = false;
excelApplication.DisplayAlerts = false;
excelWorkbook = excelApplication.Workbooks.Open(workbookPath);
if (excelWorkbook == null)
{
excelApplication.Quit();
excelApplication = null;
excelWorkbook = null;
return false;
}
var exportSuccessful = true;
try
{
excelWorkbook.ExportAsFixedFormat(Microsoft.Office.Interop.Excel.XlFixedFormatType.xlTypePDF, outputPath);
}
catch (System.Exception ex)
{
exportSuccessful = false;
}
finally
{
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);
upload.ConvertSingleImage(FinalPath);
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).
else if (ext == ".ppt" || ext == ".pptx")
{
string inputFilePath = "";
inputFilePath = Server.MapPath("~/UploadBooks/Attachments/" + guid + ext);
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();
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;
try
{
Slides objSlides = oPres.Slides;
for (int i = 1; i < 2; i++)
{
string files = Path.Combine(ExportLocation, string.Format("{0}.{1}", guid, "jpg"));
oPres.Slides[i].Export(files, "jpg", 800, 600);
}
}
finally
{
ppApp.Quit();
}
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.
else if (ext == ".pdf")
{
FinalPath = Server.MapPath("~/UploadBooks/Attachments/" + guid + ext);
upload.ConvertSingleImage(FinalPath);
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);
upload.ConvertSingleImage(FinalPath);
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