Ejemplo n.º 1
0
        protected void CreateImageFileWithBarcode(string scriptsHTML, string fileName, string code)
        {
            try
            {
                System.Drawing.PointF point      = new System.Drawing.PointF(0, 0);
                System.Drawing.PointF _subPpoint = new System.Drawing.PointF(0, 0);
                System.Drawing.Image  _image     = System.Drawing.Image.FromFile(Server.MapPath("../Gallery/Contents/ticket.PNG"));

                _image = _image.GetThumbnailImage(755, 415, null, IntPtr.Zero);
                HtmlRender.RenderToImage(_image, scriptsHTML, point);

                System.Drawing.Image _barcode = CodeGenerator.CreateBarCode(code);
                //System.Drawing.Image _barcode = Code.CreateQrCode(code, 200);
                //_barcode = _barcode.GetThumbnailImage(150, 150, null, IntPtr.Zero);
                _barcode = _barcode.GetThumbnailImage(200, 70, null, IntPtr.Zero);

                HtmlRender.RenderToImage(_barcode, string.Empty, _subPpoint);
                _barcode.RotateFlip(RotateFlipType.Rotate270FlipX);


                Bitmap bitmap = new Bitmap(755, 415);
                using (Graphics graphics = Graphics.FromImage(bitmap))
                {
                    graphics.DrawImage(_image, 0, 0);
                    graphics.DrawImage(_barcode, 630, 115);
                    //graphics.DrawImage(_barcode, 550, 150);
                    bitmap.Save(Server.MapPath("../Gallery/Ticket/" + fileName + ".PNG"), System.Drawing.Imaging.ImageFormat.Png);
                }
            }
            catch (Exception ex)
            {
                string a = ex.Message;
            }
        }
Ejemplo n.º 2
0
        private void GenerateImage()
        {
            if (_backgroundColorTSB.SelectedItem != null && _textRenderingHintTSCB.SelectedItem != null)
            {
                var backgroundColor = Color.FromName(_backgroundColorTSB.SelectedItem.ToString());
                TextRenderingHint textRenderingHint = (TextRenderingHint)Enum.Parse(typeof(TextRenderingHint), _textRenderingHintTSCB.SelectedItem.ToString());

                Image img;
                if (_useGdiPlusTSB.Checked || HtmlRenderingHelper.IsRunningOnMono())
                {
                    img = HtmlRender.RenderToImageGdiPlus(_html, _pictureBox.ClientSize, textRenderingHint, null, DemoUtils.OnStylesheetLoad, HtmlRenderingHelper.OnImageLoad);
                }
                else
                {
                    EventHandler <HtmlStylesheetLoadEventArgs> stylesheetLoad = DemoUtils.OnStylesheetLoad;
                    EventHandler <HtmlImageLoadEventArgs>      imageLoad      = HtmlRenderingHelper.OnImageLoad;
                    var objects = new object[] { _html, _pictureBox.ClientSize, backgroundColor, null, stylesheetLoad, imageLoad };

                    var types = new[] { typeof(String), typeof(Size), typeof(Color), typeof(CssData), typeof(EventHandler <HtmlStylesheetLoadEventArgs>), typeof(EventHandler <HtmlImageLoadEventArgs>) };
                    var m     = typeof(HtmlRender).GetMethod("RenderToImage", BindingFlags.InvokeMethod | BindingFlags.Static | BindingFlags.Public, null, types, null);
                    img = (Image)m.Invoke(null, objects);
                }
                _pictureBox.Image = img;
            }
        }
Ejemplo n.º 3
0
        public string Render(string md)
        {
            var mdParser   = new Parser(md);
            var mdDocument = mdParser.Parse();

            return(HtmlRender.RenderDocument(mdDocument));
        }
