Пример #1
0
        public HttpResponseMessage Get(string file, string attachment, int page, string watermarkText, int?watermarkColor, WatermarkPosition?watermarkPosition, int?watermarkWidth, byte watermarkOpacity)
        {
            var attachmentPath             = "cache\\" + Path.GetFileNameWithoutExtension(file) + Path.GetExtension(file).Replace(".", "_") + "\\attachments\\" + attachment;
            ViewerHtmlHandler handler      = Utils.CreateViewerHtmlHandler();
            var        docInfo             = handler.GetDocumentInfo(file);
            List <int> pageNumberstoRender = new List <int>();

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

            o.PageNumbersToRender = pageNumberstoRender;
            o.PageNumber          = page;
            o.CountPagesToRender  = 1;
            o.HtmlResourcePrefix  = "/AttachmentResource?file=" + file + "&attachment=" + attachment + "&page=" + page + "&resource=";
            if (watermarkText != "")
            {
                o.Watermark = Utils.GetWatermark(watermarkText, watermarkColor, watermarkPosition, watermarkWidth, watermarkOpacity);
            }
            string fullHtml       = "";
            var    attachmentFile = _cachePath + "\\" + Path.GetFileNameWithoutExtension(file) + Path.GetExtension(file).Replace(".", "_") + "\\attachments";

            if (Directory.Exists(attachmentFile.Replace(@"\\", @"\")))
            {
                List <PageHtml> pages = handler.GetPages(attachmentPath, o);
                foreach (PageHtml pageHtml in pages.Where(x => x.PageNumber == page))
                {
                    fullHtml += pageHtml.HtmlContent;
                }
                ;
            }
            else
            {
                foreach (AttachmentBase attachmentBase in docInfo.Attachments.Where(x => x.Name == attachment))
                {
                    // Get attachment document html representation
                    List <PageHtml> pages = handler.GetPages(attachmentBase, o);
                    foreach (PageHtml pageHtml in pages.Where(x => x.PageNumber == page))
                    {
                        fullHtml += pageHtml.HtmlContent;
                    }
                    ;
                }
            }
            var response = new HttpResponseMessage();

            response.Content = new StringContent(fullHtml);
            response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/html");
            return(response);
        }
        /// <summary>
        /// Set custom fonts directory path
        /// </summary>
        /// <param name="DocumentName">Input document name</param>
        public static void SetCustomFontDirectory(String DocumentName)
        {
            try
            {
                //ExStart:SetCustomFontDirectory
                // Setup GroupDocs.Viewer config
                ViewerConfig config = Utilities.GetConfigurations();

                // Add custom fonts directories to FontDirectories list
                config.FontDirectories.Add(@"/usr/admin/Fonts");
                config.FontDirectories.Add(@"/home/admin/Fonts");

                ViewerHtmlHandler htmlHandler = new ViewerHtmlHandler(config);

                // File guid
                string guid = DocumentName;

                List <PageHtml> pages = htmlHandler.GetPages(guid);

                foreach (PageHtml page in pages)
                {
                    //Save each page at disk
                    Utilities.SaveAsHtml(page.PageNumber + "_" + DocumentName, page.HtmlContent);
                }
                //ExEnd:SetCustomFontDirectory
            }
            catch (System.Exception exp)
            {
                Console.WriteLine(exp.Message);
            }
        }
        /// <summary>
        /// Render document in html representation with watermark
        /// </summary>
        /// <param name="DocumentName">file/document name</param>
        /// <param name="WatermarkText">watermark text</param>
        /// <param name="WatermarkColor"> System.Drawing.Color</param>
        /// <param name="position">Watermark Position is optional parameter. Default value is WatermarkPosition.Diagonal</param>
        /// <param name="WatermarkWidth"> width of watermark as integer. it is optional Parameter default value is 100</param>
        /// <param name="DocumentPassword">Password Parameter is optional</param>
        public static void RenderDocumentAsHtml(String DocumentName, String WatermarkText, Color WatermarkColor, WatermarkPosition position = WatermarkPosition.Diagonal, int WatermarkWidth = 100, String DocumentPassword = null)
        {
            //ExStart:RenderAsHtmlWithWaterMark
            //Get Configurations
            ViewerConfig config = Utilities.GetConfigurations();

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

            // Guid implies that unique document name
            string guid = DocumentName;

            //Instantiate the HtmlOptions object
            HtmlOptions options = new HtmlOptions();

            options.IsResourcesEmbedded = false;
            // Set password if document is password protected.
            if (!String.IsNullOrEmpty(DocumentPassword))
            {
                options.Password = DocumentPassword;
            }

            // Call AddWatermark and pass the reference of HtmlOptions object as 1st parameter
            Utilities.PageTransformations.AddWatermark(ref options, WatermarkText, WatermarkColor, position, WatermarkWidth);

            //Get document pages in html form
            List <PageHtml> pages = htmlHandler.GetPages(guid, options);

            foreach (PageHtml page in pages)
            {
                //Save each page at disk
                Utilities.SaveAsHtml(page.PageNumber + "_" + DocumentName, page.HtmlContent);
            }
            //ExEnd:RenderAsHtmlWithWaterMark
        }
        /// <summary>
        /// Add Watermark to Html page representation
        /// </summary>
        public static void Add_Watermark_For_Html()
        {
            Console.WriteLine("***** {0} *****", "Add Watermark to Html page representation");

            /* ********************* SAMPLE ********************* */

            // Setup GroupDocs.Viewer config
            ViewerConfig config = new ViewerConfig();
            config.StoragePath = @"C:\storage";

            // Create html handler
            ViewerHtmlHandler htmlHandler = new ViewerHtmlHandler(config);
            string guid = "word.doc";

            HtmlOptions options = new HtmlOptions();

            // Set watermark properties
            Watermark watermark = new Watermark("This is watermark text");
            watermark.Color = System.Drawing.Color.Blue;
            watermark.Position = WatermarkPosition.Diagonal;
            watermark.Width = 100;

            options.Watermark = watermark;

            // Get document pages html representation with watermark
            List<PageHtml> pages = htmlHandler.GetPages(guid, options);
        }
        /// <summary>
        /// Render simple document in html representation
        /// </summary>
        /// <param name="DocumentName">File name</param>
        /// <param name="DocumentPassword">Optional</param>
        public static void RenderDocumentAsHtml(String DocumentName, String DocumentPassword = null)
        {
            //ExStart:RenderAsHtml
            //Get Configurations
            ViewerConfig config = Utilities.GetConfigurations();

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

            // Guid implies that unique document name
            string guid = DocumentName;

            //Instantiate the HtmlOptions object
            HtmlOptions options = new HtmlOptions();

            //to get html representations of pages with embedded resources
            options.IsResourcesEmbedded = true;

            // Set password if document is password protected.
            if (!String.IsNullOrEmpty(DocumentPassword))
            {
                options.Password = DocumentPassword;
            }
            //  options.PageNumbersToConvert = Enumerable.Range(1, 3).ToList();
            //Get document pages in html form
            List <PageHtml> pages = htmlHandler.GetPages(guid, options);

            foreach (PageHtml page in pages)
            {
                //Save each page at disk
                Utilities.SaveAsHtml(page.PageNumber + "_" + DocumentName, page.HtmlContent);
            }
            //ExEnd:RenderAsHtml
        }
        public static void InHtmlRepresentation()
        {
            // Setup GroupDocs.Viewer config
            ViewerConfig config = new ViewerConfig();
            config.StoragePath = @"C:\storage";

            // Create html handler
            ViewerHtmlHandler htmlHandler = new ViewerHtmlHandler(config);
            string guid = "document.xlsx";

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

            DocumentInfoContainer container = htmlHandler.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<PageHtml> pages = htmlHandler.GetPages(guid, options);

            foreach (PageHtml page in pages)
            {
                Console.WriteLine("Page number: {0}", page.PageNumber);
                //Console.WriteLine("Html content: {0}", page.HtmlContent);
            }
        }
        /// <summary>
        /// Get document html representation with embedded resources
        /// </summary>
        public static void Get_Html_EmbeddedResources()
        {
            Console.WriteLine("***** {0} *****", "Get document html representation with embedded resources");

            /* ********************* SAMPLE ********************* */

            // Setup GroupDocs.Viewer config
            ViewerConfig config = new ViewerConfig();
            config.StoragePath = @"C:\storage";

            // Create html handler
            ViewerHtmlHandler htmlHandler = new ViewerHtmlHandler(config);
            string guid = "word.doc";

            HtmlOptions options = new HtmlOptions();
            options.IsResourcesEmbedded = true;

            List<PageHtml> pages = htmlHandler.GetPages(guid, options);

            foreach (PageHtml page in pages)
            {
                Console.WriteLine("Page number: {0}", page.PageNumber);
                Console.WriteLine("Html content: {0}", page.HtmlContent);
            }
        }
        /// <summary>
        /// Render a document in html representation whom located at web/remote location.
        /// </summary>
        /// <param name="DocumentURL">URL of the document</param>
        /// <param name="DocumentPassword">Password Parameter is optional</param>
        public static void RenderDocumentAsHtml(Uri DocumentURL, String DocumentPassword = null)
        {
            //ExStart:RenderRemoteDocAsHtml
            //Get Configurations
            ViewerConfig config = Utilities.GetConfigurations();

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

            //Instantiate the HtmlOptions object
            HtmlOptions options = new HtmlOptions();

            if (!String.IsNullOrEmpty(DocumentPassword))
            {
                options.Password = DocumentPassword;
            }

            //Get document pages in html form
            List <PageHtml> pages = htmlHandler.GetPages(DocumentURL, options);

            foreach (PageHtml page in pages)
            {
                //Save each page at disk
                Utilities.SaveAsHtml(page.PageNumber + "_" + Path.GetFileName(DocumentURL.LocalPath), page.HtmlContent);
            }
            //ExEnd:RenderRemoteDocAsHtml
        }
        /// <summary>
        /// Get document html representation
        /// </summary>
        public static void Get_Html_With_Resources()
        {
            Console.WriteLine("***** {0} *****", "Get document html representation");

            /* ********************* SAMPLE ********************* */

            // Setup GroupDocs.Viewer config
            ViewerConfig config = new ViewerConfig();
            config.StoragePath = @"C:\storage";

            // Create html handler
            ViewerHtmlHandler htmlHandler = new ViewerHtmlHandler(config);
            string guid = "word.doc";

            List<PageHtml> pages = htmlHandler.GetPages(guid);

            foreach (PageHtml page in pages)
            {
                Console.WriteLine("Page number: {0}", page.PageNumber);
                Console.WriteLine("Resources count: {0}", page.HtmlResources.Count);
                Console.WriteLine("Html content: {0}", page.HtmlContent);

                // Html resources descriptions
                foreach (HtmlResource resource in page.HtmlResources)
                {
                    Console.WriteLine(resource.ResourceName, resource.ResourceType);

                    // Get html page resource stream
                    Stream resourceStream = htmlHandler.GetResource(guid, resource);
                }
            }
        }
        public ResultModel Get(string file)
        {
            if (Utils.IsValidUrl(file))
            {
                file = Utils.DownloadToStorage(file);
            }

            ViewerHtmlHandler     handler = Utils.CreateViewerHtmlHandler();
            ResultModel           model   = new ResultModel();
            DocumentInfoContainer info    = null;

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

            model.pages = Convert(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(model);
        }
        /// <summary>
        /// How to use custom input data handler
        /// </summary>
        public static void Run()
        {
            Console.WriteLine("***** {0} *****", "How to use custom input data handler");

            /* ********************* SAMPLE ********************* */

            // Setup GroupDocs.Viewer config
            ViewerConfig config = new ViewerConfig();
            config.StoragePath = @"C:\storage";

            // File guid
            string guid = @"word.doc";

            // Use custom IInputDataHandler implementation
            IInputDataHandler inputDataHandler = new FtpInputDataHandler();

            // Get file HTML representation
            ViewerHtmlHandler htmlHandler = new ViewerHtmlHandler(config, inputDataHandler);

            List<PageHtml> pages = htmlHandler.GetPages(guid);

            Console.WriteLine("Pages count: {0}", pages.Count);

            // Get list of entities for ftp root folder
            FileTreeOptions options = new FileTreeOptions(@"ftp://localhost");
            FileTreeContainer container = htmlHandler.LoadFileTree(options);
        }
 public static List <PageHtml> LoadPageHtmlList(ViewerHtmlHandler handler, String filename, HtmlOptions options)
 {
     try
     {
         return(handler.GetPages(filename, options));
     }
     catch (Exception x)
     {
         throw x;
     }
 }
Пример #13
0
 public static List <PageHtml> LoadAttachmentHtmlList(ViewerHtmlHandler handler, String filename, String attahchment, HtmlOptions options)
 {
     try
     {
         return(handler.GetPages(_cachePath + "\\" + Path.GetFileNameWithoutExtension(filename) + Path.GetExtension(filename).Replace(".", "_") + "\\attachments\\" + attahchment, options));
     }
     catch (Exception x)
     {
         throw x;
     }
 }
        public void Page_Load(object sender, EventArgs e)
        {
            var file       = GetValueFromQueryString("file");
            var page       = Convert.ToInt32(GetValueFromQueryString("page"));
            var attachment = GetValueFromQueryString("attachment");

            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"));


            ViewerHtmlHandler handler             = Utils.CreateViewerHtmlHandler();
            List <int>        pageNumberstoRender = new List <int>();

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

            o.PageNumbersToRender = pageNumberstoRender;
            o.PageNumber          = page;
            o.CountPagesToRender  = 1;
            o.HtmlResourcePrefix  = (String.Format(
                                         "/page/resource?file=%s&page=%d&resource=",
                                         file,
                                         page
                                         ));
            if (watermarkText != "")
            {
                o.Watermark = Utils.GetWatermark(watermarkText, watermarkColor, watermarkPosition, watermarkWidth, watermarkOpacity);
            }
            var docInfo = handler.GetDocumentInfo(file);

            List <PageHtml> list = Utils.LoadPageHtmlList(handler, file, o);

            string fullHtml = "";

            foreach (AttachmentBase attachmentBase in docInfo.Attachments.Where(x => x.Name == attachment))
            {
                // Get attachment document html representation
                List <PageHtml> pages = handler.GetPages(attachmentBase, o);
                foreach (PageHtml pageHtml in pages.Where(x => x.PageNumber == page))
                {
                    fullHtml += pageHtml.HtmlContent;
                }
                ;
            }

            HttpContext.Current.Response.ContentType = "text/html";
            HttpContext.Current.Response.Write(fullHtml);
            HttpContext.Current.Response.Flush();
            HttpContext.Current.Response.End();
        }
Пример #15
0
        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
            {
                if (Path.GetExtension(file).ToLower().StartsWith(".xls"))
                {
                    info = handler.GetDocumentInfo(file, new GroupDocs.Viewer.Domain.Options.DocumentInfoOptions()
                    {
                        CellsOptions = new GroupDocs.Viewer.Converter.Options.CellsOptions()
                        {
                            CountRowsPerPage = 150, OnePagePerSheet = false
                        }
                    });
                }
                else
                {
                    info = handler.GetDocumentInfo(file);
                }
            }
            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"));
        }
Пример #16
0
        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 (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);
                var    result = new HttpResponseMessage(HttpStatusCode.OK);
                result.Content = new StreamContent(stream);
                result.Content.Headers.ContentType = new MediaTypeHeaderValue(type);
                return(result);
            }
            return(null);
        }
Пример #17
0
        public ResultModel Get(string file)
        {
            if (Utils.IsValidUrl(file))
            {
                file = Utils.DownloadToStorage(file);
            }

            ViewerHtmlHandler     handler = Utils.CreateViewerHtmlHandler();
            ResultModel           model   = new ResultModel();
            DocumentInfoContainer info    = null;

            try
            {
                if (Path.GetExtension(file).ToLower().StartsWith(".xls"))
                {
                    info = handler.GetDocumentInfo(file, new GroupDocs.Viewer.Domain.Options.DocumentInfoOptions()
                    {
                        CellsOptions = new GroupDocs.Viewer.Converter.Options.CellsOptions()
                        {
                            CountRowsPerPage = 150, OnePagePerSheet = false
                        }
                    });
                }
                else
                {
                    info = handler.GetDocumentInfo(file);
                }
            }
            catch (Exception x)
            {
                throw x;
            }

            model.pages = Convert(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(model);
        }
        /// <summary>
        ///  document in html representation and reorder a page
        /// </summary>
        /// <param name="DocumentName">file/document name</param>
        /// <param name="CurrentPageNumber">Page existing order number</param>
        /// <param name="NewPageNumber">Page new order number</param>
        /// <param name="DocumentPassword">Password Parameter is optional</param>
        public static List <HtmlInfo> RenderDocumentAsHtml(String DocumentName, int CurrentPageNumber, int NewPageNumber, String DocumentPassword = null)
        {
            //ExStart:RenderAsHtmlAndReorderPage
            //Get Configurations
            ViewerConfig config = Utilities.GetConfigurations();

            // Cast ViewerHtmlHandler class object to its base class(ViewerHandler).
            ViewerHandler <PageHtml> handler = new ViewerHtmlHandler(config);

            // Guid implies that unique document name
            string guid = DocumentName;

            //Instantiate the HtmlOptions object with setting of Reorder Transformation
            HtmlOptions options = new HtmlOptions {
                Transformations = Transformation.Reorder
            };

            //to get html representations of pages with embedded resources
            options.IsResourcesEmbedded = true;

            // Set password if document is password protected.
            if (!String.IsNullOrEmpty(DocumentPassword))
            {
                options.Password = DocumentPassword;
            }

            //Call ReorderPage and pass the reference of ViewerHandler's class  parameter by reference.
            Utilities.PageTransformations.ReorderPage(ref handler, guid, CurrentPageNumber, NewPageNumber);

            //down cast the handler(ViewerHandler) to viewerHtmlHandler
            ViewerHtmlHandler htmlHandler = (ViewerHtmlHandler)handler;

            //Get document pages in html form
            List <PageHtml> pages = htmlHandler.GetPages(guid, options);

            List <HtmlInfo> contents = new List <HtmlInfo>();

            foreach (PageHtml page in pages)
            {
                HtmlInfo htmlInfo = new HtmlInfo();
                htmlInfo.HtmlContent = page.HtmlContent;
                htmlInfo.PageNmber   = page.PageNumber;
                contents.Add(htmlInfo);
            }
            return(contents);
            //ExEnd:RenderAsHtmlAndReorderPage
        }
        public static List <HtmlInfo> RotateDocumentAsHtml(String DocumentName, int pageNumber, int RotationAngle, String DocumentPassword = null)
        {
            //ExStart:RenderAsImageWithRotationTransformation
            //Get Configurations
            ViewerConfig config = Utilities.GetConfigurations();

            // Create image handler
            ViewerHandler <PageHtml> handler = new ViewerHtmlHandler(config);

            // Guid implies that unique document name
            string guid = DocumentName;

            //Initialize ImageOptions Object and setting Rotate Transformation
            HtmlOptions options = new HtmlOptions {
                Transformations = Transformation.Rotate
            };

            // Set password if document is password protected.
            if (!String.IsNullOrEmpty(DocumentPassword))
            {
                options.Password = DocumentPassword;
            }

            //Call RotatePages to apply rotate transformation to a page
            Utilities.PageTransformations.RotatePages(ref handler, guid, pageNumber, RotationAngle);

            //down cast the handler(ViewerHandler) to viewerHtmlHandler
            ViewerHtmlHandler htmlHandler = (ViewerHtmlHandler)handler;

            //Get document pages in image form
            List <PageHtml> pages = htmlHandler.GetPages(guid, options);

            List <HtmlInfo> contents = new List <HtmlInfo>();

            foreach (PageHtml page in pages)
            {
                HtmlInfo htmlInfo = new HtmlInfo();
                htmlInfo.HtmlContent = page.HtmlContent;
                htmlInfo.PageNmber   = page.PageNumber;
                contents.Add(htmlInfo);
            }

            return(contents);
            //ExEnd:RenderAsImageWithRotationTransformation
        }
Пример #20
0
        public JsonResult LoadDocument(string fullName)
        {
            if (!string.IsNullOrEmpty(fullName))
            {
                var result = new ViewDocumentResponse
                {
                    pageCss = new string[] {},
                    lic     = true,
                    url     = fullName,
                    path    = fullName,
                    name    = fullName
                };


                var docInfo = _htmlHandler.GetDocumentInfo(new GroupDocs.Viewer.Domain.Options.DocumentInfoOptions(fullName));

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

                var htmlOptions = new HtmlOptions {
                    IsResourcesEmbedded = true
                };

                var htmlPages = _htmlHandler.GetPages(fullName, htmlOptions);
                result.pageHtml = htmlPages.Select(_ => _.HtmlContent).ToArray();

                //NOTE: Fix for incomplete cells document
                for (int i = 0; i < result.pageHtml.Length; i++)
                {
                    var html          = result.pageHtml[i];
                    var indexOfScript = html.IndexOf("script");
                    if (indexOfScript > 0)
                    {
                        result.pageHtml[i] = html.Substring(0, indexOfScript);
                    }
                }

                AjaxResponse ajaxResponse = AjaxResponse.Successful(string.Empty, result);

                return(Json(ajaxResponse));
            }
            return(null);
        }
        public void ShouldRender()
        {
            // Create a file to be rendered
            string filePath = "sample/file.txt";

            using (Stream testStream = GetTestFileStream())
            {
                _fileStorage.SaveFile(filePath, testStream);
            }

            // Create IFileStorage and run the rendering
            AzureBlobStorage  storage = new AzureBlobStorage(TestContainerName);
            ViewerHtmlHandler handler = new ViewerHtmlHandler(storage);
            List <PageHtml>   pages   = handler.GetPages("sample/file.txt");


            Assert.True(pages.Count > 0);
            Assert.NotNull(pages[0].HtmlContent);
        }
        static void RenderTestFile(string fileName, DropboxClient client)
        {
            var storage = new DropboxStorage(client);

            var config = new ViewerConfig
            {
                EnableCaching = true
            };
            var viewer = new ViewerHtmlHandler(config, storage);

            var pages = viewer.GetPages(fileName);

            foreach (var page in pages)
            {
                Console.WriteLine(page.HtmlContent);
            }

            viewer.ClearCache(fileName);
        }
        /// <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);
            }
        }
        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 ((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);
                return(new FileStreamResult(stream, type));
            }
            return(null);
        }
        public static void InHtmlRepresentation()
        {
            // Setup GroupDocs.Viewer config
            ViewerConfig config = new ViewerConfig();
            config.StoragePath = @"C:\storage";

            // Create html handler
            ViewerHtmlHandler htmlHandler = new ViewerHtmlHandler(config);
            string guid = "document.xlsx";

            // Set html options to show grid lines
            HtmlOptions options = new HtmlOptions();
            options.CellsOptions.ShowGridLines = true;
            List<PageHtml> pages = htmlHandler.GetPages(guid, options);

            foreach (PageHtml page in pages)
            {
                Console.WriteLine("Page number: {0}", page.PageNumber);
                Console.WriteLine("Html content: {0}", page.HtmlContent);
            }
        }
        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"));
        }
        /// <summary>
        /// Render simple document in html representation
        /// </summary>
        /// <param name="DocumentName">File name</param>
        /// <param name="DocumentPassword">Optional</param>
        public static List <HtmlInfo> RenderDocumentAsHtml(String DocumentName, String DocumentPassword = null)
        {
            //ExStart:RenderAsHtml
            //Get Configurations
            ViewerConfig config = Utilities.GetConfigurations();

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


            // Guid implies that unique document name
            string guid = DocumentName;

            //Instantiate the HtmlOptions object
            HtmlOptions options = new HtmlOptions();

            //to get html representations of pages with embedded resources
            options.IsResourcesEmbedded = true;

            // Set password if document is password protected.
            if (!String.IsNullOrEmpty(DocumentPassword))
            {
                options.Password = DocumentPassword;
            }

            //Get document pages in html form
            List <PageHtml> pages    = htmlHandler.GetPages(guid, options);
            List <HtmlInfo> contents = new List <HtmlInfo>();

            foreach (PageHtml page in pages)
            {
                HtmlInfo htmlInfo = new HtmlInfo();
                htmlInfo.HtmlContent = page.HtmlContent;
                htmlInfo.PageNmber   = page.PageNumber;
                contents.Add(htmlInfo);
            }

            return(contents);
            //ExEnd:RenderAsHtml
        }
        /// <summary>
        /// Render a document from FTP location
        /// </summary>
        /// <param name="DocumentName"></param>
        public static void RenderDocFromFTP(String DocumentName)
        {
            // Setup GroupDocs.Viewer config
            ViewerConfig config = Utilities.GetConfigurations();

            // File guid
            string guid = DocumentName;

            // Use custom IInputDataHandler implementation
            IInputDataHandler inputDataHandler = new FtpInputDataHandler();

            // Get file HTML representation
            ViewerHtmlHandler htmlHandler = new ViewerHtmlHandler(config, inputDataHandler);

            List <PageHtml> pages = htmlHandler.GetPages(guid);

            foreach (PageHtml page in pages)
            {
                //Save each page at disk
                Utilities.SaveAsHtml(page.PageNumber + "_" + DocumentName, page.HtmlContent);
            }
        }
        static void Main(string[] args)
        {
            //TODO: 1. Set your credentials in app.config
            //TODO: 2. Set bucket name
            //TODO: 3. Upload at least one document into bucket for testing

            var amazonS3Client      = new AmazonS3Client();
            var amazonS3FileManager = new AmazonS3FileManager(amazonS3Client, Bucket);
            var viewerDataHandler   = new ViewerDataHandler(amazonS3FileManager);

            var viewerConfig = new ViewerConfig {
                EnableCaching = true
            };
            var handler = new ViewerHtmlHandler(viewerConfig, viewerDataHandler, viewerDataHandler);

            var pagesHtml = handler.GetPages(FileName);

            Debug.Assert(pagesHtml.Count > 0);
            Debug.Assert(!string.IsNullOrEmpty(pagesHtml[0].HtmlContent));

            Console.WriteLine("Press any key...");
            Console.ReadKey();
        }
        /* Working from 3.2.0*/
        /// <summary>
        /// Show grid lines for Excel files in html representation
        /// </summary>
        /// <param name="DocumentName"></param>
        public static void RenderWithGridLinesInExcel(String DocumentName)
        {
            // Setup GroupDocs.Viewer config
            ViewerConfig config = Utilities.GetConfigurations();

            ViewerHtmlHandler htmlHandler = new ViewerHtmlHandler(config);

            // File guid
            string guid = DocumentName;

            // Set html options to show grid lines
            HtmlOptions options = new HtmlOptions();

            //do same while using ImageOptions
            options.CellsOptions.ShowGridLines = true;

            List <PageHtml> pages = htmlHandler.GetPages(guid, options);

            foreach (PageHtml page in pages)
            {
                //Save each page at disk
                Utilities.SaveAsHtml(page.PageNumber + "_" + DocumentName, page.HtmlContent);
            }
        }
        public ActionResult Get(string file, string attachment, int page)
        {
            ViewerHtmlHandler handler = Utils.CreateViewerHtmlHandler();

            List <int> pageNumberstoRender = new List <int>();
            var        docInfo             = handler.GetDocumentInfo(file);

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

            o.PageNumbersToRender = pageNumberstoRender;
            o.PageNumber          = page;
            o.CountPagesToRender  = 1;
            o.HtmlResourcePrefix  = (String.Format(
                                         "/page/resource?file=%s&page=%d&resource=",
                                         file,
                                         page
                                         ));

            List <PageHtml> list     = Utils.LoadPageHtmlList(handler, file, o);
            string          fullHtml = "";

            foreach (AttachmentBase attachmentBase in docInfo.Attachments.Where(x => x.Name == attachment))
            {
                // Get attachment document html representation
                List <PageHtml> pages = handler.GetPages(attachmentBase, o);
                foreach (PageHtml pageHtml in pages.Where(x => x.PageNumber == page))
                {
                    fullHtml += pageHtml.HtmlContent;
                }
                ;
            }


            return(Content(fullHtml));
        }
        /// <summary>
        /// create and use file with localized string
        /// </summary>
        /// <param name="DocumentName"></param>
        public static void RenderWithLocales(String DocumentName)
        {
            // Setup GroupDocs.Viewer config
            ViewerConfig config = Utilities.GetConfigurations();

            config.LocalesPath = @"D:\from office working\for aspose\GroupDocsViewer\GroupDocs.Viewer.Examples\Data\Locale";

            CultureInfo       cultureInfo = new CultureInfo("fr-FR");
            ViewerHtmlHandler htmlHandler = new ViewerHtmlHandler(config, cultureInfo);

            // File guid
            string guid = DocumentName;

            // Set html options to show grid lines
            HtmlOptions options = new HtmlOptions();

            List <PageHtml> pages = htmlHandler.GetPages(guid, options);

            foreach (PageHtml page in pages)
            {
                //Save each page at disk
                Utilities.SaveAsHtml(page.PageNumber + "_" + DocumentName, page.HtmlContent);
            }
        }
        public static void Reorder_Pages_In_Html_Mode()
        {
            Console.WriteLine("***** {0} *****", "Reorder pages in Html mode");

            /* ********************* SAMPLE ********************* */
            /* ********************   Reorder 1st and 2nd pages  *********************** */

            // Setup GroupDocs.Viewer config
            ViewerConfig config = new ViewerConfig();
            config.StoragePath = @"C:\storage";

            // Create html handler
            ViewerHtmlHandler htmlHandler = new ViewerHtmlHandler(config);
            string guid = "word.doc";
            int pageNumber = 1;
            int newPosition = 2;

            // Perform page reorder
            ReorderPageOptions options = new ReorderPageOptions(guid, pageNumber, newPosition);
            htmlHandler.ReorderPage(options);


            /* ********************  Retrieve all document pages including transformation *********************** */

            // Set html options to include reorder transformations
            HtmlOptions htmlOptions = new HtmlOptions
            {
                Transformations = Transformation.Reorder
            };

            // Get html representation of all document pages, including reorder transformations 
            List<PageHtml> pages = htmlHandler.GetPages(guid, htmlOptions);


            /* ********************  Retrieve all document pages excluding transformation *********************** */

            // Set html options NOT to include ANY transformations
            HtmlOptions noTransformationsOptions = new HtmlOptions
            {
                Transformations = Transformation.None // This is by default
            };

            // Get html representation of all document pages, without transformations 
            List<PageHtml> pagesWithoutTransformations = htmlHandler.GetPages(guid, noTransformationsOptions);

            // Get html representation of all document pages, without transformations
            List<PageHtml> pagesWithoutTransformations2 = htmlHandler.GetPages(guid);
        }
        public HttpResponseMessage LoadDocumentPage(PostedDataWrapper postedData)
        {
            try
            {
                // get/set parameters
                string            documentGuid = postedData.guid;
                int               pageNumber   = postedData.page;
                bool              htmlMode     = postedData.htmlMode;
                string            password     = postedData.password;
                LoadedPageWrapper loadedPage   = new LoadedPageWrapper();
                string            angle        = "0";
                // set options
                if (htmlMode)
                {
                    HtmlOptions htmlOptions = new HtmlOptions();
                    htmlOptions.PageNumber          = pageNumber;
                    htmlOptions.CountPagesToRender  = 1;
                    htmlOptions.IsResourcesEmbedded = true;
                    // set password for protected document
                    if (!String.IsNullOrEmpty(password))
                    {
                        htmlOptions.Password = password;
                    }
                    // get page HTML
                    loadedPage.pageHtml = viewerHtmlHandler.GetPages(documentGuid, htmlOptions)[0].HtmlContent;
                    // get page rotation angle
                    angle = viewerHtmlHandler.GetDocumentInfo(documentGuid).Pages[pageNumber - 1].Angle.ToString();
                }
                else
                {
                    ImageOptions imageOptions = new ImageOptions();
                    imageOptions.PageNumber         = pageNumber;
                    imageOptions.CountPagesToRender = 1;
                    // set password for protected document
                    if (!String.IsNullOrEmpty(password))
                    {
                        imageOptions.Password = password;
                    }

                    byte[] bytes;
                    using (var memoryStream = new MemoryStream())
                    {
                        viewerImageHandler.GetPages(documentGuid, imageOptions)[0].Stream.CopyTo(memoryStream);
                        bytes = memoryStream.ToArray();
                    }

                    string incodedImage = Convert.ToBase64String(bytes);

                    loadedPage.pageImage = incodedImage;
                    // get page rotation angle
                    angle = viewerImageHandler.GetDocumentInfo(documentGuid).Pages[pageNumber - 1].Angle.ToString();
                }
                loadedPage.angle = angle;
                // return loaded page object
                return(Request.CreateResponse(HttpStatusCode.OK, loadedPage));
            }
            catch (Exception ex)
            {
                // set exception message
                ErrorMsgWrapper errorMsgWrapper = new ErrorMsgWrapper();
                errorMsgWrapper.message   = ex.Message;
                errorMsgWrapper.exception = ex;
                return(Request.CreateResponse(HttpStatusCode.OK, errorMsgWrapper));
            }
        }
        /// <summary>
        /// Perform multiple transformations in Html mode
        /// </summary>
        public static void Multiple_Transformations_For_Html()
        {
            Console.WriteLine("***** {0} *****", "Perform multiple transformations in Html mode");

            /* ********************* SAMPLE ********************* */

            // Setup GroupDocs.Viewer config
            ViewerConfig config = new ViewerConfig();
            config.StoragePath = @"C:\storage";

            // Create html handler
            ViewerHtmlHandler htmlHandler = new ViewerHtmlHandler(config);
            string guid = "word.doc";

            // Rotate first page 90 degrees
            htmlHandler.RotatePage(new RotatePageOptions(guid, 1, 90));

            // Rotate second page 180 degrees
            htmlHandler.RotatePage(new RotatePageOptions(guid, 2, 180));

            // Reorder first and second pages
            htmlHandler.ReorderPage(new ReorderPageOptions(guid, 1, 2));

            // Set options to include rotate and reorder transformations
            HtmlOptions options = new HtmlOptions { Transformations = Transformation.Rotate | Transformation.Reorder };

            // Set watermark properties
            Watermark watermark = new Watermark("This is watermark text")
            {
                Color = System.Drawing.Color.Blue,
                Position = WatermarkPosition.Diagonal,
                Width = 100
            };

            options.Watermark = watermark;

            // Get document pages html representation with multiple transformations
            List<PageHtml> pages = htmlHandler.GetPages(guid, options);
        }
        /// <summary>
        /// Rotate page in Html mode
        /// </summary>
        public static void Rotate_Page_In_Html_Mode()
        {
            Console.WriteLine("***** {0} *****", "Rotate page in Html mode");

            /* ********************* SAMPLE ********************* */

            string licensePath = @"D:\GroupDocs.Viewer.lic";

            // Setup license
            GroupDocs.Viewer.License lic = new GroupDocs.Viewer.License();
            lic.SetLicense(licensePath);

            /* ********************  SAMPLE BEGIN ************************ */
            /* ********************  Rotate 1st page of the document by 90 deg *********************** */
            // Setup GroupDocs.Viewer config
            ViewerConfig config = new ViewerConfig();
            config.StoragePath = @"C:\storage";

            // Create html handler
            ViewerHtmlHandler htmlHandler = new ViewerHtmlHandler(config);
            string guid = "word.doc";

            // Set rotation angle 90 for page number 1
            RotatePageOptions rotateOptions = new RotatePageOptions(guid, 1, 90);

            // Perform page rotation
            htmlHandler.RotatePage(rotateOptions);


            /* ********************  Retrieve all document pages including transformation *********************** */
            // Set html options to include rotate transformations
            HtmlOptions htmlOptions = new HtmlOptions
            {
                Transformations = Transformation.Rotate
            };

            // Get html representation of all document pages, including rotate transformations 
            List<PageHtml> pages = htmlHandler.GetPages(guid, htmlOptions);


            /* ********************  Retrieve all document pages excluding transformation *********************** */
            // Set html options NOT to include ANY transformations
            HtmlOptions noTransformationsOptions = new HtmlOptions
            {
                Transformations = Transformation.None // This is by default
            };

            // Get html representation of all document pages, without transformations 
            List<PageHtml> pagesWithoutTransformations = htmlHandler.GetPages(guid, noTransformationsOptions);

            // Get html representation of all document pages, without transformations
            List<PageHtml> pagesWithoutTransformations2 = htmlHandler.GetPages(guid);

            /*********************  SAMPLE END *************************/
            //foreach (PageHtml page in pages)
            //{
            //    // Page number
            //    Console.WriteLine("Page number: {0}", page.PageNumber);
            //}
        }
