Пример #1
0
        public static void OverlayImage(string mainImageUrl, string rootImageUrl, string dealerId)
        {
            var htmlToImageConverter = new HtmlToImage();

            htmlToImageConverter.SerialNumber = ConfigurationManager.AppSettings["PDFSerialNumber"];
            // set browser width
            htmlToImageConverter.BrowserWidth = 300;



            // set HTML Load timeout
            htmlToImageConverter.HtmlLoadedTimeout = 2;

            htmlToImageConverter.TransparentImage = false;

            System.Drawing.Image imageObject = null;

            string htmlCode =
                GenerateHtmlImageCode(mainImageUrl, dealerId);

            if (!String.IsNullOrEmpty(htmlCode))
            {
                imageObject = htmlToImageConverter.ConvertHtmlToImage(htmlCode, null)[0];

                imageObject.Save(rootImageUrl, System.Drawing.Imaging.ImageFormat.Jpeg);
            }
        }
Пример #2
0
        public static void GenerateRunTimePhysicalImageTesting()
        {
            const string physicalImagePath = @"C:\ImageWarehouse";

            try
            {
                var dirNormal = new DirectoryInfo(physicalImagePath);

                if (!dirNormal.Exists)
                {
                    dirNormal.Create();
                }


                var htmlToImageConverter = new HtmlToImage
                {
                    SerialNumber      = ConfigurationManager.AppSettings["PDFSerialNumber"],
                    BrowserWidth      = 570,
                    HtmlLoadedTimeout = 15,
                    TransparentImage  = false
                };

                const string snapshotfilePath = physicalImagePath + "/" + "Test.jpg";

                var imageObjectSnapshot =
                    htmlToImageConverter.ConvertUrlToImage("file:///C:/ExportFeed/craigslist/index.html")[0];

                imageObjectSnapshot.Save(snapshotfilePath, System.Drawing.Imaging.ImageFormat.Jpeg);
            }
            catch (Exception)
            {
            }
        }
Пример #3
0
        public byte[] convertHTMLToImage(string body)
        {
            // create the HTML to Image converter
            HtmlToImage htmlToImageConverter = new HtmlToImage();

            // set a demo serial number
            htmlToImageConverter.SerialNumber = "YCgJMTAE-BiwJAhIB-EhlWTlBA-UEBRQFBA-U1FOUVJO-WVlZWQ==";
            //// set browser width
            //htmlToImageConverter.BrowserWidth = int.Parse(textBoxBrowserWidth.Text);

            //// set browser height if specified, otherwise use the default
            //if (textBoxBrowserHeight.Text.Length > 0)
            //    htmlToImageConverter.BrowserHeight = int.Parse(textBoxBrowserHeight.Text);

            //// set HTML Load timeout
            //htmlToImageConverter.HtmlLoadedTimeout = int.Parse(textBoxLoadHtmlTimeout.Text);

            // set whether the resulted image is transparent (has effect only when the output format is PNG)
            htmlToImageConverter.TransparentImage = false;

            // convert to image
            System.Drawing.Image imageObject = null;

            var imageBuffer = htmlToImageConverter.ConvertHtmlToMemory(body, System.Web.HttpContext.Current.Server.MapPath("~/Reports/22.html"));

            // byte[] imageBuffer = GetImageBuffer(imageObject);

            return(imageBuffer);
        }
    public Model_Template model_InsertEmailEelement(Model_Template el)
    {
        int      ret      = 0;
        DateTime d        = DatetimeHelper._UTCNow();
        string   filename = d.ToString("ddmmyyyyhhmmss") + ".jpg";

        using (SqlConnection cn = new SqlConnection(this.ConnectionString))
        {
            SqlCommand cmd = new SqlCommand(@"INSERT INTO Template (EID,CreatedDate,CreateBy,Title,Description,DemoPath,DemoFileName)
                        VALUES(@EID,@CreatedDate,@CreateBy,@Title,@Description,@DemoPath,@DemoFileName) ; SET @TID = SCOPE_IDENTITY(); ", cn);
            cmd.Parameters.Add("@EID", SqlDbType.NVarChar).Value = el.EID;
            cmd.Parameters.Add("@CreatedDate", SqlDbType.SmallDateTime).Value = el.CreatedDate;
            cmd.Parameters.Add("@CreateBy", SqlDbType.NVarChar).Value         = el.CreateBy;
            cmd.Parameters.Add("@Title", SqlDbType.NVarChar).Value            = el.Title;
            cmd.Parameters.Add("@Description", SqlDbType.NVarChar).Value      = el.Description;
            cmd.Parameters.Add("@DemoPath", SqlDbType.NVarChar).Value         = AppTools.TemplateMockPath();
            cmd.Parameters.Add("@DemoFileName", SqlDbType.NVarChar).Value     = filename;
            cmd.Parameters.Add("@TID", SqlDbType.Int).Direction = ParameterDirection.Output;
            cn.Open();


            if (ExecuteNonQuery(cmd) > 0)
            {
                ret = (int)cmd.Parameters["@TID"].Value;
                // string fullpath = AppTools.TemplateMockPath() + "test.png";
                HtmlToImage.ConvertHtmlToImage(AppTools.TemplateMockPath(), filename, el.EL.html);
            }

            el.DemoPath     = AppTools.TemplateMockPath();
            el.DemoFileName = filename;
            el.TID          = ret;
        }

        return(el);
    }
Пример #5
0
        public HttpResponseMessage GenerateImage([FromBody] Dictionary <string, string> data)
        {
            var content = data["Content"];
            int width;

            if (!int.TryParse(data["Width"], out width))
            {
                width = 1920;
            }
            ;

            var image = HtmlToImage.GenerateImage(UnicodeEncode(content), "png", width);

            var result = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new ByteArrayContent(image)
            };

            result.Content.Headers.ContentDisposition =
                new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
            {
                FileName = "image.png"
            };
            result.Content.Headers.ContentType =
                new MediaTypeHeaderValue("image/png");

            return(result);
        }