Ejemplo n.º 4
0
        public void Calculation(ref int taskNumber, int k, double[] table1, double[] table2)
        {
            this.R = (double)N0 / N;
            for (int i = 0; i < k; i++)
            {
                this.R += (this.a[i] * (this.Ni[i] - 1)) / this.N;
            }
            Console.WriteLine("Вероятность безотказного выполнения программы (R): {0}",
                              Math.Round(this.R, 3));

            Console.Write("Нажмите 1, если требуется сохранить задачу...\n");
            string result = Console.ReadLine();

            if (result == "1")
            {
                taskNumber++;
                #region Создание изображения с таблицей
                string tableHTML = this.ConvertTableIntToTableHtml(table1, table2, "Кол-во ошибок и их вероятность их появления", "Ошибка №");
                string html      = String.Format(KorkorenMethodDataGenerator.HtmlTemplate, tableHTML);

                HtmlRender htmlRender = new HtmlRender();
                string     fileName   = String.Format("{0}_{1}.png",
                                                      taskNumber,
                                                      Math.Round(this.R, 3));

                htmlRender.SaveHtmlAsJPGAsync(html, fileName, 1000, 160,
                                              ar => { Console.WriteLine("Файл {0} сохранён\n", fileName); });
                #endregion
                System.Threading.Thread.Sleep(300);
            }
        }
Ejemplo n.º 5
0
        /// <summary>
        /// 根据文件将html转换为image
        /// SubmissionAndApprovalRecords用recordDetails
        /// SubmissionApprovalRecord用records
        /// </summary>
        /// <param name="templateType"></param>
        /// <param name="values"></param>
        /// <param name="records"></param>
        /// <param name="recordDetails"></param>
        /// <returns></returns>
        public static System.Drawing.Image HtmlConvertToImageObject(HtmlTempalteType templateType, Dictionary <string, string> values, List <SubmissionApprovalRecord> records, List <SubmissionApprovalRecord> recordDetails)
        {
            var html = GenerateHtmlFromTemplate(templateType, values, records, recordDetails);

            System.Drawing.Image image = HtmlRender.RenderToImage(html);
            return(image);
        }
Ejemplo n.º 6
0
        public void GenerateTestMethodTask(ref int taskNumber)
        {
            int[,] table = this.GenerateTableInt(5, 10);
            this.WriteTableInt(table, "Сгенерированная табличка");

            TestMethod testMethod = new TestMethod();
            int        calcResult = testMethod.Calculate(table);

            this.WriteInt("Z", calcResult);

            Console.Write("Нажмите 1, если требуется сохранить задачу...  ");
            string result = Console.ReadLine();

            if (result == "1")
            {
                taskNumber++;

                string tableHTML = this.ConvertTableIntToTableHtml(table, "Taблица 1", "Столбец", "Строка");
                string html      = String.Format(TestMethodDataGenerator.HtmlTemplate, tableHTML);

                HtmlRender htmlRender = new HtmlRender();
                string     fileName   = String.Format("{0}_{1}.png", taskNumber, calcResult);

                htmlRender.SaveHtmlAsJPGAsync(html, fileName, 1000, 400,
                                              ar => { Console.WriteLine("Файл {0} сохранён", fileName); });
            }
        }
Ejemplo n.º 7
0
        public HtmlScreenButtonElement(HtmlElement argElement,
                                       HtmlRender argParent)
            : base(argElement, argParent)
        {
            string typeAttri = argElement.GetAttribute("type");

            if (UIServiceCfgDefines.s_checkbox.Equals(typeAttri, StringComparison.OrdinalIgnoreCase) ||
                UIServiceCfgDefines.s_radio.Equals(typeAttri, StringComparison.OrdinalIgnoreCase))
            {
                if (argElement.TagName.Equals("input", StringComparison.OrdinalIgnoreCase))
                {
                    m_iButtonElement = (IHTMLOptionButtonElement)argElement.DomElement;
                }
                m_isStateButton = true;
            }

            if (typeAttri.Equals(UIServiceCfgDefines.s_checkbox, StringComparison.OrdinalIgnoreCase) ||
                typeAttri.Equals(UIServiceCfgDefines.s_radio, StringComparison.OrdinalIgnoreCase) ||
                typeAttri.Equals(UIServiceCfgDefines.s_submitButton, StringComparison.OrdinalIgnoreCase) ||
                typeAttri.Equals(UIServiceCfgDefines.s_resetButton, StringComparison.OrdinalIgnoreCase))
            {
                if (argElement.TagName.Equals("input", StringComparison.OrdinalIgnoreCase))
                {
                    m_ihostedElement.Click += m_ihostedElement_Click;
                }
            }

            string maskChar = argElement.GetAttribute("maskChar");

            if (!string.IsNullOrWhiteSpace(maskChar))
            {
                m_maskChar = maskChar;
            }
        }
