public void SaveDescription(DocumentInfoContainer description)
        {
            if(description == null)
                return;
            string descriptionFolder = Path.Combine(repoPath, description.Name, description.DocumentType);

            lock (_syncRoot)
            {
                if(!Directory.Exists(descriptionFolder))
                    Directory.CreateDirectory(descriptionFolder);
                try
                {
                    using(var stream = File.OpenWrite(Path.Combine(descriptionFolder, "fd.json")))
                    using(var writer = new StreamWriter(stream))
                    using(JsonWriter jwriter = new JsonTextWriter(writer) { Formatting = Formatting.Indented })
                    {
                        JsonSerializer serializer = new JsonSerializer();
                        serializer.Serialize(jwriter, description);
                    }
                }
                catch(Exception e)
                {
                    throw new Exception("Failed to serialize an object to file: '{0}'.", e);
                }
            }
        }
示例#2
0
        public ActionResult Index(string file, string attachment, int page, string resource)
        {
            var attachmentPath                        = "cache\\" + Path.GetFileNameWithoutExtension(file) + Path.GetExtension(file).Replace(".", "_") + "\\attachments\\" + attachment;
            ViewerHtmlHandler     handler             = Utils.CreateViewerHtmlHandler();
            DocumentInfoContainer info                = handler.GetDocumentInfo(file);
            List <int>            pageNumberstoRender = new List <int>();

            pageNumberstoRender.Add(page);
            HtmlOptions o          = new HtmlOptions();
            int         pageNumber = page;

            o.PageNumbersToRender = pageNumberstoRender;
            o.PageNumber          = page;
            o.CountPagesToRender  = 1;
            List <PageHtml>     pages         = handler.GetPages(attachmentPath, o);
            List <HtmlResource> htmlResources = pages.Where(x => x.PageNumber == page).Select(x => x.HtmlResources).FirstOrDefault();
            var    fileResource = htmlResources.Where(x => x.ResourceName == resource).FirstOrDefault();
            string type         = "";

            if (fileResource != null)
            {
                switch (fileResource.ResourceType)
                {
                case HtmlResourceType.Font:
                    type = "application/font-woff";
                    break;

                case HtmlResourceType.Style:

                    type = "text/css";
                    break;

                case HtmlResourceType.Image:
                    type = "image/jpeg";
                    break;

                case HtmlResourceType.Graphics:
                    type = "image/svg+xml";
                    break;
                }
                Stream stream = handler.GetResource(attachmentPath, fileResource);
                return(new FileStreamResult(stream, type));
            }
            return(null);
        }
        public HttpResponseMessage Get(string file, string attachment, int page, string resource)
        {
            var attachmentPath                        = "cache\\" + Path.GetFileNameWithoutExtension(file) + Path.GetExtension(file).Replace(".", "_") + "\\attachments\\" + attachment;
            ViewerHtmlHandler     handler             = Utils.CreateViewerHtmlHandler();
            DocumentInfoContainer info                = handler.GetDocumentInfo(file);
            List <int>            pageNumberstoRender = new List <int>();

            pageNumberstoRender.Add(page);
            HtmlOptions o          = new HtmlOptions();
            int         pageNumber = page;

            o.PageNumbersToRender = pageNumberstoRender;
            o.PageNumber          = page;
            o.CountPagesToRender  = 1;
            List <PageHtml>     pages         = handler.GetPages(attachmentPath, o);
            List <HtmlResource> htmlResources = pages.Where(x => x.PageNumber == page).Select(x => x.HtmlResources).FirstOrDefault();
            var    fileResource = htmlResources.Where(x => x.ResourceName == resource).FirstOrDefault();
            string type         = "";

            if (fileResource != null)
            {
                switch ((int)fileResource.ResourceType)
                {
                case 2:
                    type = "application/font-woff";
                    break;

                case 3:

                    type = "text/css";
                    break;

                case 1:
                    type = "image/jpeg";
                    break;
                }
                Stream stream = handler.GetResource(attachmentPath, fileResource);
                var    result = new HttpResponseMessage(HttpStatusCode.OK);
                result.Content = new StreamContent(stream);
                result.Content.Headers.ContentType = new MediaTypeHeaderValue(type);
                return(result);
            }
            return(null);
        }
        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);
        }
