Exemple #1
0
        public static GetImageUrlsResponse GetImageUrls(GetImageUrlsParameters parameters)
        {
            if (string.IsNullOrEmpty(parameters.Path))
            {
                var empty = new GetImageUrlsResponse {
                    imageUrls = new string[0]
                };
                return(empty);
            }

            DocumentInfoOptions   documentInfoOptions   = new DocumentInfoOptions(parameters.Path);
            DocumentInfoContainer documentInfoContainer = _imageHandler.GetDocumentInfo(documentInfoOptions);

            int[] pageNumbers = new int[documentInfoContainer.Pages.Count];
            for (int i = 0; i < documentInfoContainer.Pages.Count; i++)
            {
                pageNumbers[i] = documentInfoContainer.Pages[i].Number;
            }

            var applicationHost = GetApplicationHost();

            string[] imageUrls = ImageUrlHelper.GetImageUrls(applicationHost, pageNumbers, parameters);

            var result = new GetImageUrlsResponse
            {
                imageUrls = imageUrls
            };

            return(result);
        }
Exemple #2
0
        public ActionResult Get(int?width, int?height, string file, string attachment, int page)
        {
            ViewerImageHandler handler             = Utils.CreateViewerImageHandler();
            ImageOptions       o                   = new ImageOptions();
            List <int>         pageNumberstoRender = new List <int>();

            pageNumberstoRender.Add(page);
            o.PageNumbersToRender = pageNumberstoRender;
            o.PageNumber          = page;
            o.CountPagesToRender  = 1;
            if (width.HasValue)
            {
                o.Width = Convert.ToInt32(width);
            }
            if (height.HasValue)
            {
                o.Height = Convert.ToInt32(height);
            }
            Stream stream = null;
            DocumentInfoContainer info = handler.GetDocumentInfo(file);

            // Iterate over the attachments collection
            foreach (AttachmentBase attachmentBase in info.Attachments.Where(x => x.Name == attachment))
            {
                List <PageImage> pages = handler.GetPages(attachmentBase);
                foreach (PageImage attachmentPage in pages.Where(x => x.PageNumber == page))
                {
                    stream = attachmentPage.Stream;
                }
                ;
            }
            return(new FileStreamResult(stream, "image/png"));
        }
        /// <summary>
        /// Get attached file's image representation
        /// </summary>
        /// <param name="DocumentName">Input document name</param>
        public static void GetEmailAttachmentImageRepresentation(String DocumentName)
        {
            try
            {
                //ExStart:GetEmailAttachmentImageRepresentation
                // Setup GroupDocs.Viewer config
                ViewerConfig config = Utilities.GetConfigurations();

                // Init viewer image handler
                ViewerImageHandler handler = new ViewerImageHandler(config);

                DocumentInfoContainer info = handler.GetDocumentInfo(DocumentName);

                // Iterate over the attachments collection
                foreach (AttachmentBase attachment in info.Attachments)
                {
                    Console.WriteLine("Attach name: {0}, size: {1}", attachment.Name, attachment.FileType);

                    // Get attachment document image representation
                    List <PageImage> pages = handler.GetPages(attachment);
                    foreach (PageImage page in pages)
                    {
                        Console.WriteLine("  Page: {0}, size: {1}", page.PageNumber, page.Stream.Length);
                    }
                }
                //ExEnd:GetEmailAttachmentImageRepresentation
            }
            catch (System.Exception exp)
            {
                Console.WriteLine(exp.Message);
            }
        }
        public static void InImageRepresentation()
        {
            // Setup GroupDocs.Viewer config
            ViewerConfig config = new ViewerConfig();
            config.StoragePath = @"C:\storage";

            // Create image handler
            ViewerImageHandler imageHandler = new ViewerImageHandler(config);
            string guid = "document.xlsx";

            // Set image options to show grid lines
            ImageOptions options = new ImageOptions();
            options.CellsOptions.ShowHiddenSheets = true;

            DocumentInfoContainer container = imageHandler.GetDocumentInfo(new DocumentInfoOptions(guid));

            foreach (PageData page in container.Pages)
                Console.WriteLine("Page number: {0}, Page Name: {1}, IsVisible: {2}", page.Number, page.Name, page.IsVisible);

            List<PageImage> pages = imageHandler.GetPages(guid, options);

            foreach (PageImage page in pages)
            {
                Console.WriteLine("Page number: {0}", page.PageNumber);

                // Page image stream
                Stream imageContent = page.Stream;
            }
        }
        public static void Run()
        {
            //Initialize viewer config
            ViewerConfig viewerConfig = new ViewerConfig();
            viewerConfig.StoragePath = "c:\\storage";

            //Initialize viewer handler
            ViewerImageHandler viewerImageHandler = new ViewerImageHandler(viewerConfig);

            //Set encoding
            Encoding encoding = Encoding.GetEncoding("shift-jis");

            //Set image options
            ImageOptions imageOptions = new ImageOptions();
            imageOptions.WordsOptions.Encoding = encoding;
            imageOptions.CellsOptions.Encoding = encoding;
            imageOptions.EmailOptions.Encoding = encoding;

            //Get words document pages with encoding
            string wordsDocumentGuid = "document.txt";
            List<PageImage> wordsDocumentPages = viewerImageHandler.GetPages(wordsDocumentGuid, imageOptions);

            //Get cells document pages with encoding
            string cellsDocumentGuid = "document.csv";
            List<PageImage> cellsDocumentPages = viewerImageHandler.GetPages(cellsDocumentGuid, imageOptions);

            //Get email document pages with encoding
            string emailDocumentGuid = "document.msg";
            List<PageImage> emailDocumentPages = viewerImageHandler.GetPages(emailDocumentGuid, imageOptions);

            //Get words document info with encoding
            DocumentInfoOptions wordsDocumentInfoOptions = new DocumentInfoOptions(wordsDocumentGuid);
            wordsDocumentInfoOptions.WordsDocumentInfoOptions.Encoding = encoding;
            DocumentInfoContainer wordsDocumentInfoContainer = viewerImageHandler.GetDocumentInfo(wordsDocumentInfoOptions);

            //Get cells document info with encoding
            DocumentInfoOptions cellsDocumentInfoOptions = new DocumentInfoOptions(cellsDocumentGuid);
            cellsDocumentInfoOptions.CellsDocumentInfoOptions.Encoding = encoding;
            DocumentInfoContainer cellsDocumentInfoContainer = viewerImageHandler.GetDocumentInfo(cellsDocumentInfoOptions);

            //Get email document info with encoding
            DocumentInfoOptions emailDocumentInfoOptions = new DocumentInfoOptions(emailDocumentGuid);
            emailDocumentInfoOptions.EmailDocumentInfoOptions.Encoding = encoding;
            DocumentInfoContainer emailDocumentInfoContainer = viewerImageHandler.GetDocumentInfo(emailDocumentInfoOptions);
        }