Ejemplo n.º 8
0
        public ActionResult DrawInvoice(InvoiceQueryViewModel viewModel)
        {
            //HtmlRender.RenderToImage
            //ViewBag.ViewModel = viewModel;
            //ViewResult result = (ViewResult)PrintInvoice(viewModel);
            //result.ViewName = "CanvasDrawInvoice";
            //return result;
            String viewUrl = Settings.Default.HostDomain + VirtualPathUtility.ToAbsolute("~/Invoice/CanvasPrintInvoice") + "?" + Request.Params["QUERY_STRING"];

            using (WebClient client = new WebClient())
            {
                client.Encoding = Encoding.UTF8;
                String data = client.DownloadString(viewUrl);
                using (Image image = HtmlRender.RenderToImage(data))
                {
                    //using (Bitmap bmp = new Bitmap(image, new Size(image.Size.Width * 9 / 10, image.Size.Height * 9 / 10)))
                    //{
                    Response.Clear();
                    Response.ContentType = "image/Png";
                    image.Save(Response.OutputStream, ImageFormat.Png);
                    //}
                    //Response.End();
                }
            }

            return(new EmptyResult());
        }
        protected void CreateCertificate(string scriptsHTML, string fileName)
        {
            System.Drawing.PointF point      = new System.Drawing.PointF(-50, 50);
            System.Drawing.PointF _subPpoint = new System.Drawing.PointF(0, 0);
            System.Drawing.Image  _image     = System.Drawing.Image.FromFile(Server.MapPath("../Gallery/Contents/certificate.PNG"));

            //Before here define text as image
            _image = _image.GetThumbnailImage(5000, 3533, null, IntPtr.Zero);
            HtmlRender.RenderToImage(_image, scriptsHTML, point);

            //System.Drawing.Image _barcode = CodeGenerator.CreateBarCode(fileName);
            System.Drawing.Image _barcode = Code.CreateQrCode(fileName, 445);
            _barcode = _barcode.GetThumbnailImage(425, 425, null, IntPtr.Zero);
            //_barcode = _barcode.GetThumbnailImage(200, 70, null, IntPtr.Zero);

            HtmlRender.RenderToImage(_barcode, string.Empty, _subPpoint);
            //_barcode.RotateFlip(RotateFlipType.Rotate270FlipX);

            Bitmap bitmap = new Bitmap(5000, 3533);

            using (Graphics graphics = Graphics.FromImage(bitmap))
            {
                graphics.DrawImage(_image, 0, 0);
                graphics.DrawImage(_barcode, 4350, 2900);
                bitmap.Save(Server.MapPath("../Gallery/Certificate/" + fileName + ".PNG"), System.Drawing.Imaging.ImageFormat.Png);
            }
        }
Ejemplo n.º 10
0
 private void GenerateImage()
 {
     if (_imageBoxBorder.RenderSize.Width > 0 && _imageBoxBorder.RenderSize.Height > 0)
     {
         _generatedImage  = HtmlRender.RenderToImage(_html, _imageBoxBorder.RenderSize, null, DemoUtils.OnStylesheetLoad, HtmlRenderingHelper.OnImageLoad);
         _imageBox.Source = _generatedImage;
     }
 }
Ejemplo n.º 11
0
        public HtmlScreenElementBase(HtmlElement argElement,
                                     HtmlRender argParent)
        {
            Debug.Assert(null != argElement && null != argParent);

            m_ihostedElement = argElement;
            m_parent         = argParent;
        }
Ejemplo n.º 12
0
        public void ConvertViaHTMLRenderer()
        {
            Bitmap   bitmap = new Bitmap((Int32)ActualWidth, (Int32)ActualHeight, PixelFormat.Format32bppArgb);
            CssData  d      = CssData.Parse("body {font-family:'Times New Roman';font-size: 12pt}");
            Graphics g      = Graphics.FromImage(bitmap);

            g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit;
            HtmlRender.Render(g, s, new PointF(), new SizeF(), d);
        }