示例#5
0
        public ActionResult RotatePage(RotatePageParameters parameters)
        {
            string guid      = parameters.Path;
            int    pageIndex = parameters.PageNumber;

            DocumentInfoContainer documentInfoContainer = _imageHandler.GetDocumentInfo(guid);
            int pageNumber = documentInfoContainer.Pages[pageIndex].Number;

            RotatePageOptions rotatePageOptions = new RotatePageOptions(pageNumber, parameters.RotationAmount);

            _imageHandler.RotatePage(guid, rotatePageOptions);

            documentInfoContainer = _imageHandler.GetDocumentInfo(guid);
            var resultAngle = documentInfoContainer.Pages[pageIndex].Angle;

            return(ToJsonResult(new RotatePageResponse {
                resultAngle = resultAngle
            }));
        }
示例#6
0
        public static RotatePageResponse RotatePage(RotatePageParameters parameters)
        {
            string guid      = parameters.Path;
            int    pageIndex = parameters.PageNumber;

            DocumentInfoOptions   documentInfoOptions   = new DocumentInfoOptions(guid);
            DocumentInfoContainer documentInfoContainer = _imageHandler.GetDocumentInfo(documentInfoOptions);
            int pageNumber = documentInfoContainer.Pages[pageIndex].Number;

            RotatePageOptions   rotatePageOptions   = new RotatePageOptions(guid, pageNumber, parameters.RotationAmount);
            RotatePageContainer rotatePageContainer = _imageHandler.RotatePage(rotatePageOptions);

            RotatePageResponse response = new RotatePageResponse
            {
                resultAngle = rotatePageContainer.CurrentRotationAngle
            };

            return(response);
        }