Exemple #6
0
        static void Main(string[] args)
        {
            SetLicense();

            string executionDirectory = Path.GetDirectoryName(
                System.Reflection.Assembly.GetExecutingAssembly().Location);

            ViewerConfig viewerConfig = new ViewerConfig();

            viewerConfig.StoragePath = executionDirectory;
            viewerConfig.UsePdf      = true;

            ViewerImageHandler viewerImageHandler = new ViewerImageHandler(viewerConfig);

            string guid = "Resources\\sample.pdf";

            DocumentInfoOptions documentInfoOptions =
                new DocumentInfoOptions(guid);
            DocumentInfoContainer documentInfoContainer =
                viewerImageHandler.GetDocumentInfo(documentInfoOptions);

            foreach (PageData pageData in documentInfoContainer.Pages)
            {
                Console.WriteLine("Page number: " + pageData.Number);

                for (int i = 0; i < pageData.Rows.Count; i++)
                {
                    RowData rowData = pageData.Rows[i];

                    Console.WriteLine("Row: " + (i + 1));
                    Console.WriteLine("Text: " + rowData.Text);
                    Console.WriteLine("Text width: " + rowData.LineWidth);
                    Console.WriteLine("Text height: " + rowData.LineHeight);
                    Console.WriteLine("Distance from left: " + rowData.LineLeft);
                    Console.WriteLine("Distance from top: " + rowData.LineTop);

                    string[] words = rowData.Text.Split(' ');

                    for (int j = 0; j < words.Length; j++)
                    {
                        int coordinateIndex = j == 0 ? 0 : j + 1;

                        Console.WriteLine(string.Empty);
                        Console.WriteLine("Word: '" + words[j] + "'");
                        Console.WriteLine("Word distance from left: " + rowData.TextCoordinates[coordinateIndex]);
                        Console.WriteLine("Word width: " + rowData.TextCoordinates[coordinateIndex + 1]);
                        Console.WriteLine(string.Empty);
                    }
                }

                Console.WriteLine(string.Empty);
            }

            Console.ReadKey();
        }
        public HttpResponseMessage Get(int?width, string file, string attachment, int page, string watermarkText, int?watermarkColor, WatermarkPosition?watermarkPosition, int?watermarkWidth, byte watermarkOpacity, int?height = null)
        {
            ViewerImageHandler handler             = Utils.CreateViewerImageHandler();
            ImageOptions       o                   = new ImageOptions();
            List <int>         pageNumberstoRender = new List <int>();

            pageNumberstoRender.Add(page);
            o.PageNumbersToRender = pageNumberstoRender;
            o.PageNumber          = page;
            o.CountPagesToRender  = 1;
            if (width.HasValue)
            {
                o.Width = Convert.ToInt32(width);
            }
            if (height.HasValue)
            {
                o.Height = Convert.ToInt32(height);
            }
            if (watermarkText != "")
            {
                o.Watermark = Utils.GetWatermark(watermarkText, watermarkColor, watermarkPosition, watermarkWidth, watermarkOpacity);
            }
            Stream stream = null;
            DocumentInfoContainer info = handler.GetDocumentInfo(file);

            // Iterate over the attachments collection
            foreach (AttachmentBase attachmentBase in info.Attachments.Where(x => x.Name == attachment))
            {
                List <PageImage> pages = handler.GetPages(attachmentBase, o);
                foreach (PageImage attachmentPage in pages.Where(x => x.PageNumber == page))
                {
                    stream = attachmentPage.Stream;
                }
                ;
            }
            var          result       = new HttpResponseMessage(HttpStatusCode.OK);
            Image        image        = Image.FromStream(stream);
            MemoryStream memoryStream = new MemoryStream();

            image.Save(memoryStream, ImageFormat.Jpeg);
            result.Content = new ByteArrayContent(memoryStream.ToArray());
            result.Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
            return(result);
        }