Ejemplo n.º 13
0
        public static void SaveHtmlToImage(string html, string imageName)
        {
            Image image = HtmlRender.RenderToImage(html);

            //Image resizedImage = image.GetThumbnailImage(600, 10000, null, IntPtr.Zero);
            //resizedImage.Save(imageName, ImageFormat.Png);

            image.Save(imageName, ImageFormat.Png);
        }
Ejemplo n.º 14
0
        public override void PrintTemplate(string dest, string template)
        {
            Image image = HtmlRender.RenderToImage(template);

            using (var file = new FileStream(dest, FileMode.Create))
            {
                image.Save(file, ImageFormat.Png);
            }
        }
Ejemplo n.º 15
0
 /// <summary>
 /// Load custom fonts to be used by renderer HTMLs
 /// </summary>
 private static void LoadCustomFonts()
 {
     // load custom font font into private fonts collection
     foreach (FontFamily fontFamily in Fonts.GetFontFamilies(new Uri("pack://application:,,,/"), "./fonts/"))
     {
         // add the fonts to renderer
         HtmlRender.AddFontFamily(fontFamily);
     }
 }
Ejemplo n.º 16
0
        private void button1_Click(object sender, EventArgs e)
        {
            Bitmap m_Bitmap = new Bitmap(400, 600);
            PointF point    = new PointF(0, 0);
            SizeF  maxSize  = new SizeF(500, 500);

            HtmlRender.Render(Graphics.FromImage(m_Bitmap), richTextBox1.Text, point, maxSize);

            m_Bitmap.Save(Application.StartupPath + @"Test.png", ImageFormat.Png);
        }
Ejemplo n.º 17
0
        private void AddHTMLImageToDataGridView(string htmlText)
        {
            int nNewRow = dataGridView1.Rows.Add();

            Image image = HtmlRender.RenderToImage("<b>hello</b> there");

            int nColCount = 0;

            dataGridView1.Rows[nNewRow].Cells[nColCount++].Value = image;
        }
Ejemplo n.º 18
0
        /// <summary>
        /// DIO圖片
        /// 網址:localhost:50471/img/wry?t=2018-1-1_0:0:0
        /// </summary>
        /// <param name="t"></param>
        /// <returns></returns>
        public ActionResult wry(String t)
        {
            if (t == null || t == "")
            {
                t = "2018-1-1";
            }


            String html = html_640_360;

            html = html.Replace("{url}", Server.MapPath("~/Image/wry.jpg"));


            try {
                //初始化時間
                t = t.Replace(" ", "-").Replace(":", "-").Replace("_", "-").Replace("/", "-").Replace(":", "-").Replace("\\", "-");
                t = t.Replace("--", "-").Replace("--", "-").Replace("--", "-");
                String[] tt   = t.Split('-');
                int[]    ar_d = { 2018, 1, 1, 0, 0, 0 };
                for (int i = 0; i < 6; i++)
                {
                    try {
                        ar_d[i] = Int32.Parse(tt[i]);
                    } catch { }
                }
                DateTime d = new DateTime(ar_d[0], ar_d[1], ar_d[2], ar_d[3], ar_d[4], ar_d[5]);

                double output = ((DateTime.Now - d).TotalSeconds);//與目前的時間相減,並換成『秒』

                if (output >= 0)
                {
                    html = html.Replace("{txt}", output.ToString("0") + "秒過去了");
                }
                else
                {
                    output = output * -1;
                    html   = html.Replace("{txt}", "還有" + output.ToString("0") + "秒");
                }
            } catch (Exception) {
                html = html.Replace("{txt}", "wryyyyyy");
            }

            System.Windows.Media.Imaging.BitmapFrame image = HtmlRender.RenderToImage(html);

            byte[] imgBytes;
            var    png = new JpegBitmapEncoder();

            png.Frames.Add(image);
            using (MemoryStream mem = new MemoryStream()) {
                png.Save(mem);
                imgBytes = mem.ToArray();  // and use the imgBytes array in your SQL operation
            }

            return(File(imgBytes, "image/jpeg"));
        }