Пример #6
0
        public static byte[] DownloadContentAsImage(string url)
        {
            ImageFormat imageFormat  = ImageFormat.Jpeg;
            var         imgConverter = new HtmlToImage();

            imgConverter.WebPageWidth  = 430;
            imgConverter.WebPageHeight = 488;
            var image = imgConverter.ConvertUrl(url);

            return(image.ImageToByteArray());
        }
Пример #7
0
        public async Task Can_generate_image()
        {
            var options = new HtmlToImageOptions
            {
                ExectuionDirectory = new CustomDirectory(TestContext.CurrentContext.WorkDirectory)
            };

            using var htmlToImage = new HtmlToImage(options, NullLoggerFactory.Instance);

            var stream = await htmlToImage.CreateImageAsync("<html><body style=\"background-color: red\"></body></html>", 100, ImageFormat.Png);

            Assert.That(stream.Length, Is.GreaterThan(0));
        }
    public Model_Template model_UpdateEmailElement(Model_Template el)
    {
        using (SqlConnection cn = new SqlConnection(this.ConnectionString))
        {
            SqlCommand cmd = new SqlCommand("UPDATE Template SET Title = @Title WHERE  TID=@TID", cn);
            cmd.Parameters.Add("@TID", SqlDbType.Int).Value        = el.TID;
            cmd.Parameters.Add("@Title", SqlDbType.NVarChar).Value = el.Title;
            cn.Open();

            if (ExecuteNonQuery(cmd) > 0)
            {
                HtmlToImage.ConvertHtmlToImage(el.DemoPath, el.DemoFileName, el.EL.html);
            }
        }

        return(el);
    }
Пример #9
0
        public static MemoryStream OverlayImage(string mainImageUrl, DealerUser user)
        {
            var htmlToImageConverter = new HtmlToImage
            {
                SerialNumber      = ConfigurationManager.AppSettings["PDFSerialNumber"],
                BrowserWidth      = 300,
                HtmlLoadedTimeout = 2,
                TransparentImage  = false
            };

            var htmlCode =
                GenerateHtmlImageCode(mainImageUrl, user);

            if (!String.IsNullOrEmpty(htmlCode))
            {
                System.Drawing.Image imageObject = htmlToImageConverter.ConvertHtmlToImage(htmlCode, null)[0];
                var stream = new MemoryStream();
                imageObject.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
                stream.Position = 0;
                return(stream);
            }

            return(null);
        }