示例#7
0
        private static void ViewDocumentAsImage(ViewDocumentParameters request, ViewDocumentResponse result, string fileName)
        {
            var docInfo = _imageHandler.GetDocumentInfo(new DocumentInfoOptions(request.Path));

            var maxWidth  = 0;
            var maxHeight = 0;

            foreach (var pageData in docInfo.Pages)
            {
                if (pageData.Height > maxHeight)
                {
                    maxHeight = pageData.Height;
                    maxWidth  = pageData.Width;
                }
            }
            var fileData = new FileData
            {
                DateCreated  = DateTime.Now,
                DateModified = docInfo.LastModificationDate,
                PageCount    = docInfo.Pages.Count,
                Pages        = docInfo.Pages,
                MaxWidth     = maxWidth,
                MaxHeight    = maxHeight
            };

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

            DocumentInfoOptions   documentInfoOptions   = new DocumentInfoOptions(request.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;
            }

            string applicationHost = GetApplicationHost();

            result.imageUrls = ImageUrlHelper.GetImageUrls(applicationHost, pageNumbers, request);
        }
        /// <summary>
        /// Get attached file's html representation
        /// </summary>
        /// <param name="DocumentName">Input document name</param>
        public static void GetEmailAttachmentHTMLRepresentation(String DocumentName)
        {
            try
            {
                //ExStart:GetEmailAttachmentHTMLRepresentation
                // Setup GroupDocs.Viewer config
                ViewerConfig config = Utilities.GetConfigurations();

                // Setup html conversion options
                HtmlOptions htmlOptions = new HtmlOptions();
                htmlOptions.IsResourcesEmbedded = false;

                // Init viewer html handler
                ViewerHtmlHandler handler = new ViewerHtmlHandler(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 html representation
                    List <PageHtml> pages = handler.GetPages(attachment, htmlOptions);
                    foreach (PageHtml page in pages)
                    {
                        Console.WriteLine("  Page: {0}, size: {1}", page.PageNumber, page.HtmlContent.Length);
                        foreach (HtmlResource htmlResource in page.HtmlResources)
                        {
                            Stream resourceStream = handler.GetResource(attachment, htmlResource);
                            Console.WriteLine("     Resource: {0}, size: {1}", htmlResource.ResourceName, resourceStream.Length);
                        }
                    }
                }
                //ExEnd:GetEmailAttachmentHTMLRepresentation
            }
            catch (System.Exception exp)
            {
                Console.WriteLine(exp.Message);
            }
        }
        /// <summary>
        /// Get document information by stream
        /// </summary>
        /// <param name="DocumentName">Name of input document</param>
        public static void GetDocumentInfoByStream(String DocumentName)
        {
            try
            {
                //ExStart:GetDocumentInfoByStream
                // Setup GroupDocs.Viewer config
                ViewerConfig config = Utilities.GetConfigurations();

                // Create html handler
                ViewerHtmlHandler htmlHandler = new ViewerHtmlHandler(config);

                // Get document stream
                Stream stream = Utilities.GetDocumentStream(DocumentName);
                // Get document information
                DocumentInfoOptions   options      = new DocumentInfoOptions();
                DocumentInfoContainer documentInfo = htmlHandler.GetDocumentInfo(stream, options);

                Console.WriteLine("DateCreated: {0}", documentInfo.DateCreated);
                Console.WriteLine("DocumentType: {0}", documentInfo.DocumentType);
                Console.WriteLine("DocumentTypeFormat: {0}", documentInfo.DocumentTypeFormat);
                Console.WriteLine("Extension: {0}", documentInfo.Extension);
                Console.WriteLine("FileType: {0}", documentInfo.FileType);
                Console.WriteLine("Guid: {0}", documentInfo.Guid);
                Console.WriteLine("LastModificationDate: {0}", documentInfo.LastModificationDate);
                Console.WriteLine("Name: {0}", documentInfo.Name);
                Console.WriteLine("PageCount: {0}", documentInfo.Pages.Count);
                Console.WriteLine("Size: {0}", documentInfo.Size);

                foreach (PageData pageData in documentInfo.Pages)
                {
                    Console.WriteLine("Page number: {0}", pageData.Number);
                    Console.WriteLine("Page name: {0}", pageData.Name);
                }
                stream.Close();
                //ExEnd:GetDocumentInfoByStream
            }
            catch (System.Exception exp)
            {
                Console.WriteLine(exp.Message);
            }
        }
        public ActionResult Get(string file)
        {
            if (Utils.IsValidUrl(file))
            {
                file = Utils.DownloadToStorage(file);
            }
            ViewerHtmlHandler     handler = Utils.CreateViewerHtmlHandler();
            DocumentInfoContainer info    = null;
            ResultModel           model   = new ResultModel();
            DocumentInfoOptions   options = new DocumentInfoOptions(file);

            try
            {
                info = handler.GetDocumentInfo(file, options);
            }
            catch (Exception x)
            {
                throw x;
            }
            model.pages = info.Pages;
            List <Attachment> attachmentList = new List <Attachment>();

            foreach (AttachmentBase attachment in info.Attachments)
            {
                List <int>      count = new List <int>();
                List <PageHtml> pages = handler.GetPages(attachment);
                for (int i = 1; i <= pages.Count; i++)
                {
                    count.Add(i);
                }
                model.attachments.Add(new Attachment(attachment.Name, count));
            }
            return(Content(JsonConvert.SerializeObject(
                               model,
                               Formatting.Indented,
                               new JsonSerializerSettings {
                ContractResolver = new CamelCasePropertyNamesContractResolver()
            }
                               ), "application/json"));
        }
