Concept
This project converts txt, doc, docx, xls, xlsx, ppt, pptx and rtf extension files into a PDF and then converts the created PDF into a JPEG format. When a user uploads the file and clicks on the Submit button then first page of the uploaded file is converted into the image file and shown on the browser without a postback. For converting from a doc, docx, xls, xlsx, ppt, pptx or rtf file, Microsoft Office 2007 or later should be installed in your system. The uploaded file and the converted PDF file will be stored in the Attachments Folder and the converted JPEG file will be stored in the Preview Folder of this project.
1. First of all open Visual Studio 2010 or later and then select "File" -> "New" -> "Project..." and click on ASP.NET MVC3 Web Application in Visual C#, name the project FileUploader. Then add the following folders to your project.
- Classes
- UploadBooks
Attachments (Inside the UploadBooks folder)
Preview (Inside the Attachments folder)
2. 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();
- }
- }
3. Now create a view, right-click on the Fileuploader() and select Add View and then click OK.
Write the following code in this view.
- @{<br /> 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" />
- }
4. Create a model named FileUploaderModel.cs and add the following code to this. Also add the class file “PdfConvert.cs” to the Classes folder, add the “gsdll32.dll”, in other words Ghost Script, in the bin folder of your project and the reference file TextPdf.dll. This code converts the PDF file into single a JPEG 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");
- }
- }
- }
- catch (Exception ex)
- {
- }
- return;
- }
- }
Converting the text file into JPEG file
1. Add the following code to your controller to convert the text file that will come from the FileUploader view into a PDF and then into the JPEG format and finally pass the converted JPEG file path back to the FileUploader view.
Converting the text file into JPEG file
2. Add the following code to your controller to convert the text file that will come from the FileUploader view into the PDF and then into the JPEG format and finally pass the converted JPEG 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);
- }
- }
- }
3. 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 be 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>
Converting the xls or xlsx file into a JPEG file
1. Add the following method code to your model to convert the xls or xlsx file into a PDF file and also add the reference file 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;
- }
2. Add the following code to your controller to convert the xls or xlsx file that will come from the FileUploader view into the PDF and then into JPEG format and finally pass the converted JPEG 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);
- }
3. Add the following method code to your model to convert the doc, docx or RTF file into a PDF file and also add the reference file 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;
- }
4. Add the following code to your controller to convert the doc, docx or RTF file that will come from the FileUploader view into a PDF and then into JPEG format and finally pass the converted JPEG 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);
- }
Converting the ppt or pptx file into JPEG file
1. Add the following code to your controller to convert the ppt or pptx file that will come from the FileUploader view directly into JPEG format and finally pass the converted JPEG file back to the FileUploader view. For this add the reference files 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);
- }
Converting the PDF file into JPEG file
1. Add the following code to your controller to convert the PDF file that will come from the FileUploader view directly into JPEG format and finally pass the converted JPEG 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);
- }
Converting the htm or html file into JPEG file
1. Add the following code to your controller to convert the htm or html file that will come from the FileUploader view into a PDF and then into JPEG format and finally pass the converted JPEG file back to the FileUploader view.
For this add the class file Html2PDF.cs to the 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);
- }
Now run your project and enjoy the code.