Ejemplo n.º 19
0
 public HtmlScreenMediaElement(HtmlElement argElement,
                               HtmlRender argParent)
     : base(argElement, argParent)
 {
     if (null != argElement.FirstChild &&
         argElement.FirstChild.TagName.Equals(s_grgMediaType, StringComparison.OrdinalIgnoreCase))
     {
         m_grgMediaOriginContent = argElement.FirstChild.OuterHtml.Trim();
         m_grgMediaOriginContent = m_grgMediaOriginContent.Replace(s_grgMediaType, "embed");
     }
 }
Ejemplo n.º 20
0
        public override void SetHtml(string text)
        {
            m_ImageScrollControl.ScrollToTop();
            m_ImageScrollControl.ScrollToLeft();

            m_HtmlContainer.SetHtml(text, HtmlRender.ParseStyleSheet//CssData.Parse
                                        (null, true));

            CreateBitmap();

            m_ImagePanel.Show();
        }
Ejemplo n.º 21
0
        public override bool SetPropertyValue(string argProperty, object argValue)
        {
            if ( /*0 == string.Compare( argProperty, UIPropertyKey.s_ContentKey, true )*/
                argProperty.Equals(UIPropertyKey.s_ContentKey, StringComparison.OrdinalIgnoreCase) &&
                (argValue is string || argValue is int || argValue is double || argValue is float || argValue is long || argValue is short))
            {
                string formatValue = null;
                m_realContent.Clear();
                m_realContent.Append(argValue);
                if (FormatText(argValue.ToString(), out formatValue))
                {
                    return(base.SetPropertyValue(argProperty, HtmlRender.ConvertText(formatValue)));
                }
                else
                {
                    return(base.SetPropertyValue(argProperty, HtmlRender.ConvertText(argValue.ToString())));
                }
            }
            //else if ( 0 == string.Compare( argProperty, UIPropertyKey.s_ClearContent, true ) )
            else if (argProperty.Equals(UIPropertyKey.s_ClearContent, StringComparison.OrdinalIgnoreCase))
            {
                m_realContent.Clear();
            }
            else if (argProperty.Equals(UIPropertyKey.s_addValueKey, StringComparison.OrdinalIgnoreCase))
            {
                if (null != argValue)
                {
                    m_realContent.Append(argValue);
                    return(SetFormatOutput(UIPropertyKey.s_ContentKey, m_realContent.ToString()));
                }

                return(true);
            }
            else if (argProperty.Equals(UIPropertyKey.s_removeValueKey, StringComparison.OrdinalIgnoreCase))
            {
                if (m_realContent.Length > 0)
                {
                    m_realContent.Remove(m_realContent.Length - 1, 1);
                    if (m_realContent.Length > 0)
                    {
                        return(SetFormatOutput(UIPropertyKey.s_ContentKey, m_realContent.ToString()));
                    }
                    else
                    {
                        return(base.SetPropertyValue(UIPropertyKey.s_ContentKey, null));
                    }
                }

                return(true);
            }

            return(base.SetPropertyValue(argProperty, argValue));
        }
Ejemplo n.º 22
0
        public static Bitmap AddText(this Bitmap toImage, decimal bottomPercent, int pudding, string htmlText)
        {
            var html = $"<body style='font: 12pt Verdana'>{htmlText}</body>";

            var   destRect = new Rectangle(0, toImage.Height - (int)(toImage.Height * bottomPercent / 100), toImage.Width, (int)(toImage.Height * bottomPercent / 100));
            Image image    = HtmlRender.RenderToImageGdiPlus(html, new Size(destRect.Width, destRect.Height));
            var   graphics = Graphics.FromImage(toImage);

            graphics.DrawImage(image, destRect, 0, 0, image.Width, image.Height, GraphicsUnit.Pixel);

            return(toImage);
        }
Ejemplo n.º 23
0
        public void Test_Html_to_BMP()
        {
            // Perform
            Image image =
                HtmlRender.RenderToImage("<html><body><p>This is some html code</p><p>This is another html line</p></body>", new Size(400, 200), Color.White);

            using MemoryStream ms = new MemoryStream();
            image.Save(ms, ImageFormat.Png);

            // Validate
            Assert.Equal(2140, ms.Length);

            // image.Save(@"D:\Test.png", ImageFormat.Png);
        }