Пример #37
0
        private static void ViewDocumentAsHtml(ViewDocumentParameters request, ViewDocumentResponse result, string fileName)
        {
            var htmlHandler = (ViewerHtmlHandler)HttpContext.Current.Session["htmlHandler"];

            var docInfo = htmlHandler.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
            };



            var htmlOptions = new HtmlOptions
            {
                // IsResourcesEmbedded = Utils.IsImage(fileName),
                IsResourcesEmbedded = false,
                HtmlResourcePrefix  = string.Format("/GetResourceForHtml.aspx?documentPath={0}", fileName) + "&pageNumber={page-number}&resourceName=",
            };

            if (request.PreloadPagesCount.HasValue && request.PreloadPagesCount.Value > 0)
            {
                htmlOptions.PageNumber         = 1;
                htmlOptions.CountPagesToRender = request.PreloadPagesCount.Value;
            }

            List <string> cssList;
            var           htmlPages = GetHtmlPages(fileName, fileName, htmlOptions, out cssList);

            foreach (AttachmentBase attachment in docInfo.Attachments)
            {
                var attachmentPath         = _tempPath + "\\" + Path.GetFileNameWithoutExtension(docInfo.Guid) + Path.GetExtension(docInfo.Guid).Replace(".", "_") + "\\attachments\\" + attachment.Name;
                var attachmentResourcePath = HttpUtility.UrlEncode(_tempPath + "\\" + Path.GetFileNameWithoutExtension(docInfo.Guid) + Path.GetExtension(docInfo.Guid).Replace(".", "_") + "\\attachments\\" + attachment.Name.Replace(".", "_"));
                var attachmentHtmlOptions  = new HtmlOptions()
                {
                    IsResourcesEmbedded = Utils.IsImage(fileName),
                    HtmlResourcePrefix  = string.Format("/GetResourceForHtml.aspx?documentPath={0}", HttpUtility.UrlEncode(attachmentPath)) + "&pageNumber={page-number}&resourceName=",
                };
                List <PageHtml> pages          = _htmlHandler.GetPages(attachment, attachmentHtmlOptions);
                var             attachmentInfo = _htmlHandler.GetDocumentInfo(attachmentPath);
                fileData.PageCount += attachmentInfo.Pages.Count;
                fileData.Pages.AddRange(attachmentInfo.Pages);
                List <string> attachmentCSSList;
                var           attachmentPages = GetHtmlPages(attachmentPath, attachmentResourcePath, attachmentHtmlOptions, out attachmentCSSList);
                cssList.AddRange(attachmentCSSList);
                htmlPages.AddRange(attachmentPages);
            }
            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;
            result.pageHtml            = htmlPages.Select(_ => _.HtmlContent).ToArray();
            result.pageCss             = new[] { string.Join(" ", cssList) };
        }