Пример #10
0
        public static ImageModel GenerateRunTimePhysicalImageForFullertonAutoSquare(WhitmanEntepriseMasterVehicleInfo vehicle, List <WhitmanEntepriseMasterVehicleInfo> squareRandom)
        {
            var imageModel = new ImageModel {
                PhysicalImageUrl = new List <string>()
            };

            var random = new Random();

            string[] carImage = vehicle.CarImageUrl.Split(new string[] { ",", "|" },
                                                          StringSplitOptions.RemoveEmptyEntries);

            var number = random.Next(4, 6);

            var count = 1;

            var physicalImagePath = @"C:\ImageWarehouse" + "\\" + vehicle.DealerId + "\\" + vehicle.Vin;

            try
            {
                var dirNormal = new DirectoryInfo(physicalImagePath);

                if (!dirNormal.Exists)
                {
                    dirNormal.Create();
                }


                var htmlToImageConverter = new HtmlToImage
                {
                    SerialNumber      = ConfigurationManager.AppSettings["PDFSerialNumber"],
                    BrowserWidth      = 570,
                    HtmlLoadedTimeout = 15,
                    TransparentImage  = false
                };


                //string square4FilePath = dirNormal + "\\" + vehicle.StockNumber + "-" + (count++);

                //if (squareRandom.Count >= 4)
                //{

                //    var imageObjectSquare =
                //        htmlToImageConverter.ConvertHtmlToImage(ComputerAccountHelper.GenerateHtmlImageCodeSquare4Pictures(squareRandom), null)[0];

                //    imageObjectSquare.Save(square4FilePath, System.Drawing.Imaging.ImageFormat.Jpeg);
                //}

                foreach (string tmp in carImage)
                {
                    string imageFileName = vehicle.StockNumber + "-" + count;

                    var imageObject = htmlToImageConverter.ConvertHtmlToImage(ComputerAccountHelper.GenerateHtmlImageCodeOverlayForFullerton(vehicle, tmp), null)[0];

                    string filePath = dirNormal + "\\" + imageFileName + ".jpg";

                    imageObject.Save(filePath, System.Drawing.Imaging.ImageFormat.Jpeg);

                    imageModel.PhysicalImageUrl.Add(filePath);

                    count++;

                    break;

                    //if (imageModel.PhysicalImageUrl.Count > number)
                    //    break;
                }


                foreach (var tmp in squareRandom)
                {
                    if (!String.IsNullOrEmpty(tmp.CarImageUrl))
                    {
                        string[] totalImage = tmp.CarImageUrl.Split(new[] { "|", "," }, StringSplitOptions.RemoveEmptyEntries);

                        string imageFileName = vehicle.StockNumber + "-" + count;

                        var imageObject = htmlToImageConverter.ConvertHtmlToImage(ComputerAccountHelper.GenerateHtmlImageCodeOverlayForFullerton(tmp, totalImage[0]), null)[0];

                        string filePath = dirNormal + "\\" + imageFileName + ".jpg";

                        imageObject.Save(filePath, System.Drawing.Imaging.ImageFormat.Jpeg);

                        imageModel.PhysicalImageUrl.Add(filePath);

                        count++;
                    }
                }

                //if (squareRandom.Count >= 4)
                //    imageModel.PhysicalImageUrl.Add(square4FilePath);
            }
            catch (Exception)
            {
            }
            return(imageModel);
        }