Ejemplo n.º 24
0
        /// <summary>
        /// Returns a fair width in which an html can be displayed
        /// </summary>
        public static int MeasureHtmlPrefWidth(string htmlContent, int minWidth, int maxWidth)
        {
            // find max height taken by the html
            // Measure the size of the html
            using (var gImg = new Bitmap(1, 1))
                using (var g = Graphics.FromImage(gImg)) {
                    string content = YamuiThemeManager.WrapLabelText(htmlContent);

                    // this should retrieve the best width, however it will not be the case if there are some width='100%' for instance
                    var calcWidth = (int)HtmlRender.Measure(g, content, 99999, YamuiThemeManager.CurrentThemeCss, null, (sender, args) => YamuiThemeManager.GetHtmlImages(args)).Width;

                    if (calcWidth >= 9999)
                    {
                        // get the minimum size required to display everything
                        var sizef = HtmlRender.Measure(g, content, 10, YamuiThemeManager.CurrentThemeCss, null, (sender, args) => YamuiThemeManager.GetHtmlImages(args));
                        minWidth = ((int)sizef.Width).Clamp(minWidth, maxWidth);

                        // set to max Width, get the height at max Width
                        sizef = HtmlRender.Measure(g, content, maxWidth, YamuiThemeManager.CurrentThemeCss, null, (sender, args) => YamuiThemeManager.GetHtmlImages(args));
                        var prefHeight = sizef.Height;

                        // now we got the final height, resize width until height changes
                        int j     = 0;
                        int detla = maxWidth / 2;
                        calcWidth = maxWidth;
                        do
                        {
                            calcWidth -= detla;
                            calcWidth  = calcWidth.Clamp(minWidth, maxWidth);

                            sizef = HtmlRender.Measure(g, content, calcWidth, YamuiThemeManager.CurrentThemeCss, null, (sender, args) => YamuiThemeManager.GetHtmlImages(args));

                            if (sizef.Height > prefHeight)
                            {
                                calcWidth += detla;
                                detla     /= 2;
                            }

                            if (calcWidth == maxWidth || calcWidth == minWidth)
                            {
                                break;
                            }

                            j++;
                        } while (j < 6);
                    }

                    return(calcWidth.Clamp(minWidth, maxWidth));
                }
        }
Ejemplo n.º 25
0
        /// <summary>
        /// Load custom fonts to be used by renderer HTMLs
        /// </summary>
        private void LoadCustomFonts()
        {
            // load custom font font into private fonts collection
            var file = Path.GetTempFileName();

            File.WriteAllBytes(file, Resources.CustomFont);
            _privateFont.AddFontFile(file);

            // add the fonts to renderer
            foreach (var fontFamily in _privateFont.Families)
            {
                HtmlRender.AddFontFamily(fontFamily);
            }
        }
        private Image GenerateHTMLImage()
        {
            string htmlText = "<b>hello</b> there. Visit <a href=\"https://github.com/OceanAirdrop\">github.com/OceanAirdrop</a>  for code. Heres a <span style=\"color: red\">random</span> apple ";
            Image  img      = HtmlRender.RenderToImage(htmlText); //,, maxWidth: cellSize.Width);

            return(img);

            // Step 4: Keep a record of the full image size to send back to caller.
            //  fullImageSize.Height = htmlImage.Height;
            //   fullImageSize.Width = htmlImage.Width;

            // Step 5: Render the HTML imaage a second time with the cell size width / height
            //img = HtmlRender.RenderToImage(htmlText, new Size(cellSize.Width, cellSize.Height));
        }
Ejemplo n.º 27
0
        private bool SetFormatOutput(string argProperty,
                                     string argContent)
        {
            string formatValue = null;

            if (FormatText(argContent, out formatValue))
            {
                return(base.SetPropertyValue(argProperty, HtmlRender.ConvertText(formatValue)));
            }
            else
            {
                return(base.SetPropertyValue(argProperty, HtmlRender.ConvertText(argContent)));
            }
        }