Пример #38
0
        private List <HtmlPageContent> GetHtmlPageContents(string guid, HtmlOptions htmlOptions)
        {
            var pageContents = new List <HtmlPageContent>();

            var documentInfo = _htmlHandler.GetDocumentInfo(guid);

            var htmlPages = _htmlHandler.GetPages(guid, htmlOptions);

            foreach (var page in htmlPages)
            {
                var html = page.HtmlContent;

                var indexOfBodyOpenTag = html.IndexOf("<body>", StringComparison.InvariantCultureIgnoreCase);
                if (indexOfBodyOpenTag > 0)
                {
                    html = html.Substring(indexOfBodyOpenTag + "<body>".Length);
                }

                var indexOfBodyCloseTag = html.IndexOf("</body>", StringComparison.InvariantCultureIgnoreCase);
                if (indexOfBodyCloseTag > 0)
                {
                    html = html.Substring(0, indexOfBodyCloseTag);
                }

                string css = string.Empty;
                foreach (var resource in page.HtmlResources.Where(_ => _.ResourceType == HtmlResourceType.Style))
                {
                    var resourceStream  = _htmlHandler.GetResource(guid, resource);
                    var resourceContent = new StreamReader(resourceStream).ReadToEnd();

                    if (!string.IsNullOrEmpty(css))
                    {
                        css += " ";
                    }

                    css += resourceContent;
                }

                // wrap single image tags
                var match = Regex.Match(html, "^<img.+?src=[\"'](.+?)[\"'].*?>$", RegexOptions.IgnoreCase);
                if (match.Success)
                {
                    var src      = match.Groups[1].Value;
                    var pageData = documentInfo.Pages.Single(_ => _.Number == page.PageNumber);

                    css = ".grpdx .ie .doc-page {font-size:0;}";
                    if (documentInfo.DocumentType == DocumentTypeName.DIAGRAM)
                    {
                        html = string.Format("<div style='width:{0}px;height:{1}px;font-size:0'>" +
                                             "<img style='width:{0}px;height:{1}px;font-size:0' src='{2}'/>" +
                                             "</div>",
                                             600,
                                             800,
                                             src);
                    }
                    else
                    {
                        html = string.Format("<div style='width:{0}px;height:{1}px;font-size:0'>" +
                                             "<img style='width:{0}px;height:{1}px;font-size:0' src='{2}'/>" +
                                             "</div>",
                                             pageData.Width,
                                             pageData.Height,
                                             src);
                    }
                }

                //wrap svg tags
                if (html.StartsWith("<svg"))
                {
                    html = "<div>" + html + "</div>";
                }

                pageContents.Add(new HtmlPageContent(html, css));
            }

            return(pageContents);
        }
        private List <PageHtml> GetHtmlPages(string filePath, HtmlOptions htmlOptions, out List <string> cssList)
        {
            var htmlPages = _htmlHandler.GetPages(filePath, htmlOptions);

            cssList = new List <string>();
            foreach (var page in htmlPages)
            {
                var test = page.HtmlResources;
                var indexOfBodyOpenTag = page.HtmlContent.IndexOf("<body>", StringComparison.InvariantCultureIgnoreCase);
                if (indexOfBodyOpenTag > 0)
                {
                    page.HtmlContent = page.HtmlContent.Substring(indexOfBodyOpenTag + "<body>".Length);
                }

                var indexOfBodyCloseTag = page.HtmlContent.IndexOf("</body>", StringComparison.InvariantCultureIgnoreCase);
                if (indexOfBodyCloseTag > 0)
                {
                    page.HtmlContent = page.HtmlContent.Substring(0, indexOfBodyCloseTag);
                }
                if (Path.GetExtension(filePath) == ".msg")
                {
                    foreach (var resource in page.HtmlResources.Where(_ => _.ResourceType == HtmlResourceType.Image))
                    {
                        string imagePath = string.Format("resources\\page{0}\\{1}",
                                                         page.PageNumber, resource.ResourceName);

                        page.HtmlContent = page.HtmlContent.Replace(resource.ResourceName,
                                                                    string.Format("/document-viewer/GetResourceForHtml?documentPath={0}&pageNumber={1}&resourceName={2}",
                                                                                  filePath, page.PageNumber, resource.ResourceName));
                    }
                }
                foreach (var resource in page.HtmlResources.Where(_ => _.ResourceType == HtmlResourceType.Style))
                {
                    var cssStream = _htmlHandler.GetResource(filePath, resource);
                    var text      = new StreamReader(cssStream).ReadToEnd();

                    var needResave = false;
                    if (text.IndexOf("url(\"", StringComparison.Ordinal) >= 0 &&
                        text.IndexOf("url(\"/document-viewer/GetResourceForHtml?documentPath=", StringComparison.Ordinal) < 0)
                    {
                        needResave = true;
                        text       = text.Replace("url(\"",
                                                  string.Format("url(\"/document-viewer/GetResourceForHtml?documentPath={0}&pageNumber={1}&resourceName=",
                                                                filePath, page.PageNumber));
                    }

                    if (text.IndexOf("url('", StringComparison.Ordinal) >= 0 &&
                        text.IndexOf("url('/document-viewer/GetResourceForHtml?documentPath=", StringComparison.Ordinal) < 0)
                    {
                        needResave = true;
                        text       = text.Replace("url('",
                                                  string.Format(
                                                      "url('/document-viewer/GetResourceForHtml?documentPath={0}&pageNumber={1}&resourceName=",
                                                      filePath, page.PageNumber));
                    }
                    // update path to image resource


                    cssList.Add(text);

                    if (needResave)
                    {
                        var fullPath = Path.Combine(_tempPath, filePath.Replace('.', '_'), "html", "resources",
                                                    string.Format("page{0}", page.PageNumber), resource.ResourceName);

                        System.IO.File.WriteAllText(fullPath, text);
                    }
                }

                List <string> cssClasses = Utils.GetCssClasses(page.HtmlContent);
                foreach (var cssClass in cssClasses)
                {
                    var newCssClass = string.Format("page-{0}-{1}", page.PageNumber, cssClass);

                    page.HtmlContent = page.HtmlContent.Replace(cssClass, newCssClass);
                    for (int i = 0; i < cssList.Count; i++)
                    {
                        cssList[i] = cssList[i].Replace(cssClass, newCssClass);
                    }
                }
            }
            return(htmlPages);
        }