public ActionResult cropImage(string imagePath, string pdfPath, int leftX, int leftY, int width, int height, int serviceId, string title, string allImagePaths)
        {
            // TODO: Pathing!
            string uniqueName  = "";
            string LogFilePath = ConfigurationManager.AppSettings["logFilePath"];
            var    sr          = new StreamWriter(LogFilePath + "pdfconvert.log");

            sr.AutoFlush = true;
            bool success = true;

            try
            {
                sr.WriteLine("Orignal Image Path: " + imagePath);
                int    lastSlash       = imagePath.LastIndexOf('/');
                string serverImagePath = ConfigurationManager.AppSettings["pdfUploadSpot"] + @"\tempPics\" + imagePath.Substring(lastSlash + 1);
                sr.WriteLine("SeverImagePath = " + serverImagePath);
                sr.WriteLine("leftx = " + leftX.ToString());
                sr.WriteLine("lefty = " + leftY.ToString());
                sr.WriteLine("width = " + width.ToString());
                sr.WriteLine("height = " + height.ToString());
                sr.WriteLine("Before src");
                Bitmap src = Image.FromFile(serverImagePath) as Bitmap;
                if (leftX == 0 && leftY == 0 && width == 0 && height == 0)
                {
                    //Do nothing but set width and height
                    width  = src.Width;
                    height = src.Height;
                }

                Rectangle cropRect = new Rectangle(leftX, leftY, width, height);


                sr.WriteLine("after src");
                Bitmap target = new Bitmap(cropRect.Width, cropRect.Height);
                //Bitmap target = new Bitmap(10, 20);

                sr.WriteLine("Before using graphics");

                using (Graphics g = Graphics.FromImage(target))
                {
                    sr.WriteLine("Before draw");

                    g.DrawImage(src, new Rectangle(0, 0, target.Width, target.Height), cropRect, GraphicsUnit.Pixel);
                }
                sr.WriteLine("Before save");

                uniqueName = UniqueNames.GetTimestamp(DateTime.Now) + ".jpg";
                string savePath = ConfigurationManager.AppSettings["pdfArchive"] + @"\Thumbnails\" + uniqueName;
                sr.WriteLine("Save Path: " + savePath);

                target.Save(savePath);
                src.Dispose();

                target.Dispose();

                CloudStorageAccount storageAccount = CloudStorageAccount.Parse(ConfigurationManager.AppSettings["StorageConnectionString"]);
                CloudBlobClient     blobClient     = storageAccount.CreateCloudBlobClient();
                CloudBlobContainer  container      = blobClient.GetContainerReference("pdf-thumbnails");
                CloudBlockBlob      blockBlob      = container.GetBlockBlobReference(uniqueName);
                blockBlob.UploadFromFile(savePath);
                blockBlob.Properties.ContentType = "image/jpeg";
                blockBlob.SetProperties();
            }
            catch (Exception e)
            {
                sr.WriteLine("Error message= " + e.Message);
                //sr.WriteLine("INNER message = " + e.InnerException.Message);
                sr.WriteLine("Stacktrace = " + e.StackTrace);
                success = false;
            }
            sr.Close();
            Service service = db.Services.Find(serviceId);
            PDF     dbPdf   = new PDF();

            if (service.PDF == null)
            {
                dbPdf.ServiceId       = serviceId;
                dbPdf.ThumbnailPath   = uniqueName;
                dbPdf.PDFPath         = pdfPath;
                dbPdf.TitleText       = title;
                db.Entry(dbPdf).State = EntityState.Added;
                db.SaveChanges();
            }
            else
            {
                service.PDF.ThumbnailPath   = uniqueName;
                service.PDF.PDFPath         = pdfPath;
                service.PDF.TitleText       = title;
                db.Entry(service.PDF).State = EntityState.Modified;
                db.SaveChanges();
            }
            string safePdf        = pdfPath.Replace(" ", "%20");
            string safeUniqueName = uniqueName.Replace('\\', '/');
            string outwardPdfPath = ConfigurationManager.AppSettings["portalPath"] + @"/pdfs/displaypdf/" + serviceId;
            var    userId         = User.Identity.GetUserId();

            if (userId != null)
            {
                FuneralHome fh = db.FuneralHomes.Where(x => x.UserId == userId).FirstOrDefault();
                if (fh != null)
                {
                    if (fh.Setting.SEOFriendlyPDF == false)
                    {
                        outwardPdfPath = ConfigurationManager.AppSettings["portalPath"] + @"/pdfs/servepdf/" + serviceId;
                    }
                }
            }
            string outwardThumbnail = ConfigurationManager.AppSettings["portalPath"] + @"/pdfs/displaythumbnail/" + serviceId;

            allImagePaths = allImagePaths.Substring(2);
            allImagePaths = allImagePaths.Remove(allImagePaths.Length - 2);
            allImagePaths = allImagePaths.Replace("]", "");
            allImagePaths = allImagePaths.Replace(@"\", "");
            allImagePaths = allImagePaths.Replace("\"", "");
            string[] allPaths = allImagePaths.Split(',');



            if (allPaths != null)
            {
                foreach (string imageToBeDeleted in allPaths)
                {
                    int    slashPos        = imagePath.LastIndexOf('/');
                    string serverImagePath = ConfigurationManager.AppSettings["rootPath"] + @"\UploadedPDFs\tempPics\" + imageToBeDeleted.Substring(slashPos + 1);
                    if (System.IO.File.Exists(serverImagePath))
                    {
                        System.IO.File.Delete(serverImagePath);
                    }
                }
            }
            //Save to DB

            return(Json(new { outwardPdfPath, outwardThumbnail, success }));
        }
        public async Task <ActionResult> PDFtoImage(string fileurl, int maxWidth)
        {
            string websitePath    = ConfigurationManager.AppSettings["portalPath"];
            string LogFilePath    = ConfigurationManager.AppSettings["logFilePath"];
            var    sr             = new StreamWriter(LogFilePath + "pdfToImage.log");
            string timestampedPDF = "error.pdf";

            sr.AutoFlush = true;
            string        outwardPath    = "";
            string        currentPDFPath = "";
            List <string> PathedArray    = new List <string>();

            try
            {
                sr.WriteLine("fileurl = " + fileurl);

                sr.WriteLine("beforeInput");
                string inputPath = ConfigurationManager.AppSettings["pdfUploadSpot"] + @"\" + fileurl;


                sr.WriteLine("beforeoutput");
                string filename   = "tempImage" + UniqueNames.GetTimestamp(DateTime.Now) + ".jpg";
                string outputPath = ConfigurationManager.AppSettings["pdfUploadSpot"] + @"\tempPics\" + filename;

                sr.WriteLine("inputpath = " + inputPath);
                sr.WriteLine("outputpath = " + outputPath);

                List <string> outwardPaths = new List <string>();
                for (int i = 1; i < 4; i++)
                {
                    outputPath = outputPath.Replace(".jpg", i + ".jpg");
                    GhostscriptWrapper.GeneratePageThumb(inputPath, outputPath, i, 120, 120);
                    if (!System.IO.File.Exists(outputPath))
                    {
                        break;
                    }

                    outwardPaths.Add(outputPath);
                }

                foreach (var path in outwardPaths)
                {
                    ScaleImage(path, maxWidth, 3000);

                    string newPath = path.Substring(path.LastIndexOf('\\') + 1);
                    newPath = ConfigurationManager.AppSettings["portalPath"] + @"/pdfs/gettemppic/" + newPath;
                    PathedArray.Add(newPath);
                }

                currentPDFPath = inputPath;
                timestampedPDF = DateTime.Now.GetTimestamp() + fileurl;
                string archivePath = ConfigurationManager.AppSettings["pdfArchive"] + @"\PDFs\" + timestampedPDF;

                //PDFParser parser = new PDFParser();
                //string result = parser.ExtractText(currentPDFPath);
                //moving file
                sr.WriteLine("Current PDF Path:" + currentPDFPath);
                sr.WriteLine("Archive PDF Path:" + archivePath);
                //System.IO.File.Move(currentPDFPath, archivePath);
            }
            catch (Exception e)
            {
                sr.WriteLine("message = " + e.Message);
                sr.WriteLine("stacktrace = " + e.StackTrace);
            }
            sr.Close();

            Task.Factory.StartNew(() =>
            {
                UploadPDFToAzure(currentPDFPath, timestampedPDF);
            });

            return(Json(new { PathedArray, timestampedPDF }));
        }