示例#11
0
        public static RotatePageResponse RotatePage(RotatePageParameters parameters)
        {
            string guid      = parameters.Path;
            int    pageIndex = parameters.PageNumber;

            DocumentInfoContainer documentInfoContainer = _imageHandler.GetDocumentInfo(guid);
            int pageNumber = documentInfoContainer.Pages[pageIndex].Number;

            RotatePageOptions rotatePageOptions = new RotatePageOptions(pageNumber, parameters.RotationAmount);

            _imageHandler.RotatePage(guid, rotatePageOptions);
            DocumentInfoContainer container = _imageHandler.GetDocumentInfo(guid);

            PageData pageData = container.Pages.Single(_ => _.Number == pageNumber);

            RotatePageResponse response = new RotatePageResponse
            {
                resultAngle = pageData.Angle
            };

            return(response);
        }
        public ActionResult ReorderPage(ReorderPageParameters parameters)
        {
            try
            {
                string guid = parameters.Path;

                DocumentInfoContainer documentInfoContainer = _imageHandler.GetDocumentInfo(guid);

                int pageNumber  = documentInfoContainer.Pages[parameters.OldPosition].Number;
                int newPosition = parameters.NewPosition + 1;

                ReorderPageOptions reorderPageOptions = new ReorderPageOptions(pageNumber, newPosition);
                _imageHandler.ReorderPage(guid, reorderPageOptions);

                return(ToJsonResult(new ReorderPageResponse()));
            }
            catch (Exception e)
            {
                return(this.JsonOrJsonP(new FailedResponse {
                    Reason = e.Message
                }, null));
            }
        }
示例#13
0
        public ActionResult Get(int?width, int?height, string file, string attachment, int page, string watermarkText, int?watermarkColor, WatermarkPosition?watermarkPosition, int?watermarkWidth, byte 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 (watermarkText != "")
            {
                o.Watermark = Utils.GetWatermark(watermarkText, watermarkColor, watermarkPosition, watermarkWidth, watermarkOpacity);
            }
            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, o);
                foreach (PageImage attachmentPage in pages.Where(x => x.PageNumber == page))
                {
                    stream = attachmentPage.Stream;
                }
                ;
            }
            return(new FileStreamResult(stream, "image/png"));
        }
        public List <PageDataModel> Get(string file)
        {
            ViewerHtmlHandler handler = Utils.CreateViewerHtmlHandler();

            DocumentInfoContainer info = null;

            try
            {
                info = handler.GetDocumentInfo(file);
            }
            catch (Exception x)
            {
                throw x;
            }

            List <PageData> result = new List <PageData>();

            foreach (PageData pageData in info.Pages)
            {
                result.Add(pageData);
            }

            return(Convert(result));
        }
        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));
            }
        }