Пример #11
0
        public static ImageModel GenerateRunTimeImageBlobByComputerAccount(WhitmanEntepriseMasterVehicleInfo vehicle)
        {
            var imageModel = new ImageModel();

            try
            {
                WebsitesScreenshot.WebsitesScreenshot bottomObj = null;
                if (vehicle.DealerId != 17716 && vehicle.DealerId != 14853)
                {
                    var _Obj = new WebsitesScreenshot.WebsitesScreenshot(
                        ConfigurationManager.AppSettings["WebScreenShotSerialKey"].ToString
                            (CultureInfo.InvariantCulture));

                    bottomObj =
                        new WebsitesScreenshot.WebsitesScreenshot(
                            ConfigurationManager.AppSettings["WebScreenShotSerialKey"].ToString
                                (CultureInfo.InvariantCulture));


                    WebsitesScreenshot.WebsitesScreenshot.Result result;

                    WebsitesScreenshot.WebsitesScreenshot.Result bottomResult;

                    if (vehicle.DealerId == 113738 || vehicle.DealerId == 3738)
                    {
                        var firstImageString = ComputerAccountHelper.GenerateHtmlImageCodeForAudiByComputerAccount(
                            vehicle);

                        result =
                            _Obj.CaptureHTML("<html><body>" + firstImageString + "</body></html>");

                        var secondImageString = ComputerAccountHelper.GenerateHtmlImageCodeForSecondBottomImage(
                            vehicle);

                        if (!String.IsNullOrEmpty(secondImageString))
                        {
                            bottomResult =
                                bottomObj.CaptureHTML("<html><body>" + secondImageString + "</body></html>");
                        }
                        else
                        {
                            bottomResult = bottomObj.CaptureHTML("<html><body>" + firstImageString + "</body></html>");
                        }
                    }

                    else
                    {
                        var firstImageString = ComputerAccountHelper.GenerateHtmlImageCode(
                            vehicle);


                        result =
                            _Obj.CaptureHTML("<html><body>" +
                                             firstImageString + "</body></html>");

                        var secondImageString = ComputerAccountHelper.GenerateHtmlImageCodeForSecondBottomImage(
                            vehicle);


                        if (!String.IsNullOrEmpty(secondImageString))
                        {
                            bottomResult =
                                bottomObj.CaptureHTML("<html><body>" +
                                                      secondImageString + "</body></html>");
                        }
                        else
                        {
                            bottomResult = bottomObj.CaptureHTML("<html><body>" + firstImageString + "</body></html>");
                        }
                    }



                    if (result == WebsitesScreenshot.WebsitesScreenshot.Result.Captured &&
                        bottomResult == WebsitesScreenshot.WebsitesScreenshot.Result.Captured)
                    {
                        _Obj.ImageFormat = WebsitesScreenshot.
                                           WebsitesScreenshot.ImageFormats.JPG;

                        bottomObj.ImageFormat = WebsitesScreenshot.
                                                WebsitesScreenshot.ImageFormats.JPG;

                        _Obj.DelaySeconds = 10;

                        bottomObj.DelaySeconds = 10;


                        var _Image = _Obj.GetImage();

                        var _BottomImage = bottomObj.GetImage();

                        var stream = new MemoryStream();

                        var bottomStream = new MemoryStream();

                        _Image.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);

                        _BottomImage.Save(bottomStream, System.Drawing.Imaging.ImageFormat.Jpeg);

                        var bytes = stream.ToArray();

                        var bottombytes = bottomStream.ToArray();

                        imageModel.BottomImage = bottombytes;

                        imageModel.TopImage = bytes;

                        stream.Dispose();

                        stream.Close();

                        bottomStream.Dispose();

                        bottomStream.Close();

                        _Obj.Dispose();

                        bottomObj.Dispose();
                    }
                }
                else
                {
                    bottomObj =
                        new WebsitesScreenshot.WebsitesScreenshot(
                            System.Configuration.ConfigurationManager.AppSettings["WebScreenShotSerialKey"].ToString
                                (CultureInfo.InvariantCulture));

                    WebsitesScreenshot.WebsitesScreenshot.Result _BottomResult;

                    _BottomResult =
                        bottomObj.CaptureHTML("<html><body>" +
                                              ComputerAccountHelper.GenerateHtmlImageCodeForSecondBottomImage(
                                                  vehicle) + "</body></html>");

                    if (_BottomResult == WebsitesScreenshot.WebsitesScreenshot.Result.Captured)
                    {
                        bottomObj.ImageFormat = WebsitesScreenshot.
                                                WebsitesScreenshot.ImageFormats.JPG;

                        bottomObj.DelaySeconds = 5;


                        var bottomImage = bottomObj.GetImage();

                        var htmlToImageConverter = new HtmlToImage();

                        htmlToImageConverter.SerialNumber = ConfigurationManager.AppSettings["PDFSerialNumber"];
                        // set browser width
                        htmlToImageConverter.BrowserWidth = 1200;

                        // set HTML Load timeout
                        htmlToImageConverter.HtmlLoadedTimeout = 5;

                        // set whether the resulted image is transparent
                        htmlToImageConverter.TransparentImage = false;

                        System.Drawing.Image imageObject = null;

                        string htmlCode =
                            ComputerAccountHelper.GenerateHtmlImageCodeForCaliforniaBeemerByComputerAccount(vehicle);

                        imageObject = htmlToImageConverter.ConvertHtmlToImage(htmlCode, null)[0];

                        var stream = new MemoryStream();

                        var bottomStream = new MemoryStream();

                        imageObject.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);

                        bottomImage.Save(bottomStream, System.Drawing.Imaging.ImageFormat.Jpeg);

                        var bytes = stream.ToArray();


                        var bottombytes = bottomStream.ToArray();

                        imageModel.BottomImage = bottombytes;

                        imageModel.TopImage = bytes;

                        stream.Dispose();

                        stream.Close();

                        bottomStream.Dispose();

                        bottomStream.Close();

                        imageObject.Dispose();

                        bottomObj.Dispose();
                    }
                }
            }
            catch (Exception ex)
            {
                //string body = "Error = " + ex.Message + ex.Source + ex.InnerException + ex.TargetSite + ex.StackTrace +
                //             "**************************************************************************************" +
                //             _subMasterVehicleList.ElementAt(0).ListingId + "----" +
                //             _subMasterVehicleList.ElementAt(0).DealerId;

                //if (_subMasterVehicleList.Any())
                //    _subMasterVehicleList.RemoveAt(0);

                //timerPostAccount.Enabled = true;

                //return imageModel;
            }


            return(imageModel);
        }
        public ActionResult ConvertToImage(FormCollection collection)
        {
            m_formCollection = collection;

            // create the HTML to Image converter
            HtmlToImage htmlToImageConverter = new HtmlToImage();

            // set a demo serial number
            htmlToImageConverter.SerialNumber = "YCgJMTAE-BiwJAhIB-EhlWTlBA-UEBRQFBA-U1FOUVJO-WVlZWQ==";

            // set browser width
            htmlToImageConverter.BrowserWidth = int.Parse(collection["textBoxBrowserWidth"]);

            // set browser height if specified, otherwise use the default
            if (collection["textBoxBrowserHeight"].Length > 0)
            {
                htmlToImageConverter.BrowserHeight = int.Parse(collection["textBoxBrowserHeight"]);
            }

            // set HTML Load timeout
            htmlToImageConverter.HtmlLoadedTimeout = int.Parse(collection["textBoxLoadHtmlTimeout"]);

            // set whether the resulted image is transparent (has effect only when the output format is PNG)
            htmlToImageConverter.TransparentImage = (collection["dropDownListImageFormat"] == "PNG") ?
                                                    collection["checkBoxTransparentImage"] != null : false;

            // set triggering mode; for WaitTime mode set the wait time before convert
            switch (collection["dropDownListTriggeringMode"])
            {
            case "Auto":
                htmlToImageConverter.TriggerMode = ConversionTriggerMode.Auto;
                break;

            case "WaitTime":
                htmlToImageConverter.TriggerMode       = ConversionTriggerMode.WaitTime;
                htmlToImageConverter.WaitBeforeConvert = int.Parse(collection["textBoxWaitTime"]);
                break;

            case "Manual":
                htmlToImageConverter.TriggerMode = ConversionTriggerMode.Manual;
                break;

            default:
                htmlToImageConverter.TriggerMode = ConversionTriggerMode.Auto;
                break;
            }

            // convert to image
            System.Drawing.Image imageObject = null;
            string imageFormatName           = collection["dropDownListImageFormat"].ToLower();
            string imageFileName             = String.Format("HtmlToImage.{0}", imageFormatName);

            if (collection["UrlOrHtmlCode"] == "radioButtonConvertUrl")
            {
                // convert URL
                string url = collection["textBoxUrl"];

                imageObject = htmlToImageConverter.ConvertUrlToImage(url)[0];
            }
            else
            {
                // convert HTML code
                string htmlCode = collection["textBoxHtmlCode"];
                string baseUrl  = collection["textBoxBaseUrl"];

                imageObject = htmlToImageConverter.ConvertHtmlToImage(htmlCode, baseUrl)[0];
            }

            // get the image buffer in the selected image format
            byte[] imageBuffer = GetImageBuffer(imageObject);

            // the image object rturned by converter can be disposed
            imageObject.Dispose();

            // inform the browser about the binary data format
            string mimeType = imageFormatName == "jpg" ? "jpeg" : imageFormatName;

            FileResult fileResult = new FileContentResult(imageBuffer, "image/" + mimeType);

            fileResult.FileDownloadName = imageFileName;

            return(fileResult);
        }