Exemple #8
0
        public ActionResult GetImageUrls(GetImageUrlsParameters parameters)
        {
            var guid = parameters.Path;

            // Get document info
            var documentInfoContainer = _imageHandler.GetDocumentInfo(guid);

            var pageNumbers     = documentInfoContainer.Pages.Select(_ => _.Number).ToArray();
            var applicationHost = GetApplicationHost();

            // Get image urls
            string[] imageUrls = ImageUrlHelper.GetImageUrls(applicationHost, pageNumbers, parameters);

            return(ToJsonResult(new GetImageUrlsResult(imageUrls)));
        }
        public HttpResponseMessage LoadDocumentDescription(PostedDataWrapper postedData)
        {
            string password     = "";
            string documentGuid = "";
            bool   htmlMode     = false;

            try
            {
                // get request body
                if (postedData != null)
                {
                    // get/set parameters
                    documentGuid = postedData.guid;
                    htmlMode     = postedData.htmlMode;
                    password     = postedData.password;
                    // check if documentGuid contains path or only file name
                    if (!Path.IsPathRooted(documentGuid))
                    {
                        documentGuid = quickViewConfig.getApplication().getFilesDirectory() + "/" + documentGuid;
                    }
                }
                DocumentInfoContainer documentInfoContainer = new DocumentInfoContainer();
                // get document info options
                DocumentInfoOptions documentInfoOptions = new DocumentInfoOptions(documentGuid);
                // set password for protected document
                documentInfoOptions.Password = password;
                // get document info container
                if (htmlMode)
                {
                    documentInfoContainer = viewerHtmlHandler.GetDocumentInfo(documentGuid, documentInfoOptions);
                }
                else
                {
                    documentInfoContainer = viewerImageHandler.GetDocumentInfo(documentGuid, documentInfoOptions);
                }
                // return document description
                return(Request.CreateResponse(HttpStatusCode.OK, documentInfoContainer.Pages));
            }
            catch (InvalidPasswordException ex)
            {
                // Set exception message
                ErrorMsgWrapper errorMsgWrapper = new ErrorMsgWrapper();
                if (String.IsNullOrEmpty(password))
                {
                    errorMsgWrapper.message = "Password Required";
                }
                else if (!String.IsNullOrEmpty(password))
                {
                    errorMsgWrapper.message = "Incorrect password";
                }
                else
                {
                    errorMsgWrapper.message = ex.Message;
                }
                errorMsgWrapper.exception = ex;
                return(Request.CreateResponse(HttpStatusCode.OK, errorMsgWrapper));
            }
            catch (Exception ex)
            {
                // set exception message
                ErrorMsgWrapper errorMsgWrapper = new ErrorMsgWrapper();
                errorMsgWrapper.message   = ex.Message;
                errorMsgWrapper.exception = ex;
                return(Request.CreateResponse(HttpStatusCode.OK, errorMsgWrapper));
            }
        }