示例#16
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 GetDocumentPageImage(GetDocumentPageImageParameters parameters)
        {
            var guid       = parameters.Path;
            var pageIndex  = parameters.PageIndex;
            var pageNumber = pageIndex + 1;

            var imageOptions = new ImageOptions
            {
                //ConvertImageFileType = _convertImageFileType,

                /*Watermark = Utils.GetWatermark(parameters.WatermarkText, parameters.WatermarkColor,
                 * parameters.WatermarkPosition, parameters.WatermarkWidth),*/
                //Transformations = parameters.Rotate ? Transformation.Rotate : Transformation.None,
                PageNumbersToConvert = new List <int>()
                {
                    parameters.PageIndex
                },
                PageNumber = pageNumber,
                //JpegQuality = parameters.Quality.GetValueOrDefault()
            };
            DocumentInfoContainer documentInfoContainer = annotator.GetDocumentInfo(guid);

            if (parameters.Rotate && parameters.Width.HasValue)
            {
                int pageAngle        = documentInfoContainer.Pages[pageIndex].Angle;
                var isHorizontalView = pageAngle == 90 || pageAngle == 270;

                int sideLength = parameters.Width.Value;
                if (isHorizontalView)
                {
                    imageOptions.Height = sideLength;
                }
                else
                {
                    imageOptions.Width = sideLength;
                }
            }
            else if (parameters.Width.HasValue)
            {
                imageOptions.Width = parameters.Width.Value;
            }

            string baseUrl = Request.Url.Scheme + "://" + Request.Url.Authority + Request.ApplicationPath.TrimEnd('/') + "/";

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

            PageImage pageImage;
            string    docFoldePath = Path.Combine(tempFolderPath, parameters.Path);

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

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

            if (!System.IO.File.Exists(pageImageName))
            {
                pageImage = annotator.GetPages(guid, imageOptions).Single();
                using (FileStream fileStream = new FileStream(pageImageName, FileMode.Create))
                {
                    pageImage.Stream.Seek(0, SeekOrigin.Begin);
                    pageImage.Stream.CopyTo(fileStream);
                }
                pageImage.Stream.Position = 0;
                return(File(pageImage.Stream, String.Format("image/{0}", "png")));
            }
            Stream stream = new MemoryStream();

            using (FileStream fsSource = new FileStream(pageImageName,
                                                        FileMode.Open, FileAccess.Read))
            {
                fsSource.Seek(0, SeekOrigin.Begin);
                fsSource.CopyTo(stream);
            }
            stream.Position = 0;
            return(File(stream, "image/png"));
        }
        public static ViewDocumentResponse ViewDocument(string path)
        {
            string request = path;

            try
            {
                GroupDocs.Annotation.License lic = new GroupDocs.Annotation.License();
                lic.SetLicense("C:/Users/Ali Ahmad/Documents/GroupDocs.Total.lic");
            }
            catch (Exception ex)
            {
                throw;
            }


            string fileName             = Path.GetFileName(request);
            var    pathFinder           = new ApplicationPathFinder();
            string _appPath             = HttpContext.Current.Server.MapPath("~/_layouts/15/GroupDocs_Annotation_SharePoint_WebPart/");
            ViewDocumentResponse result = new ViewDocumentResponse
            {
                pageCss        = new string[] { },
                lic            = true,
                pdfDownloadUrl = _appPath + "App_Data/" + request,
                url            = _appPath + "App_Data/" + request,
                path           = request,
                name           = fileName
            };
            DocumentInfoContainer docInfo = null;

            try
            {
                docInfo = annotator.GetDocumentInfo(request);
            }
            catch (Exception ex)
            {
                throw;
            }

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

            List <PageImage> imagePages = annotator.GetPages(request);

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

            // If no cache - save images to temp folder
            string tempFolderPath = HttpContext.Current.Server.MapPath("~/_layouts/15/GroupDocs_Annotation_SharePoint_WebPart/Content/TempStorage");


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

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

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

                using (Stream stream = pageImage.Stream)
                    using (FileStream fileStream = new FileStream(pageImageName, FileMode.Create))
                    {
                        stream.Seek(0, SeekOrigin.Begin);
                        stream.CopyTo(fileStream);
                    }
                string baseUrl = HttpContext.Current.Request.Url.Scheme + "://" + HttpContext.Current.Request.Url.Authority + HttpContext.Current.Request.ApplicationPath + "_layouts/15/GroupDocs_Annotation_SharePoint_WebPart/";
                urls.Add(string.Format("{0}Content/TempStorage/{1}/{2}.png", baseUrl, request, pageImage.PageNumber));
            }

            result.imageUrls = urls.ToArray();

            // invoke event
            new DocumentOpenSubscriber().HandleEvent(request, _annotationSvc);

            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"));
            }
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="DocumentInfoContainer"/> class.
 /// </summary>
 /// <param name="documentInfo">The document info.</param>
 /// <param name="options">The options.</param>
 public DocumentInfoJsonSerializer(DocumentInfoContainer documentInfo, SerializationOptions options)
 {
     _documentInfo = documentInfo;
     _options = options;
 }
        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();
        }
        public ActionResult ViewDocument(ViewDocumentParameters request)
        {
            string fileName = Path.GetFileName(request.Path);

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

            DocumentInfoContainer docInfo = annotator.GetDocumentInfo(request.Path);

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

            List <PageImage> imagePages = annotator.GetPages(request.Path);

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

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

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

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

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

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

                string 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();

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

            string serializedData = serializer.Serialize(result);

            // invoke event
            new DocumentOpenSubscriber().HandleEvent(request.Path);

            return(Content(serializedData, "application/json"));
        }
        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.
                }
            }
        }
        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);
        }