Пример #13
0
    public void CopyAppPage(Hashtable State, string page_to_copy, string new_page_name)
    {
        XmlDocument xmlDoc = GetStagingAppXml(State);

        XmlNode prev_page_name_node = xmlDoc.SelectSingleNode("//pages/page/name[.  ='" + page_to_copy + "']");
        if (prev_page_name_node != null)
        {
            XmlNode prev_page_node = prev_page_name_node.ParentNode;
            XmlNode new_page_node = prev_page_node.CloneNode(true);

            //modify prev node with new names
            new_page_node.SelectSingleNode("name").InnerText = new_page_name;
            new_page_node.SelectSingleNode("order").InnerText =  GetNextPageOrder(xmlDoc);

            XmlNodeList fields = new_page_node.SelectSingleNode("fields").ChildNodes;
            foreach (XmlNode field in fields)
            {
                string id = field.SelectSingleNode("id").InnerText;
                field.SelectSingleNode("id").InnerText = new_page_name.Replace(" ","_") + "_" + id;
                if(field.Name == "table")
                {
                  XmlNodeList table_field_names = field.SelectNodes("table_fields/table_field/name");
                  foreach (XmlNode table_field_name in table_field_names)
                  {
                      string name = table_field_name.InnerText;
                      table_field_name.InnerText = new_page_name.Replace(" ", "_") + "_" + name;
                  }
                }
                else if (field.Name == "picker")
                {
                    XmlNodeList picker_field_names = field.SelectNodes("picker_fields/picker_field/name");
                    foreach (XmlNode picker_field_name in picker_field_names)
                    {
                        string name = picker_field_name.InnerText;
                        picker_field_name.InnerText = new_page_name.Replace(" ", "_") + "_" + name;
                    }
                }
            }

            prev_page_node.ParentNode.AppendChild(new_page_node);

            Util util = new Util();
            State["AppXmlDoc"] = xmlDoc;
            util.UpdateStagingAppXml(State);

            HtmlToImage thumb = new HtmlToImage();
            string page_image_url = thumb.ConvertToImageLink(State, new_page_name, State["BackgroundHtml"].ToString());
            if (page_image_url != null)
                util.SaveAppPageImage(State, page_image_url);

        }
    }
Пример #14
0
    public void DeleteAppPageImage(Hashtable State, string page_name)
    {
        DB db = new DB();
        string application_id = GetAppID(State);

        //delete image file
        string sql = "SELECT page_image_url FROM application_pages WHERE application_id='" + application_id +
            "' AND page_name='" + page_name + "'";
        string page_image_url = db.ViziAppsExecuteScalar(State, sql);
        if (page_image_url != null && page_image_url.Length > 0 && page_image_url != "../images/page_not_saved.jpg")
        {
            HtmlToImage util = new HtmlToImage();
            util.DeleteImageFromUrl(State, page_image_url);
        }

        //delete DB entry
        sql = "DELETE FROM application_pages WHERE application_id='" + application_id + "' AND page_name='" + page_name + "'";
        db.ViziAppsExecuteNonQuery(State, sql);

        db.CloseViziAppsDatabase(State);
    }