Ejemplo n.º 28
0
        /// <summary>
        ///
        /// </summary>
        /// <returns></returns>
        public ActionResult ip(String s)
        {
            String html = @"<html>
  <head>
    <meta charset='UTF-8' />
    <style>
      html, body { margin:0px; padding:0px; }
      #ddd {background-color:rgb(0,0,0); font-family:'Microsoft JhengHei';  padding:20px; margin:10px;   }
      .p { color: #ffffff; font-size:24px; }
    </style>
  </head>
  <body>
    <div id='ddd'>
      <div class='p'>IP:{ip}</div>
      <div class='p'>裝置:{pc_or_phone}</div>
      <div class='p'>瀏覽器:{borwser}</div>
      <div class='p'>作業系統:{system}</div>
    </div>
  </body>
</html>";

            String s_作業系統  = func_取得作業系統();
            String s_手機或電腦 = (func_是否用手機瀏覽()) ? "手機" : "電腦";
            String s_瀏覽器   = func_取得瀏覽器類型();
            String ip      = "1.1.1.1";

            try {
                String s_ip = func_取得IP();
                if (s_ip.Length >= 8)
                {
                    ip = s_ip;
                }
            } catch { }
            html = html.Replace("{ip}", ip);
            html = html.Replace("{pc_or_phone}", s_手機或電腦);
            html = html.Replace("{borwser}", s_瀏覽器);
            html = html.Replace("{system}", s_作業系統);

            BitmapFrame image = HtmlRender.RenderToImage(html);

            byte[] imgBytes;
            var    png = new JpegBitmapEncoder();

            png.Frames.Add(image);
            using (MemoryStream mem = new MemoryStream()) {
                png.Save(mem);
                imgBytes = mem.ToArray();  // and use the imgBytes array in your SQL operation
            }
            return(File(imgBytes, "image/jpeg"));
        }
        // Вычисление результатов по формулам
        public void Calculation(ref int taskNumber, int k, int[] table)
        {
            // Общая длительность интервалов
            int    T         = 0;
            double numerator = 0;

            for (int i = 1; i < k - 1; i++)
            {
                numerator += (double)1 / (N - i + 1);
                T         += t[i];
            }

            this.C = numerator / T;
            Console.WriteLine("Коэффициент пропорциональности: {0}",
                              Math.Round(this.C, 3));

            this.L = Math.Round(C, 3) * (N - (k - 1));
            Console.WriteLine("Интенсивность отказов: {0}",
                              Math.Round(this.L, 3));

            this.t_avg = 1 / Math.Round(L, 3);
            Console.WriteLine("Среднее время до следующего отказа: {0}",
                              Math.Round(this.t_avg, 3));

            this.P = Math.Exp(Math.Round(-L, 3) * T);
            Console.WriteLine("Функция надежности: {0}",
                              Math.Round(this.P, 3));

            Console.Write("Нажмите 1, если требуется сохранить задачу...\n");
            string result = Console.ReadLine();

            if (result == "1")
            {
                taskNumber++;
                #region Создание изображения с таблицей
                string tableHTML = this.ConvertTableIntToTableHtml(table, "Длительность каждого интервала", "");
                string html      = String.Format(SchumannMethodDataGenerator.HtmlTemplate, tableHTML);

                HtmlRender htmlRender = new HtmlRender();
                string     fileName   = String.Format("{0}_{1}.png",
                                                      taskNumber,
                                                      Math.Round(this.P, 3));

                htmlRender.SaveHtmlAsJPGAsync(html, fileName, 700, 160,
                                              ar => { Console.WriteLine("Файл {0} сохранён\n", fileName); });
                #endregion
                System.Threading.Thread.Sleep(300);
            }
        }
Ejemplo n.º 30
0
        private void Button1_Click(object sender, RoutedEventArgs e)
        {
            var filePath = @"C:\Test.png";

            var cssData = HtmlRender.ParseStyleSheet(_style);

            var img = HtmlRender.RenderToImage(_html, new Size(200, 200), new Size(999999, 999999), cssData: cssData, backgroundColor: Color.FromRgb(122, 122, 122));

            using (var fileStream = new FileStream(filePath, FileMode.Create))
            {
                var encoder = new PngBitmapEncoder();
                encoder.Frames.Add(img);
                encoder.Save(fileStream);
            }
        }
Ejemplo n.º 31
0
 public HtmlRendererAdapter(IDataRenderer dataRenderer)
 {
     this.dataRenderer = dataRenderer;
     htmlRenderer = new HtmlRender("My Page", dataRenderer.GetData()[0]);
 }