示例#25
0
 /// <summary>
 /// Initializes a new instance of the <see cref="DocumentInfoContainer"/> class.
 /// </summary>
 /// <param name="documentInfo">The document info.</param>
 /// <param name="options">The options.</param>
 public DocumentInfoJsonSerializer(DocumentInfoContainer documentInfo, SerializationOptions options)
 {
     _documentInfo = documentInfo;
     _options      = options;
 }
        public ActionResult GetDocumentPageImage(GetDocumentPageImageParameters parameters)
        {
            try
            {
                //parameters.IgnoreDocumentAbsence - not supported
                //parameters.InstanceIdToken - not supported

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

                /*
                 * //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,
                    Watermark            = Utils.GetWatermark(parameters.WatermarkText, parameters.WatermarkColor,
                                                              parameters.WatermarkPosition, parameters.WatermarkWidth, parameters.WatermarkOpacity),
                    Transformations     = parameters.Rotate ? Transformation.Rotate : Transformation.None,
                    CountPagesToRender  = 1,
                    PageNumber          = pageNumber,
                    JpegQuality         = parameters.Quality.GetValueOrDefault(),
                    PageNumbersToRender = new List <int>(new int[] { pageNumber })
                };

                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);
                    return(File(pageImage.Stream, GetContentType(_convertImageFileType)));
                }
            }
            catch (Exception e)
            {
                return(this.JsonOrJsonP(new FailedResponse {
                    Reason = e.Message
                }, null));
            }
        }
示例#27
0
        private static void ViewDocumentAsImage(ViewDocumentParameters request, ViewDocumentResponse result, string fileName)
        {
            var docInfo = _imageHandler.GetDocumentInfo(request.Path);

            var maxWidth  = 0;
            var maxHeight = 0;

            foreach (var pageData in docInfo.Pages)
            {
                if (pageData.Height > maxHeight)
                {
                    maxHeight = pageData.Height;
                    maxWidth  = pageData.Width;
                }
            }
            var fileData = new FileData
            {
                DateCreated  = DateTime.Now,
                DateModified = docInfo.LastModificationDate,
                PageCount    = docInfo.Pages.Count,
                Pages        = docInfo.Pages,
                MaxWidth     = maxWidth,
                MaxHeight    = maxHeight
            };
            DocumentInfoContainer documentInfoContainer = _imageHandler.GetDocumentInfo(request.Path);

            int[] pageNumbers = new int[documentInfoContainer.Pages.Count];
            for (int i = 0; i < documentInfoContainer.Pages.Count; i++)
            {
                pageNumbers[i] = documentInfoContainer.Pages[i].Number;
            }
            string applicationHost = GetApplicationHost();
            var    documentUrls    = ImageUrlHelper.GetImageUrls(applicationHost, pageNumbers, request);

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

                ViewDocumentParameters attachmentResponse = request;
                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));
            }
            SerializationOptions serializationOptions = new SerializationOptions
            {
                UsePdf = request.UsePdf,
                SupportListOfBookmarks       = request.SupportListOfBookmarks,
                SupportListOfContentControls = request.SupportListOfContentControls
            };
            var documentInfoJson = new DocumentInfoJsonSerializer(docInfo, serializationOptions).Serialize();

            result.documentDescription = documentInfoJson;

            result.docType  = docInfo.DocumentType;
            result.fileType = docInfo.FileType;
            if (docInfo.Attachments.Count > 0)
            {
                var imagesUrls = new string[attachmentUrls.Length + documentUrls.Length];
                documentUrls.CopyTo(imagesUrls, 0);
                attachmentUrls.CopyTo(imagesUrls, documentUrls.Length);
                result.imageUrls = imagesUrls;
            }
            else
            {
                result.imageUrls = documentUrls;
            }
        }
        public HttpResponseMessage Annotate(AnnotationPostedDataEntity annotateDocumentRequest)
        {
            AnnotatedDocumentEntity annotatedDocument = new AnnotatedDocumentEntity();

            try
            {
                // get/set parameters
                string documentGuid = annotateDocumentRequest.guid;
                string password     = annotateDocumentRequest.password;
                string documentType = annotateDocumentRequest.documentType;
                AnnotationDataEntity[] annotationsData = annotateDocumentRequest.annotationsData;
                // initiate AnnotatedDocument object
                // initiate list of annotations to add
                List <AnnotationInfo> annotations = new List <AnnotationInfo>();
                // get document info - required to get document page height and calculate annotation top position
                string        fileName  = System.IO.Path.GetFileName(documentGuid);
                FileInfo      fi        = new FileInfo(documentGuid);
                DirectoryInfo parentDir = fi.Directory;

                string documentPath  = "";
                string parentDirName = parentDir.Name;
                if (parentDir.FullName == GlobalConfiguration.Annotation.FilesDirectory.Replace("/", "\\"))
                {
                    documentPath = fileName;
                }
                else
                {
                    documentPath = Path.Combine(parentDirName, fileName);
                }
                DocumentInfoContainer documentInfo = AnnotationImageHandler.GetDocumentInfo(documentPath, password);
                // check if document type is image
                if (SupportedImageFormats.Contains(Path.GetExtension(documentGuid)))
                {
                    documentType = "image";
                }
                // initiate annotator object
                string notSupportedMessage = "";
                for (int i = 0; i < annotationsData.Length; i++)
                {
                    // create annotator
                    AnnotationDataEntity annotationData = annotationsData[i];
                    PageData             pageData       = documentInfo.Pages[annotationData.pageNumber - 1];
                    // add annotation, if current annotation type isn't supported by the current document type it will be ignored
                    try
                    {
                        BaseAnnotator annotator = AnnotatorFactory.createAnnotator(annotationData, pageData);
                        if (annotator.IsSupported(documentType))
                        {
                            annotations.Add(annotator.GetAnnotationInfo(documentType));
                        }
                        else
                        {
                            notSupportedMessage = annotator.Message;
                        }
                    }
                    catch (System.Exception ex)
                    {
                        throw new System.Exception(ex.Message, ex);
                    }
                }

                // Add annotation to the document
                DocumentType type = DocumentTypesConverter.GetDocumentType(documentType);
                // Save result stream to file.
                string path = GlobalConfiguration.Annotation.OutputDirectory + Path.DirectorySeparatorChar + fileName;
                if (File.Exists(path))
                {
                    RemoveAnnotations(path);
                }
                // check if annotations array contains at least one annotation to add
                if (annotations.Count != 0)
                {
                    Stream cleanDoc = new FileStream(documentGuid, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite);
                    Stream result   = AnnotationImageHandler.ExportAnnotationsToDocument(cleanDoc, annotations, type);
                    cleanDoc.Dispose();
                    cleanDoc.Close();
                    // Save result stream to file.
                    using (FileStream fileStream = new FileStream(path, FileMode.Create))
                    {
                        byte[] buffer = new byte[result.Length];
                        result.Seek(0, SeekOrigin.Begin);
                        result.Read(buffer, 0, buffer.Length);
                        fileStream.Write(buffer, 0, buffer.Length);
                        fileStream.Close();
                    }
                }
                else
                {
                    return(Request.CreateResponse(HttpStatusCode.OK, new Resources().GenerateException(new NotSupportedException(notSupportedMessage))));
                }
                annotatedDocument = new AnnotatedDocumentEntity()
                {
                    guid = path,
                };
            }
            catch (System.Exception ex)
            {
                // set exception message
                return(Request.CreateResponse(HttpStatusCode.OK, new Resources().GenerateException(ex)));
            }
            return(Request.CreateResponse(HttpStatusCode.OK, annotatedDocument));
        }