Пример #15
0
    public void SavePageImage(Hashtable State, string page_name, string html)
    {
        //save half size image of page
        HtmlToImage thumb = new HtmlToImage();
        if (State["SelectedDeviceType"].ToString() == Constants.IPAD ||
            State["SelectedDeviceType"].ToString() == Constants.ANDROID_TABLET)
        {
            if (State["BackgroundColor"] == null)
                State["BackgroundColor"] = "#cccccc";

            string background_color_div_prefix = "<div style=\"width:" + Constants.IPAD_SPLASH_PORTRAIT_WIDTH_S + "px;height:" + Constants.IPAD_SPLASH_PORTRAIT_HEIGHT_S + "px;vertical-align:top;background-color:" + State["BackgroundColor"].ToString() + "\" >";
            if (State["SelectedDeviceType"].ToString() == Constants.ANDROID_TABLET)
                background_color_div_prefix = "<div style=\"width:" + Constants.ANDROID_TABLET_PORTRAIT_WIDTH_S + "px;height:" + Constants.ANDROID_TABLET_SPLASH_PORTRAIT_HEIGHT_S + "px;vertical-align:top;background-color:" + State["BackgroundColor"].ToString() + "\" >";
            string background_color_div_suffix = "</div>";
            html = background_color_div_prefix + html + background_color_div_suffix;
        }
        string page_image_url = thumb.ConvertToImageLink(State, page_name, html);
        if (page_image_url != null)
        {
            SaveAppPageImage(State, page_image_url);
        }
    }
Пример #16
0
        internal void GenerateToImage()
        {
            //these fields is not change with each student
            string htmlTable              = "";
            string studyAvg               = dt.Rows[0]["KL HT tb"].ToString();
            string studentClass           = dt.Rows[0]["Lớp"].ToString();
            string studyCompletedLastWeek = dt.Rows[0]["KL học tập đã TH tuần trước"].ToString();
            string timeRemain             = dt.Rows[0]["thời gian còn lại"].ToString();

            studyAvg = BeautiNumber(studyAvg, "{0:0.0}");
            studyCompletedLastWeek = BeautiNumber(studyCompletedLastWeek, "{0:0.0}");
            timeRemain             = BeautiNumber(timeRemain, "{0:0}");

            foreach (DataRow row in dt.Rows)
            {
                try
                {
                    string course       = row["Môn"].ToString();
                    string exam         = row["Exam"].ToString();
                    string quest        = row["% ques"].ToString();
                    string quiz         = row["% quiz"].ToString();
                    string asm          = row["% asm"].ToString();
                    string lab          = row["%Lab"].ToString();
                    string courseStatus = row["Trạng thái môn"].ToString();


                    courseStatus = BeautiNumber(courseStatus, "{0:0.0}");
                    lab          = BeautiNumber(lab, "{0:0.0%}");
                    quest        = BeautiNumber(quest, "{0:0.0%}");
                    quiz         = BeautiNumber(quiz, "{0:0.0%}");
                    asm          = BeautiNumber(asm, "{0:0.0%}");

                    htmlTable += $@"<tr>
                        <td>{course}</td>
                        <td>{courseStatus}</td>
                        <td>{quest}</td>
                        <td>{quiz}</td>
                        <td>{lab}</td>
                        <td>{asm}</td>
                        <td>{exam}</td>
                    </tr>";
                }
                catch (Exception e)
                {
                    //MessageBox.Show(e.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    throw e;
                }
            }

            string width = "";
            var    weeks = Convert.ToInt16(ConfigurationManager.AppSettings[$"{certificate}"]);

            if (string.IsNullOrEmpty(timeRemain) || timeRemain.Equals("N/A"))
            {
                width = "0%";
            }
            else
            {
                width = Convert.ToDouble(timeRemain) / weeks * 100 + "%";
            }
            string[]    parameters  = { folder, reportedDate.ToString("dd/MM/yyyy"), studentName, studentId, timeRemain, weeks.ToString(), width, studyAvg, studyCompletedLastWeek, htmlTable };
            HtmlToImage htmlToImage = new HtmlToImage(850);

            string html = string.Format(contentHtml, parameters);
            Image  img  = htmlToImage.ConvertHtmlString(html);

            DirectoryInfo directory = new DirectoryInfo(Path.Combine(folderStoragePath, $"{studentClass}"));

            if (!directory.Exists)
            {
                directory.Create();
            }

            FileStream stream = File.Open(Path.Combine(folderStoragePath, $"{studentClass}/{studentId} - {studentName}.png"), FileMode.Create);

            img.Save(stream, ImageFormat.Png);
            stream.Close();
        }
Пример #17
0
        public void Path_IsCorrect()
        {
            var urlToImage = new HtmlToImage();

            Assert.AreEqual("html/image", urlToImage.Path);
        }