Exemple #10
0
        public static GetImageUrlsResponse GetImageUrls(GetImageUrlsParameters parameters)
        {
            var docPath = parameters.Path;

            if (string.IsNullOrEmpty(parameters.Path))
            {
                var empty = new GetImageUrlsResponse {
                    imageUrls = new string[0]
                };
                return(empty);
            }

            DocumentInfoContainer documentInfoContainer = _imageHandler.GetDocumentInfo(parameters.Path);

            int[] pageNumbers = new int[documentInfoContainer.Pages.Count];
            for (int i = 0; i < documentInfoContainer.Pages.Count; i++)
            {
                pageNumbers[i] = documentInfoContainer.Pages[i].Number;
            }

            var applicationHost = GetApplicationHost();

            string[] imageUrls = ImageUrlHelper.GetImageUrls(applicationHost, pageNumbers, parameters);

            string[] attachmentUrls = new string[0];
            foreach (AttachmentBase attachment in documentInfoContainer.Attachments)
            {
                List <PageImage> pages = _imageHandler.GetPages(attachment);
                var attachmentInfo     = _imageHandler.GetDocumentInfo(_tempPath + "\\" + Path.GetFileNameWithoutExtension(docPath) + Path.GetExtension(docPath).Replace(".", "_") + "\\attachments\\" + attachment.Name);

                GetImageUrlsParameters attachmentResponse = parameters;
                attachmentResponse.Path = attachmentInfo.Guid;
                int[] attachmentPageNumbers = new int[pages.Count];
                for (int i = 0; i < pages.Count; i++)
                {
                    attachmentPageNumbers[i] = pages[i].PageNumber;
                }
                Array.Resize <string>(ref attachmentUrls, (attachmentUrls.Length + pages.Count));
                string[] attachmentImagesUrls = new string[pages.Count];
                attachmentImagesUrls = ImageUrlHelper.GetImageUrls(applicationHost, attachmentPageNumbers, attachmentResponse);
                attachmentImagesUrls.CopyTo(attachmentUrls, (attachmentUrls.Length - pages.Count));
            }
            if (documentInfoContainer.Attachments.Count > 0)
            {
                var imagesUrls = new string[attachmentUrls.Length + imageUrls.Length];
                imageUrls.CopyTo(imagesUrls, 0);
                attachmentUrls.CopyTo(imagesUrls, imageUrls.Length);

                var result = new GetImageUrlsResponse
                {
                    imageUrls = imagesUrls
                };
                return(result);
            }
            else
            {
                var result = new GetImageUrlsResponse
                {
                    imageUrls = imageUrls
                };
                return(result);
            }
        }
        public ActionResult Get(int?width, int?height, string file, int page, string watermarkText, int?watermarkColor, WatermarkPosition?watermarkPosition, int?watermarkWidth, byte watermarkOpacity, int?rotate, int?zoom)
        {
            if (Utils.IsValidUrl(file))
            {
                file = Utils.DownloadToStorage(file);
            }
            ViewerImageHandler handler = Utils.CreateViewerImageHandler();

            if (rotate.HasValue)
            {
                if (rotate.Value > 0)
                {
                    handler.ClearCache(file);
                }
            }

            ImageOptions options = new ImageOptions();

            options.PageNumbersToRender = new List <int>(new int[] { page });
            options.PageNumber          = page;
            options.CountPagesToRender  = 1;

            if (Path.GetExtension(file).ToLower().StartsWith(".xls"))
            {
                options.CellsOptions.OnePagePerSheet  = false;
                options.CellsOptions.CountRowsPerPage = 150;
            }

            if (watermarkText != "")
            {
                options.Watermark = Utils.GetWatermark(watermarkText, watermarkColor, watermarkPosition, watermarkWidth, watermarkOpacity);
            }

            if (width.HasValue)
            {
                int w = Convert.ToInt32(width);
                if (zoom.HasValue)
                {
                    w = w + zoom.Value;
                }
                options.Width = w;
            }

            if (height.HasValue)
            {
                if (zoom.HasValue)
                {
                    options.Height = options.Height + zoom.Value;
                }
            }

            if (rotate.HasValue)
            {
                if (rotate.Value > 0)
                {
                    if (width.HasValue)
                    {
                        int side = options.Width;

                        DocumentInfoContainer documentInfoContainer = handler.GetDocumentInfo(file);
                        int pageAngle = documentInfoContainer.Pages[page - 1].Angle;
                        if (pageAngle == 90 || pageAngle == 270)
                        {
                            options.Height = side;
                        }
                        else
                        {
                            options.Width = side;
                        }
                    }

                    options.Transformations = Transformation.Rotate;
                    handler.RotatePage(file, new RotatePageOptions(page, rotate.Value));
                }
            }
            else
            {
                options.Transformations = Transformation.None;
                handler.RotatePage(file, new RotatePageOptions(page, 0));
            }

            using (new InterProcessLock(file))
            {
                List <PageImage> list      = handler.GetPages(file, options);
                PageImage        pageImage = list.Single(_ => _.PageNumber == page);

                return(File(pageImage.Stream, "image/png"));
            }
        }
        public ActionResult ViewDocument(ViewDocumentParameters request)
        {
            var fileName = Path.GetFileName(request.Path);

            var result = new ViewDocumentResponse
            {
                pageCss        = new string[] {},
                lic            = true,
                pdfDownloadUrl = GetPdfDownloadUrl(request),
                pdfPrintUrl    = GetPdfPrintUrl(request),
                url            = GetFileUrl(request),
                path           = request.Path,
                name           = fileName
            };

            var docInfo = _imageHandler.GetDocumentInfo(new DocumentInfoOptions(request.Path));

            result.documentDescription = new FileDataJsonSerializer(docInfo.Pages, new FileDataOptions()).Serialize(true);
            result.docType             = docInfo.DocumentType;
            result.fileType            = docInfo.FileType;

            var imageOptions = new ImageOptions {
                Watermark = GetWatermark(request)
            };
            var imagePages = _imageHandler.GetPages(request.Path, imageOptions);

            // Provide images urls
            var urls = new List <string>();

            // If no cache - save images to temp folder
            //var tempFolderPath = Path.Combine(Microsoft.SqlServer.Server.MapPath("~"), "Content", "TempStorage");
            var tempFolderPath = Path.Combine(HttpContext.Server.MapPath("~"), "Content", "TempStorage");

            foreach (var pageImage in imagePages)
            {
                var docFoldePath = Path.Combine(tempFolderPath, request.Path);

                if (!Directory.Exists(docFoldePath))
                {
                    Directory.CreateDirectory(docFoldePath);
                }

                var pageImageName = string.Format("{0}\\{1}.png", docFoldePath, pageImage.PageNumber);

                using (var stream = pageImage.Stream)
                    using (FileStream fileStream = new FileStream(pageImageName, FileMode.Create))
                    {
                        stream.Seek(0, SeekOrigin.Begin);
                        stream.CopyTo(fileStream);
                    }

                var baseUrl = Request.Url.Scheme + "://" + Request.Url.Authority + Request.ApplicationPath.TrimEnd('/') +
                              "/";
                urls.Add(string.Format("{0}Content/TempStorage/{1}/{2}.png", baseUrl, request.Path, pageImage.PageNumber));
            }

            result.imageUrls = urls.ToArray();

            var serializer = new JavaScriptSerializer {
                MaxJsonLength = int.MaxValue
            };

            var serializedData = serializer.Serialize(result);

            return(Content(serializedData, "application/json"));
        }
        public HttpResponseMessage Get(int?width, string file, int page, string watermarkText, int?watermarkColor, WatermarkPosition?watermarkPosition, int?watermarkWidth, byte watermarkOpacity, int?rotate, int?zoom, int?height = null)
        {
            if (Utils.IsValidUrl(file))
            {
                file = Utils.DownloadToStorage(file);
            }
            ViewerImageHandler handler = Utils.CreateViewerImageHandler();

            if (rotate.HasValue)
            {
                if (rotate.Value > 0)
                {
                    handler.ClearCache(file);
                }
            }

            ImageOptions options = new ImageOptions();

            options.PageNumbersToRender = new List <int>(new int[] { page });
            options.PageNumber          = page;
            options.CountPagesToRender  = 1;

            if (Path.GetExtension(file).ToLower().StartsWith(".xls"))
            {
                options.CellsOptions.OnePagePerSheet  = false;
                options.CellsOptions.CountRowsPerPage = 150;
            }

            if (watermarkText != "")
            {
                options.Watermark = Utils.GetWatermark(watermarkText, watermarkColor, watermarkPosition, watermarkWidth, watermarkOpacity);
            }

            if (width.HasValue)
            {
                int w = Convert.ToInt32(width);
                if (zoom.HasValue)
                {
                    w = w + zoom.Value;
                }
                options.Width = w;
            }

            if (height.HasValue)
            {
                if (zoom.HasValue)
                {
                    options.Height = options.Height + zoom.Value;
                }
            }

            if (rotate.HasValue)
            {
                if (rotate.Value > 0)
                {
                    if (width.HasValue)
                    {
                        int side = options.Width;

                        DocumentInfoContainer documentInfoContainer = handler.GetDocumentInfo(file);
                        int pageAngle = documentInfoContainer.Pages[page - 1].Angle;
                        if (pageAngle == 90 || pageAngle == 270)
                        {
                            options.Height = side;
                        }
                        else
                        {
                            options.Width = side;
                        }
                    }

                    options.Transformations = Transformation.Rotate;
                    handler.RotatePage(file, new RotatePageOptions(page, rotate.Value));
                }
            }
            else
            {
                options.Transformations = Transformation.None;
                handler.RotatePage(file, new RotatePageOptions(page, 0));
            }

            List <PageImage> list      = handler.GetPages(file, options);
            PageImage        pageImage = list.Single(_ => _.PageNumber == page);

            Stream       stream       = pageImage.Stream;
            var          result       = new HttpResponseMessage(HttpStatusCode.OK);
            Image        image        = Image.FromStream(stream);
            MemoryStream memoryStream = new MemoryStream();

            image.Save(memoryStream, ImageFormat.Jpeg);
            result.Content = new ByteArrayContent(memoryStream.ToArray());
            result.Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
            return(result);
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            _config = new ViewerConfig
            {
                StoragePath = _storagePath,
                UseCache    = true
            };

            ViewerImageHandler             imageHandler = (ViewerImageHandler)HttpContext.Current.Session["imageHandler"];
            ViewerHtmlHandler              htmlHandler  = (ViewerHtmlHandler)HttpContext.Current.Session["htmlHandler"];
            GetDocumentPageImageParameters parameters   = new GetDocumentPageImageParameters();


            foreach (String key in Request.QueryString.AllKeys)
            {
                if (!string.IsNullOrEmpty(Request.QueryString[key]))
                {
                    var propertyInfo = parameters.GetType().GetProperty(key, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);
                    propertyInfo.SetValue(parameters, ChangeType(Request.QueryString[key], propertyInfo.PropertyType), null);
                }
            }

            string guid        = parameters.Path;
            int    pageIndex   = parameters.PageIndex;
            int    pageNumber  = pageIndex + 1;
            var    displayName = parameters.Path;

            /*
             * //NOTE: This feature is supported starting from version 3.2.0
             * CultureInfo cultureInfo = string.IsNullOrEmpty(parameters.Locale)
             *  ? new CultureInfo("en-Us")
             *  : new CultureInfo(parameters.Locale);
             *
             * ViewerImageHandler viewerImageHandler = new ViewerImageHandler(viewerConfig, cultureInfo);
             */

            var imageOptions = new ImageOptions
            {
                //ConvertImageFileType = _convertImageFileType,
                ConvertImageFileType = ConvertImageFileType.JPG,
                JpegQuality          = 100,
                Watermark            = Utils.GetWatermark(parameters.WatermarkText, parameters.WatermarkColor,
                                                          parameters.WatermarkPosition, parameters.WatermarkWidth),
                Transformations = parameters.Rotate ? Transformation.Rotate : Transformation.None
            };

            if (parameters.Rotate && parameters.Width.HasValue)
            {
                DocumentInfoContainer documentInfoContainer = imageHandler.GetDocumentInfo(guid);

                int side = parameters.Width.Value;

                int pageAngle = documentInfoContainer.Pages[pageIndex].Angle;
                if (pageAngle == 90 || pageAngle == 270)
                {
                    imageOptions.Height = side;
                }
                else
                {
                    imageOptions.Width = side;
                }
            }

            /*
             * //NOTE: This feature is supported starting from version 3.2.0
             * if (parameters.Quality.HasValue)
             *  imageOptions.JpegQuality = parameters.Quality.Value;
             */

            using (new InterProcessLock(guid))
            {
                List <PageImage> pageImages = imageHandler.GetPages(guid, imageOptions);
                PageImage        pageImage  = pageImages.Single(_ => _.PageNumber == pageNumber);
                var fileStream = pageImage.Stream;
                // return File(pageImage.Stream, GetContentType(_convertImageFileType));
                byte[] Bytes = new byte[fileStream.Length];
                fileStream.Read(Bytes, 0, Bytes.Length);
                string contentDispositionString = "attachment; filename=\"" + displayName + "\"";


                contentDispositionString = new ContentDisposition {
                    FileName = displayName, Inline = true
                }.ToString();



                HttpContext.Current.Response.ContentType = "image/jpeg";

                HttpContext.Current.Response.AddHeader("Content-Disposition", contentDispositionString);
                HttpContext.Current.Response.AddHeader("Content-Length", fileStream.Length.ToString());
                try
                {
                    HttpContext.Current.Response.OutputStream.Write(Bytes, 0, Bytes.Length);
                    HttpContext.Current.Response.Flush();
                    HttpContext.Current.Response.End();
                }
                catch (HttpException x)
                {
                    // Ignore it.
                }
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            var file       = GetValueFromQueryString("file");
            var attachment = GetValueFromQueryString("attachment");
            int page       = Convert.ToInt32(GetValueFromQueryString("page"));
            int?width      = Convert.ToInt32(GetValueFromQueryString("width"));
            int?height     = Convert.ToInt32(GetValueFromQueryString("width"));

            if (Utils.IsValidUrl(file))
            {
                file = Utils.DownloadToStorage(file);
            }

            string            watermarkText     = GetValueFromQueryString("watermarkText");
            int?              watermarkColor    = Convert.ToInt32(GetValueFromQueryString("watermarkColor"));
            WatermarkPosition watermarkPosition = (WatermarkPosition)Enum.Parse(typeof(WatermarkPosition), GetValueFromQueryString("watermarkPosition"), true);
            string            widthFromQuery    = GetValueFromQueryString("watermarkWidth");
            int?              watermarkWidth    = GetValueFromQueryString("watermarkWidth") == "null" ? null : (int?)Convert.ToInt32(GetValueFromQueryString("watermarkWidth"));
            byte              watermarkOpacity  = Convert.ToByte(GetValueFromQueryString("watermarkOpacity"));


            ViewerImageHandler handler             = Utils.CreateViewerImageHandler();
            ImageOptions       o                   = new ImageOptions();
            List <int>         pageNumberstoRender = new List <int>();

            pageNumberstoRender.Add(page);
            o.PageNumbersToRender = pageNumberstoRender;
            o.PageNumber          = page;
            o.CountPagesToRender  = 1;
            if (width.HasValue)
            {
                o.Width = Convert.ToInt32(width);
            }
            if (height.HasValue)
            {
                o.Height = Convert.ToInt32(height);
            }
            if (watermarkText != "")
            {
                o.Watermark = Utils.GetWatermark(watermarkText, watermarkColor, watermarkPosition, watermarkWidth, watermarkOpacity);
            }

            Stream stream = null;
            DocumentInfoContainer info = handler.GetDocumentInfo(file);

            // Iterate over the attachments collection
            foreach (AttachmentBase attachmentBase in info.Attachments.Where(x => x.Name == attachment))
            {
                List <PageImage> pages = handler.GetPages(attachmentBase);
                foreach (PageImage attachmentPage in pages.Where(x => x.PageNumber == page))
                {
                    stream = attachmentPage.Stream;
                }
                ;
            }
            var result = new HttpResponseMessage(HttpStatusCode.OK);

            System.Drawing.Image image        = System.Drawing.Image.FromStream(stream);
            MemoryStream         memoryStream = new MemoryStream();

            image.Save(memoryStream, ImageFormat.Jpeg);

            HttpContext.Current.Response.ContentType = "image/jpeg";
            memoryStream.WriteTo(HttpContext.Current.Response.OutputStream);
            HttpContext.Current.Response.Flush();
            HttpContext.Current.Response.End();
        }