Пример #18
0
        protected void buttonConvertToImage_Click(object sender, EventArgs e)
        {
            // create the HTML to Image converter
            HtmlToImage htmlToImageConverter = new HtmlToImage();

            // set a demo serial number
            htmlToImageConverter.SerialNumber = "YCgJMTAE-BiwJAhIB-EhlWTlBA-UEBRQFBA-U1FOUVJO-WVlZWQ==";

            // set browser width
            htmlToImageConverter.BrowserWidth = int.Parse(textBoxBrowserWidth.Text);

            // set browser height if specified, otherwise use the default
            if (textBoxBrowserHeight.Text.Length > 0)
            {
                htmlToImageConverter.BrowserHeight = int.Parse(textBoxBrowserHeight.Text);
            }

            // set HTML Load timeout
            htmlToImageConverter.HtmlLoadedTimeout = int.Parse(textBoxLoadHtmlTimeout.Text);

            // set whether the resulted image is transparent (has effect only when the output format is PNG)
            htmlToImageConverter.TransparentImage = (dropDownListImageFormat.SelectedValue == "PNG") ?
                                                    checkBoxTransparentImage.Checked : false;

            // set triggering mode; for WaitTime mode set the wait time before convert
            switch (dropDownListTriggeringMode.SelectedValue)
            {
            case "Auto":
                htmlToImageConverter.TriggerMode = ConversionTriggerMode.Auto;
                break;

            case "WaitTime":
                htmlToImageConverter.TriggerMode       = ConversionTriggerMode.WaitTime;
                htmlToImageConverter.WaitBeforeConvert = int.Parse(textBoxWaitTime.Text);
                break;

            case "Manual":
                htmlToImageConverter.TriggerMode = ConversionTriggerMode.Manual;
                break;

            default:
                htmlToImageConverter.TriggerMode = ConversionTriggerMode.Auto;
                break;
            }

            // convert to image
            System.Drawing.Image imageObject = null;
            string imageFormatName           = dropDownListImageFormat.SelectedValue.ToLower();
            string imageFileName             = String.Format("HtmlToImage.{0}", imageFormatName);

            if (radioButtonConvertUrl.Checked)
            {
                // convert URL
                string url = textBoxUrl.Text;

                imageObject = htmlToImageConverter.ConvertUrlToImage(url)[0];
            }
            else
            {
                // convert HTML code
                string htmlCode = textBoxHtmlCode.Text;
                string baseUrl  = textBoxBaseUrl.Text;

                imageObject = htmlToImageConverter.ConvertHtmlToImage(htmlCode, baseUrl)[0];
            }

            // get the image buffer in the selected image format
            byte[] imageBuffer = GetImageBuffer(imageObject);

            // the image object rturned by converter can be disposed
            imageObject.Dispose();

            // inform the browser about the binary data format
            string mimeType = imageFormatName == "jpg" ? "jpeg" : imageFormatName;

            HttpContext.Current.Response.AddHeader("Content-Type", "image/" + mimeType);

            // let the browser know how to open the image and the image name
            HttpContext.Current.Response.AddHeader("Content-Disposition",
                                                   String.Format("attachment; filename={0}; size={1}", imageFileName, imageBuffer.Length.ToString()));

            // write the image buffer to HTTP response
            HttpContext.Current.Response.BinaryWrite(imageBuffer);

            // call End() method of HTTP response to stop ASP.NET page processing
            HttpContext.Current.Response.End();
        }
Пример #19
0
        public static ImageModel GenerateRunTimeImageBlobByComputerAccount(WhitmanEntepriseMasterVehicleInfo vehicle)
        {
            var imageModel = new ImageModel();

            WebsitesScreenshot.WebsitesScreenshot _Obj = null;

            WebsitesScreenshot.WebsitesScreenshot _BottomObj = null;

            try
            {
                if (vehicle.DealerId != 18498)
                {
                    _Obj =
                        new WebsitesScreenshot.WebsitesScreenshot(
                            System.Configuration.ConfigurationManager.AppSettings["WebScreenShotSerialKey"].ToString
                                (CultureInfo.InvariantCulture));

                    _BottomObj =
                        new WebsitesScreenshot.WebsitesScreenshot(
                            System.Configuration.ConfigurationManager.AppSettings["WebScreenShotSerialKey"].ToString
                                (CultureInfo.InvariantCulture));

                    //Dynamic FTP ACCOUNT



                    WebsitesScreenshot.WebsitesScreenshot.Result _Result;

                    WebsitesScreenshot.WebsitesScreenshot.Result _BottomResult;

                    if (vehicle.DealerId == 113738 || vehicle.DealerId == 3738)
                    {
                        var firstImageString = ComputerAccountHelper.GenerateHtmlImageCodeForAudiByComputerAccount(
                            vehicle);

                        _Result =
                            _Obj.CaptureHTML("<html><body>" + firstImageString + "</body></html>");

                        var secondImageString = ComputerAccountHelper.GenerateHtmlImageCodeForSecondBottomImage(
                            vehicle);

                        if (!String.IsNullOrEmpty(secondImageString))
                        {
                            _BottomResult =
                                _BottomObj.CaptureHTML("<html><body>" + secondImageString + "</body></html>");
                        }
                        else
                        {
                            _BottomResult = _BottomObj.CaptureHTML("<html><body>" + firstImageString + "</body></html>");
                        }
                    }

                    else
                    {
                        var firstImageString = ComputerAccountHelper.GenerateHTMLImageCode(
                            vehicle);


                        _Result =
                            _Obj.CaptureHTML("<html><body>" +
                                             firstImageString + "</body></html>");

                        var secondImageString = ComputerAccountHelper.GenerateHtmlImageCodeForSecondBottomImage(
                            vehicle);


                        if (!String.IsNullOrEmpty(secondImageString))
                        {
                            _BottomResult =
                                _BottomObj.CaptureHTML("<html><body>" +
                                                       secondImageString + "</body></html>");
                        }
                        else
                        {
                            _BottomResult = _BottomObj.CaptureHTML("<html><body>" + firstImageString + "</body></html>");
                        }
                    }



                    if (_Result == WebsitesScreenshot.WebsitesScreenshot.Result.Captured &&
                        _BottomResult == WebsitesScreenshot.WebsitesScreenshot.Result.Captured)
                    {
                        _Obj.ImageFormat = WebsitesScreenshot.
                                           WebsitesScreenshot.ImageFormats.JPG;

                        _BottomObj.ImageFormat = WebsitesScreenshot.
                                                 WebsitesScreenshot.ImageFormats.JPG;

                        _Obj.DelaySeconds = 10;

                        _BottomObj.DelaySeconds = 10;


                        var _Image = _Obj.GetImage();

                        var _BottomImage = _BottomObj.GetImage();

                        var stream = new MemoryStream();

                        var bottomStream = new MemoryStream();

                        _Image.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);

                        _BottomImage.Save(bottomStream, System.Drawing.Imaging.ImageFormat.Jpeg);

                        var bytes = stream.ToArray();

                        var bottombytes = bottomStream.ToArray();

                        imageModel.BottomImage = bottombytes;

                        imageModel.TopImage = bytes;

                        stream.Dispose();

                        stream.Close();

                        bottomStream.Dispose();

                        bottomStream.Close();

                        _Obj.Dispose();

                        _BottomObj.Dispose();
                    }
                }
                else
                {
                    _BottomObj =
                        new WebsitesScreenshot.WebsitesScreenshot(
                            System.Configuration.ConfigurationManager.AppSettings["WebScreenShotSerialKey"].ToString
                                (CultureInfo.InvariantCulture));

                    WebsitesScreenshot.WebsitesScreenshot.Result _BottomResult;

                    _BottomResult =
                        _BottomObj.CaptureHTML("<html><body>" +
                                               ComputerAccountHelper.GenerateHtmlImageCodeForSecondBottomImage(
                                                   vehicle) + "</body></html>");

                    if (_BottomResult == WebsitesScreenshot.WebsitesScreenshot.Result.Captured)
                    {
                        _BottomObj.ImageFormat = WebsitesScreenshot.
                                                 WebsitesScreenshot.ImageFormats.JPG;

                        _BottomObj.DelaySeconds = 5;


                        var _BottomImage = _BottomObj.GetImage();

                        var htmlToImageConverter = new HtmlToImage();

                        htmlToImageConverter.SerialNumber = ConfigurationManager.AppSettings["PDFSerialNumber"];
                        // set browser width
                        htmlToImageConverter.BrowserWidth = 1200;

                        // set HTML Load timeout
                        htmlToImageConverter.HtmlLoadedTimeout = 5;

                        // set whether the resulted image is transparent
                        htmlToImageConverter.TransparentImage = false;

                        System.Drawing.Image imageObject = null;

                        string htmlCode =
                            ComputerAccountHelper.GenerateHtmlImageCodeForCaliforniaBeemerByComputerAccount(vehicle);

                        imageObject = htmlToImageConverter.ConvertHtmlToImage(htmlCode, null)[0];

                        var stream = new MemoryStream();

                        var bottomStream = new MemoryStream();

                        imageObject.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);

                        _BottomImage.Save(bottomStream, System.Drawing.Imaging.ImageFormat.Jpeg);

                        var bytes = stream.ToArray();


                        var bottombytes = bottomStream.ToArray();

                        imageModel.BottomImage = bottombytes;

                        imageModel.TopImage = bytes;

                        stream.Dispose();

                        stream.Close();

                        bottomStream.Dispose();

                        bottomStream.Close();

                        imageObject.Dispose();

                        _BottomObj.Dispose();
                    }
                }
            }
            catch (Exception ex)
            {
                imageModel.BottomImage = null;
                imageModel.TopImage    = null;
                return(imageModel);
            }


            return(imageModel);
        }
Пример #20
0
 /// <summary>
 ///     This endpoints lets you to convert any html to an image.
 /// </summary>
 /// <param name="htmlToImage">Html to Image parameters.</param>
 /// <returns>Returns a ReturnResponse type</returns>
 public Task <ReturnResponse> HtmlToImage(HtmlToImage htmlToImage)
 {
     return(SendRequest(htmlToImage));
 }