protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            var barcodeWriter = new BarcodeWriter
            {
                Format = ZXing.BarcodeFormat.QR_CODE,
                Options = new ZXing.Common.EncodingOptions
                {
                    Width = 300,
                    Height = 300,
                    Margin = 30
                }
            };

            var image = barcodeWriter.Write("ZXing.Net.Mobile");

            imageBarcode.Source = image;
        }
        public override void ViewDidLoad ()
        {
            base.ViewDidLoad ();

            NavigationItem.Title = "Generate Barcode";
            View.BackgroundColor = UIColor.White;

            imageBarcode = new UIImageView (new CGRect (20, 80, View.Frame.Width - 40, View.Frame.Height - 120));

            View.AddSubview (imageBarcode);

            var barcodeWriter = new BarcodeWriter {
                Format = ZXing.BarcodeFormat.QR_CODE,
                Options = new ZXing.Common.EncodingOptions {
                    Width = 300,
                    Height = 300,
                    Margin = 30
                }
            };

            var barcode = barcodeWriter.Write ("ZXing.Net.Mobile");

            imageBarcode.Image = barcode;
        }
        public override void ViewDidLoad ()
        {
            base.ViewDidLoad ();

			View.BackgroundColor = UIColor.Gray;

			nfloat h = 31.0f;
			nfloat w = View.Bounds.Width;

			usernameField = new UITextField
			{
				Placeholder = "Enter your username",
				BorderStyle = UITextBorderStyle.RoundedRect,
				Frame = new CGRect(10, 82, w - 20, h)
			};

			View.AddSubview(usernameField);
            NavigationItem.Title = "Generate Barcode";

            imageBarcode = new UIImageView (new CGRect (220, 80, View.Frame.Width - 60, View.Frame.Height - 220));

            View.AddSubview (imageBarcode);

            var barcodeWriter = new BarcodeWriter {
                Format = ZXing.BarcodeFormat.QR_CODE,
                Options = new ZXing.Common.EncodingOptions {
                    Width = 300,
                    Height = 300,
                    Margin = 30
                }
            };

            var barcode = barcodeWriter.Write ("ZXing.Net.Mobile");

            imageBarcode.Image = barcode;
        }
        private void Report4()
        {
            ParameterField paramField1 = new ParameterField();


            //creating an object of ParameterFields class
            ParameterFields paramFields1 = new ParameterFields();

            //creating an object of ParameterDiscreteValue class
            ParameterDiscreteValue paramDiscreteValue1 = new ParameterDiscreteValue();

            //set the parameter field name
            paramField1.Name = "id";

            //set the parameter value
            paramDiscreteValue1.Value = orderId;

            //add the parameter value in the ParameterField object
            paramField1.CurrentValues.Add(paramDiscreteValue1);

            //add the parameter in the ParameterFields object
            paramFields1.Add(paramField1);
            ReportView      f2 = new ReportView();
            TableLogOnInfos reportLogonInfos = new TableLogOnInfos();
            TableLogOnInfo  reportLogonInfo  = new TableLogOnInfo();
            ConnectionInfo  reportConInfo    = new ConnectionInfo();
            Tables          tables           = default(Tables);
            //	Table table = default(Table);
            var with1 = reportConInfo;

            with1.ServerName   = "tcp:KyotoServer,49172";
            with1.DatabaseName = "ProductNRelatedDB";
            with1.UserID       = "sa";
            with1.Password     = "******";
            ReportDocument cr = new ReportDocument();

            if (brandid == 1)
            {
                cr = new DOCOmron();
            }
            else if (brandid == 2)
            {
                cr = new DOCWithoutLogo();
            }
            else if (brandid == 3)
            {
                cr = new DOCAzbil();
            }
            else if (brandid == 4)
            {
                cr = new DOCBusinessAutomation();
            }
            else if (brandid == 5)
            {
                cr = new DOCIRD();
            }
            else if (brandid == 6)
            {
                cr = new DOCKawaShima();
            }

            tables = cr.Database.Tables;
            foreach (Table table in tables)
            {
                reportLogonInfo = table.LogOnInfo;
                reportLogonInfo.ConnectionInfo = reportConInfo;
                table.ApplyLogOnInfo(reportLogonInfo);
            }
            BArcode ds = new BArcode();

            var content = refid.ToString();
            var writer  = new BarcodeWriter
            {
                Format  = BarcodeFormat.CODE_128,
                Options = new EncodingOptions
                {
                    PureBarcode = true,
                    Height      = 100,
                    Width       = 465
                }
            };
            var png = writer.Write(content);

            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            png.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);

            DataRow dtr = ds.Tables[0].NewRow();

            dtr["REF"]          = comboBox1.Text;
            dtr["BarcodeImage"] = ms.ToArray();
            ds.Tables[0].Rows.Add(dtr);
            cr.Subreports["BarCode.rpt"].DataSourceConnections.Clear();
            cr.Subreports["BarCode.rpt"].SetDataSource(ds);
            f2.crystalReportViewer1.ParameterFieldInfo = paramFields1;
            f2.crystalReportViewer1.ReportSource       = cr;
            this.Visible = false;
            f2.ShowDialog();
            this.Visible = true;
        }
Beispiel #5
0
        // parameters:
        //      strType 39 / 空 /
        static Stream BuildQrCodeImage(string path)
        {
            Hashtable param_table = ParseParameters(path, ',', '=', "url");
            string    strType     = (string)param_table["type"];
            string    strCode     = (string)param_table["code"];
            string    strWidth    = (string)param_table["width"];
            string    strHeight   = (string)param_table["height"];

            int nWidth  = 200;
            int nHeight = 200;

            if (string.IsNullOrEmpty(strWidth) == false)
            {
                Int32.TryParse(strWidth, out nWidth);
            }
            if (string.IsNullOrEmpty(strHeight) == false)
            {
                Int32.TryParse(strHeight, out nHeight);
            }

            string strCharset  = "ISO-8859-1";
            bool   bDisableECI = false;

            BarcodeFormat format = BarcodeFormat.QR_CODE;

            if (strType == "39" || strType == "code_39")
            {
                format  = BarcodeFormat.CODE_39;
                strCode = strCode.ToUpper();    // 小写字符会无法编码
            }
            else if (strType == "ean_13")
            {
                format  = BarcodeFormat.EAN_13;
                strCode = strCode.ToUpper();
            }

            EncodingOptions options = new QrCodeEncodingOptions
            {
                Height          = nWidth,  // 400,
                Width           = nHeight, // 400,
                DisableECI      = bDisableECI,
                ErrorCorrection = ErrorCorrectionLevel.L,
                CharacterSet    = strCharset // "UTF-8"
            };

            if (strType == "39" || strType == "code_39" ||
                strType == "ean_13")
            {
                options = new EncodingOptions
                {
                    Width  = nWidth,  // 500,
                    Height = nHeight, // 100,
                    Margin = 10
                }
            }
            ;

            var writer = new BarcodeWriter
            {
                // Format = BarcodeFormat.QR_CODE,
                Format = format,
                // Options = new EncodingOptions
                Options = options
            };

            try
            {
                MemoryStream result = new MemoryStream(4096);

                using (var bitmap = writer.Write(strCode))
                {
                    bitmap.Save(result, System.Drawing.Imaging.ImageFormat.Png);
                }
                result.Seek(0, SeekOrigin.Begin);
                return(result);
            }
            catch (Exception ex)
            {
                Stream result = BuildTextImage("异常: " + ex.Message, Color.FromArgb(255, Color.DarkRed));
                result.Seek(0, SeekOrigin.Begin);
                return(result);
            }
        }
        public Bitmap setESLimageDemo_29(Panel panel1, string tag1_1)
        {
            Bitmap bmp = new Bitmap(296, 128);

            using (Graphics graphics = Graphics.FromImage(bmp))
            {
                graphics.FillRectangle(new SolidBrush(Color.White), 0, 0, 296, 128);
            }

            BarcodeWriter barcodeWriter = new BarcodeWriter()
            {
                Format = BarcodeFormat.CODE_39
            };

            foreach (Control control in panel1.Controls)
            {
                if (control is CheckBox)
                {
                    ((CheckBox)control).Checked = true;
                }
                else if (control is TextBox)
                {
                    int x      = ((TextBox)control).Location.X;
                    int y      = ((TextBox)control).Location.Y;
                    int width  = ((TextBox)control).Width;
                    int height = ((TextBox)control).Height;
                    //Console.WriteLine(string.Concat(new object[] { x, ",", y, "  w:", width, ", h:", height }));
                    bmp = this.mSmcDataToImage.ConvertTextToImageDemo(bmp, (TextBox)control, Color.White, x, y);
                }
                else if (control is Panel)
                {
                    int xPanel      = ((Panel)control).Location.X;
                    int yPanel      = ((Panel)control).Location.Y;
                    int widthPanel  = ((Panel)control).Width;
                    int heightPanel = ((Panel)control).Height;
                    //Console.WriteLine("controlINPanel");


                    bmp = mSmcDataToImage.ConvertPanelToImage(bmp, (Panel)control, Color.Black, xPanel, yPanel);
                }
                else if (control is PictureBox)
                {
                    int    num     = ((PictureBox)control).Location.X;
                    int    y1      = ((PictureBox)control).Location.Y;
                    int    width1  = ((PictureBox)control).Width;
                    int    height1 = ((PictureBox)control).Height;
                    Bitmap bar93   = new Bitmap(width1, height1);

                    barcodeWriter.Options.Width  = width1;
                    barcodeWriter.Options.Height = height1;

                    barcodeWriter.Options.Margin      = 0;
                    barcodeWriter.Options.PureBarcode = true;
                    bar93 = barcodeWriter.Write(tag1_1);
                    //Console.WriteLine("barW" + bar93.Width);
                    //Console.WriteLine("barH" + bar93.Height);


                    // this.pictureBox2.Image = bar;
                    //Console.WriteLine(string.Concat(new object[] { "PictureBox ", num, ",", y1, "  w:", width1, ", h:", height1 }));
                    //    this.bmp = this.mSmcDataToImage.ConvertImageToImage(this.bmp, this.pictureBox2.Image, num, y1, this.pictureBox2.Width, this.pictureBox2.Height);
                    bmp = this.mSmcDataToImage.ConvertBarToImage(bmp, bar93, num, y1);
                }
                else if (control is Label)
                {
                    int x1      = ((Label)control).Location.X;
                    int num1    = ((Label)control).Location.Y;
                    int width2  = ((Label)control).Width;
                    int height2 = ((Label)control).Height;
                    //Console.WriteLine(string.Concat(new object[] { "Label ", x1, ",", num1, "  w:", width2, ", h:", height2 }));
                    bmp = mSmcDataToImage.ConvertTextToImageDemo(bmp, (Label)control, Color.Black, x1, num1);
                }
            }



            return(bmp);
        }
Beispiel #7
0
        /// <summary>
        /// 打印触发事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void PrintDocument_PrintPage(object sender, PrintPageEventArgs e)
        {
            Brush    bru = Brushes.Black;
            Graphics g   = e.Graphics;

            float totalHeight = 0;
            int   rowIndex    = 0;

            Action <XElement, Dictionary <string, object> > ActionText = (el, row) =>
            {
                float  Left     = string.IsNullOrWhiteSpace(el.Attribute("Left").Value) ? 0 : Convert.ToSingle(el.Attribute("Left").Value);
                float  Top      = string.IsNullOrWhiteSpace(el.Attribute("Top").Value) ? 0 : Convert.ToSingle(el.Attribute("Top").Value);
                float  FontSize = string.IsNullOrWhiteSpace(el.Attribute("FontSize").Value) ? 0 : Convert.ToSingle(el.Attribute("FontSize").Value);
                string FontName = el.Attribute("FontName") != null?el.Attribute("FontName").Value : "";

                FontName = string.IsNullOrWhiteSpace(FontName) ? "宋体" : FontName;

                Top = totalHeight + Top;
                string content = el.Value;
                if (content.Contains("{{") && content.Contains("}}"))
                {
                    int    beginIndex = content.IndexOf("{{");
                    int    endIndex   = content.LastIndexOf("}}");
                    string key        = content.Substring(beginIndex + 2, endIndex - beginIndex - 2);
                    g.DrawString(content.Replace("{{" + key + "}}", row[key].ToString()), new Font(FontName, FontSize, FontStyle.Regular), bru, new PointF(Left, Top));
                }
                else
                {
                    g.DrawString(content, new Font(FontName, FontSize, FontStyle.Regular), bru, new PointF(Left, Top));
                }
            };

            Action <XElement, Dictionary <string, object> > ActionImage = (el, row) =>
            {
                float Left   = string.IsNullOrWhiteSpace(el.Attribute("Left").Value) ? 0 : Convert.ToSingle(el.Attribute("Left").Value);
                float Top    = string.IsNullOrWhiteSpace(el.Attribute("Top").Value) ? 0 : Convert.ToSingle(el.Attribute("Top").Value);
                int   Width  = 0;
                int   Heigth = 0;

                if (el.Attribute("Width") != null)
                {
                    Width = string.IsNullOrWhiteSpace(el.Attribute("Width").Value) ? 0 : Convert.ToInt32(el.Attribute("Width").Value);
                }
                if (el.Attribute("Heigth") != null)
                {
                    Heigth = string.IsNullOrWhiteSpace(el.Attribute("Heigth").Value) ? 0 : Convert.ToInt32(el.Attribute("Heigth").Value);
                }

                Top = totalHeight + Top;
                string content = el.Value;
                if (content.Contains("{{") && content.Contains("}}"))
                {
                    int    beginIndex = content.IndexOf("{{");
                    int    endIndex   = content.LastIndexOf("}}");
                    string key        = content.Substring(beginIndex + 2, endIndex - beginIndex - 2);
                    Image  image      = Image.FromFile(row[key].ToString());

                    if (Width == 0 || Heigth == 0)
                    {
                        g.DrawImage(image, new PointF(Left, Top));
                    }
                    else
                    {
                        g.DrawImage(image, Left, Top, Width, Heigth);
                    }
                }
            };

            Action <XElement, Dictionary <string, object> > ActionQRCode = (el, row) =>
            {
                string content = string.Empty;
                float  Left    = string.IsNullOrWhiteSpace(el.Attribute("Left").Value) ? 0 : Convert.ToSingle(el.Attribute("Left").Value);
                float  Top     = string.IsNullOrWhiteSpace(el.Attribute("Top").Value) ? 0 : Convert.ToSingle(el.Attribute("Top").Value);

                Top     = totalHeight + Top;
                content = el.Value;
                if (content.Contains("{{") && content.Contains("}}"))
                {
                    int    beginIndex = content.IndexOf("{{");
                    int    endIndex   = content.LastIndexOf("}}");
                    string key        = content.Substring(beginIndex + 2, endIndex - beginIndex - 2);
                    content = content.Replace("{{" + key + "}}", row[key].ToString());
                }

                QrEncoder qrEncoder = new QrEncoder(ErrorCorrectionLevel.H);
                QrCode    qrCode    = new QrCode();
                qrEncoder.TryEncode(content, out qrCode);
                using (MemoryStream ms = new MemoryStream())
                {
                    GraphicsRenderer renderer = new GraphicsRenderer(new FixedModuleSize(3, QuietZoneModules.Two));
                    renderer.WriteToStream(qrCode.Matrix, ImageFormat.Jpeg, ms);
                    Image image = Image.FromStream(ms);
                    g.DrawImage(image, new PointF(Left, Top));
                }
            };

            Action <XElement, Dictionary <string, object> > ActionBarCode = (el, row) =>
            {
                string content = string.Empty;

                float Left = string.IsNullOrWhiteSpace(el.Attribute("Left").Value) ? 0 : Convert.ToSingle(el.Attribute("Left").Value);
                float Top  = string.IsNullOrWhiteSpace(el.Attribute("Top").Value) ? 0 : Convert.ToSingle(el.Attribute("Top").Value);

                float Width  = string.IsNullOrWhiteSpace(el.Attribute("Width").Value) ? 0 : Convert.ToSingle(el.Attribute("Width").Value);
                float Height = string.IsNullOrWhiteSpace(el.Attribute("Height").Value) ? 0 : Convert.ToSingle(el.Attribute("Height").Value);

                Top     = totalHeight + Top;
                content = el.Value;
                if (content.Contains("{{") && content.Contains("}}"))
                {
                    int    beginIndex = content.IndexOf("{{");
                    int    endIndex   = content.LastIndexOf("}}");
                    string key        = content.Substring(beginIndex + 2, endIndex - beginIndex - 2);
                    content = content.Replace("{{" + key + "}}", row[key].ToString());
                }

                QrCodeEncodingOptions options = new QrCodeEncodingOptions
                {
                    DisableECI   = true,
                    CharacterSet = "UTF-8",
                    Width        = (int)Math.Ceiling(Width),
                    Height       = (int)Math.Ceiling(Height),
                };
                BarcodeWriter writer = new BarcodeWriter();
                writer.Format  = BarcodeFormat.CODE_128;
                writer.Options = options;
                Bitmap bitmap = writer.Write(content);
                g.DrawImage(bitmap, new PointF(Left, Top));
            };

            foreach (XElement item in root.Element("Page").Elements())
            {
                if (item.Name == "Line")
                {
                    float LineHeigth = string.IsNullOrWhiteSpace(item.Attribute("Height").Value) ? 0 : Convert.ToSingle(item.Attribute("Height").Value);
                    foreach (XElement child in item.Elements())
                    {
                        if (child.Name == "Text")
                        {
                            ActionText(child, this.DataSource);
                        }
                        else if (child.Name == "Image")
                        {
                            ActionImage(child, this.DataSource);
                        }
                        else if (child.Name == "QRCode")
                        {
                            ActionQRCode(child, this.DataSource);
                        }
                        else if (child.Name == "BarCode")
                        {
                            ActionBarCode(child, this.DataSource);
                        }
                    }
                    totalHeight += LineHeigth;
                    rowIndex++;
                }
                else if (item.Name == "Loop")
                {
                    string Values = item.Attribute("Values").Value;
                    List <Dictionary <string, object> > listValues = this.DataSource[Values] as List <Dictionary <string, object> >;
                    if (listValues != null)
                    {
                        XElement lineItem   = item.Element("Line");
                        float    LineHeigth = string.IsNullOrWhiteSpace(lineItem.Attribute("Height").Value) ? 0 : Convert.ToSingle(lineItem.Attribute("Height").Value);
                        for (int i = 0; i < listValues.Count(); i++)
                        {
                            Dictionary <string, object> dicRow = listValues[i];
                            foreach (XElement child in lineItem.Elements())
                            {
                                if (child.Name == "Text")
                                {
                                    ActionText(child, dicRow);
                                }
                                else if (child.Name == "Image")
                                {
                                    ActionImage(child, dicRow);
                                }
                                else if (child.Name == "QRCode")
                                {
                                    ActionQRCode(child, dicRow);
                                }
                                else if (child.Name == "BarCode")
                                {
                                    ActionBarCode(child, dicRow);
                                }
                            }
                            totalHeight += LineHeigth;
                            rowIndex++;
                        }
                    }
                }
            }
        }
        //  Panel panel1 = new Panel();
        public Bitmap setPage1(string MacAddress)
        {
            Bitmap bmp = new Bitmap(212, 104);


            /* string[] temp = new string[] { "瑞", "新", "電", "子", "SMC", "Robert", "Lun", "Willy", "永", "晴", "恭", "賀", "Mini", "壓", "單", "提", "剛", "網", "賽", "鑫", "覦", "§"
             * , "●", "€", "$", "わ", "ら", "や", "ま", "は", "な", "た", "さ", "か", "あ", "め", "つ", "ち", "の", "â", "ī", "u", "â", "û", "ô", "电", "子", "货", "价", "标", "签", "折"
             * , "扣", "特", "殺", "杀", "下", "잘", "지", "냈", "어", "요", "수", "께", "끼", "는", "한", "국", "고", "유의", "언어", "문화적", "ESL", "Special"};
             */

            using (Graphics graphics = Graphics.FromImage(bmp))
            {
                graphics.FillRectangle(new SolidBrush(Color.White), 0, 0, 212, 104);
            }

            Bitmap        bar       = new Bitmap(210, 30);
            BarcodeWriter barcode_w = new BarcodeWriter();

            barcode_w.Format              = BarcodeFormat.CODE_93;
            barcode_w.Options.Width       = 210;
            barcode_w.Options.Height      = 30;
            barcode_w.Options.PureBarcode = true;
            bar = barcode_w.Write(MacAddress);
            bmp = mSmcDataToImage.ConvertImageToImage(bmp, bar, 4, 70); //QRcode



            /*   int max = temp.Length-1;
             * int min = 0;
             * int n = 6;
             * Random rnd = new Random();
             * int[] ValueString = new int[n];
             *
             * string str = "";
             *
             * for (int i = 0; i < n; i++)
             * {
             *     ValueString[i] = rnd.Next(min, max + 1);
             *     while (Array.IndexOf(ValueString, ValueString[i], 0, i) > -1)
             *     {
             *         ValueString[i] = rnd.Next(min, max + 1);
             *     }
             * }*/
            /* for (int i = 0; i < n; i++)
             * {
             *   str = str + temp[ValueString[i]];
             * }
             *
             * t1.Text = str;
             * if(str.Length > 6)
             * {
             *   t1.Font = new Font("Cambria", 17, FontStyle.Bold);
             * }else
             * {
             *   t1.Font = new Font("Cambria", 20, FontStyle.Bold);
             * }*/



            /*int b = 0;
             * int c = 8;
             * Random rNumber = new Random();
             *
             *
             * if (rNumber.Next(b, c) == 0) {
             *  t1.Text = "SMC Lun缺女友";
             *  t1.Font = new Font("Cambria", 20, FontStyle.Bold);
             * }
             * else if (rNumber.Next(b, c) == 1)
             * {
             *  t1.Text = "SMC 永晴";
             *  t1.Font = new Font("Cambria", 20, FontStyle.Bold);
             * }
             * else if (rNumber.Next(b, c) == 2)
             * {
             *  t1.Text = "SMC Robert神";
             *  t1.Font = new Font("Cambria", 20, FontStyle.Bold);
             * }
             * else if (rNumber.Next(b, c) == 3)
             * {
             *  t1.Text = "SMC 冬瓜哥";
             *  t1.Font = new Font("Cambria", 20, FontStyle.Bold);
             * }
             * else if (rNumber.Next(b, c) == 4)
             * {
             *  t1.Text = "SMC 晴勇";
             *  t1.Font = new Font("Cambria", 20, FontStyle.Bold);
             * }
             * else if (rNumber.Next(b, c) == 5)
             * {
             *  t1.Text = "Willy感謝讚美主";
             *  t1.Font = new Font("Cambria", 17, FontStyle.Bold);
             * }
             * else if (rNumber.Next(b, c) == 6)
             * {
             *  t1.Text = "Willy主賜福於你";
             *  t1.Font = new Font("Cambria", 17, FontStyle.Bold);
             * }
             * else
             * {
             *  t1.Text = "SMC ESL";
             *  t1.Font = new Font("Cambria", 20, FontStyle.Bold);
             * }*/
            TextBox t1 = new TextBox();

            t1.Text        = "SMC ESL";
            t1.Font        = new Font("Cambria", 20, FontStyle.Bold);
            t1.TextAlign   = HorizontalAlignment.Center; //置中
            t1.BorderStyle = BorderStyle.FixedSingle;
            t1.Width       = 206;
            t1.Height      = 25;
            bmp            = mSmcDataToImage.ConvertTextToImage(bmp, t1, Color.Red, 1, 0);

            String StrName = String.Format("{0}", DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"));

            t1.Text        = StrName;
            t1.Font        = new Font("Cambria", 15, FontStyle.Bold);
            t1.TextAlign   = HorizontalAlignment.Center; //置中
            t1.BorderStyle = BorderStyle.FixedSingle;
            t1.Width       = 206;
            t1.Height      = 25;
            bmp            = mSmcDataToImage.ConvertTextToImage(bmp, t1, Color.Red, 2, 23);


            t1.Text        = MacAddress;
            t1.Font        = new Font("Cambria", 20, FontStyle.Bold);
            t1.TextAlign   = HorizontalAlignment.Center; //置中
            t1.BorderStyle = BorderStyle.FixedSingle;
            t1.Width       = 206;
            t1.Height      = 25;
            bmp            = mSmcDataToImage.ConvertTextToImage(bmp, t1, Color.Black, 2, 40);



            return(bmp);
        }
        //  Panel panel1 = new Panel();
        public Bitmap setPage1E(string MacAddress, string rssi)
        {
            Bitmap bmp = new Bitmap(212, 104);



            using (Graphics graphics = Graphics.FromImage(bmp))
            {
                graphics.FillRectangle(new SolidBrush(Color.White), 0, 0, 212, 104);
            }

            Bitmap        bar       = new Bitmap(210, 30);
            BarcodeWriter barcode_w = new BarcodeWriter();

            barcode_w.Format              = BarcodeFormat.CODE_93;
            barcode_w.Options.Width       = 210;
            barcode_w.Options.Height      = 30;
            barcode_w.Options.PureBarcode = true;
            bar = barcode_w.Write(MacAddress);
            bmp = mSmcDataToImage.ConvertImageToImage(bmp, bar, 4, 70); //QRcode



            TextBox t1 = new TextBox();

            /*  t1.Text = "SMC ESL";
             * t1.Font = new Font("Cambria", 20, FontStyle.Bold);
             * t1.TextAlign = HorizontalAlignment.Center; //置中
             * t1.BorderStyle = BorderStyle.FixedSingle;
             * t1.Width = 150;
             * t1.Height = 25;
             * bmp = mSmcDataToImage.ConvertTextToImage(bmp, t1, Color.Red, 25, 0);*/

            t1.Text        = "RSSI: " + rssi;
            t1.Font        = new Font("Cambria", 20, FontStyle.Bold);
            t1.TextAlign   = HorizontalAlignment.Center; //置中
            t1.BorderStyle = BorderStyle.FixedSingle;
            t1.Width       = 200;
            t1.Height      = 25;
            if (Convert.ToInt32(rssi) < -60)
            {
                bmp = mSmcDataToImage.ConvertTextToImage(bmp, t1, Color.Red, 1, 10);
            }
            else
            {
                bmp = mSmcDataToImage.ConvertTextToImage(bmp, t1, Color.Black, 1, 10);
            }

            /* String StrName = String.Format("{0}", DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"));
             * t1.Text = StrName;
             * t1.Font = new Font("Cambria", 15, FontStyle.Bold);
             * t1.TextAlign = HorizontalAlignment.Center; //置中
             * t1.BorderStyle = BorderStyle.FixedSingle;
             * t1.Width = 206;
             * t1.Height = 25;
             * bmp = mSmcDataToImage.ConvertTextToImage(bmp, t1, Color.Red, 2, 23);*/


            t1.Text        = MacAddress;
            t1.Font        = new Font("Cambria", 20, FontStyle.Bold);
            t1.TextAlign   = HorizontalAlignment.Center; //置中
            t1.BorderStyle = BorderStyle.FixedSingle;
            t1.Width       = 206;
            t1.Height      = 25;
            bmp            = mSmcDataToImage.ConvertTextToImage(bmp, t1, Color.Black, 2, 40);



            return(bmp);
        }
Beispiel #10
0
        public static string GenerateQrCode(string pin)
        {
            var qrWriter = new BarcodeWriter
            {
                Format  = BarcodeFormat.QR_CODE,
                Options = new EncodingOptions()
                {
                    Height = 100, Width = 100, Margin = 0
                }
            };

            QrBytes = new List <string>();

            using (var q = qrWriter.Write("192.168.43.251:81/Users/Create?pin=" + pin))
            {
                using (var ms = new MemoryStream())
                {
                    q.Save(ms, ImageFormat.Bmp);

                    using (Image image = Image.FromStream(ms))
                    {
                        var bmp = new Bitmap(100, 100, PixelFormat.Format16bppRgb555);
                        var gr  = Graphics.FromImage(bmp);
                        gr.DrawImage(image, new Rectangle(0, 0, 100, 100));
                        Bitmap a = bmp;

                        var argb = "";
                        for (int i = 0; i < 100; i++)
                        {
                            for (int j = 0; j < 100; j++)
                            {
                                Color pixelColor = a.GetPixel(i, j);
                                byte  red        = pixelColor.R;
                                byte  green      = pixelColor.G;
                                byte  blue       = pixelColor.B;

                                int b = (blue >> 3) & 0x1f;
                                int g = ((green >> 2) & 0x3f) << 5;
                                int r = ((red >> 3) & 0x1f) << 11;

                                int result = r | g | b;
                                var st     = result.ToString("X");
                                if (st == "FFFF")
                                {
                                    st = "F";
                                }

                                argb += st;

                                if (argb.Length == 1000)
                                {
                                    QrBytes.Add(argb);
                                    argb = "";
                                }
                            }
                        }
                        return(argb);
                    }
                }
            }
        }
        public async Task LoadDialogAsync()
        {
            bool hasError = false;

            //get read only keys
            using (var uow = UnitOfWorkFactory.CreateUnitOfWork())
            {
                var readOnlyEndpointSetting = uow.SettingsRepository.GetSettingWithDefault(GinAppSettingKeys.AZURE_DOCUMENTDB_READONLY_ENDPOINT, "");
                var readOnlyKeySetting      = uow.SettingsRepository.GetSettingWithDefault(GinAppSettingKeys.AZURE_DOCUMENTDB_READONLY_KEY, "");
                var ginName = uow.SettingsRepository.GetSettingWithDefault(GinAppSettingKeys.GIN_NAME, "");
                var email   = uow.SettingsRepository.GetSettingWithDefault(GinAppSettingKeys.IMAP_USERNAME, "");

                if (string.IsNullOrWhiteSpace(readOnlyEndpointSetting) || string.IsNullOrWhiteSpace(readOnlyKeySetting))
                {
                    hasError      = true;
                    lblError.Text = "Unable to create QR code.  Azure Cosmos DB READ ONLY Settings have not been saved.";
                }
                else if (string.IsNullOrWhiteSpace(email))
                {
                    hasError      = true;
                    lblError.Text = "Unable to create QR code.  IMAP username/email missing or not yet saved.";
                }

                if (!hasError)
                {
                    try
                    {
                        bool writeAble = await CottonDBMS.Cloud.DocumentDBContext.CanWrite(readOnlyEndpointSetting, readOnlyKeySetting);

                        bool readAble = await CottonDBMS.Cloud.DocumentDBContext.CanRead(readOnlyEndpointSetting, readOnlyKeySetting);

                        if (writeAble)
                        {
                            hasError      = true;
                            lblError.Text = "Unable to create QR code.  Azure Cosmos Read Only settings are allowing write access.  Please ensure you have not entered the read/write key for the READ only key.";
                        }
                        else if (!readAble)
                        {
                            hasError      = true;
                            lblError.Text = "Unable to create QR code.  Unable to read from Azure Cosmos DB.  Please verify your READ ONLY Uri and Key is correct.";
                        }
                    }
                    catch (Exception exc)
                    {
                        hasError      = true;
                        lblError.Text = exc.Message;
                    }
                }

                btnDownloadQRCode.Enabled = !hasError;
                lblInfoText.Visible       = !hasError;
                lblError.Visible          = hasError;
                pictureBoxQRCode.Visible  = !hasError;

                if (!hasError)
                {
                    //no errors were found so configuration is good - we need to generate a json document with the endpoint information
                    var info = new CottonDBMS.DataModels.MobileConnectionInfo();
                    info.Email = email;
                    info.Gin   = ginName;
                    info.Url   = readOnlyEndpointSetting;
                    info.Key   = readOnlyKeySetting;

                    //we encrypt to mask the data in the QR code - RFID Module Scan will decrypt
                    var dataString = EncryptionHelper.Encrypt(Newtonsoft.Json.JsonConvert.SerializeObject(info));

                    var writer = new BarcodeWriter {
                        Format = BarcodeFormat.QR_CODE
                    };
                    writer.Options.Height = 300;
                    writer.Options.Width  = 300;
                    var result = writer.Write(dataString);
                    pictureBoxQRCode.Image = result;

                    var decrypted = EncryptionHelper.Decrypt(dataString);
                }
            }
        }
Beispiel #12
0
        private void GeneratePDF_SortPlan(string filePath, string dateTimeStr)
        {
            try
            {
                // create PDF file
                FileStream fs     = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.None);
                Document   doc    = new Document();
                PdfWriter  writer = PdfWriter.GetInstance(doc, fs);

                doc.Open();

                // Add table
                PdfPTable table    = new PdfPTable(3);
                float[]   colWidth = new float[] { 2.0f, 5.0f, 7.0f };
                table.SetWidths(colWidth);

                PdfPCell cell = new PdfPCell(new Phrase("SORT PLAN - " + dateTimeStr));
                cell.Colspan             = 3;
                cell.HorizontalAlignment = 1;
                table.AddCell(cell);

                table.AddCell("Lane");
                table.AddCell("AWB");
                table.AddCell("Barcode");

                sortedParcelList.Sort(new LaneComparer());

                for (int i = 0; i < sortedParcelList.Count; i++)
                {
                    // Add image
                    BarcodeWriter barcodeWriter = new BarcodeWriter()
                    {
                        Format  = BarcodeFormat.CODE_128,
                        Options = new QrCodeEncodingOptions()
                        {
                            Width  = 300,
                            Height = 100
                        }
                    };
                    Bitmap bmp = barcodeWriter.Write(sortedParcelList[i].AWB);
                    iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(bmp, System.Drawing.Imaging.ImageFormat.Bmp);
                    image.ScaleToFit(150.0F, 50.0F);
                    image.Alignment = Element.ALIGN_CENTER;

                    PdfPCell imgCell = new PdfPCell()
                    {
                        PaddingLeft = 5, PaddingRight = 5
                    };
                    imgCell.AddElement(image);

                    table.AddCell(sortedParcelList[i].Lanes);
                    table.AddCell(sortedParcelList[i].AWB);
                    table.AddCell(imgCell);
                }

                doc.Add(table);

                doc.Close();
                writer.Close();
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
            }
        }
Beispiel #13
0
        private void Report2()
        {
            button1.Enabled = false;
            backgroundWorker1.RunWorkerAsync();
            progressBar1.Visible = true;

            // To report progress from the background worker we need to set this property
            backgroundWorker1.WorkerReportsProgress = true;
            // This event will be raised on the worker thread when the worker starts
            backgroundWorker1.DoWork += new DoWorkEventHandler(backgroundWorker1_DoWork);
            // This event will be raised when we call ReportProgress
            backgroundWorker1.ProgressChanged += new ProgressChangedEventHandler(backgroundWorker1_ProgressChanged);
            ParameterField paramField1 = new ParameterField();


            //creating an object of ParameterFields class
            ParameterFields paramFields1 = new ParameterFields();

            //creating an object of ParameterDiscreteValue class
            ParameterDiscreteValue paramDiscreteValue1 = new ParameterDiscreteValue();

            //set the parameter field name
            paramField1.Name = "id";

            //set the parameter value
            paramDiscreteValue1.Value = orderId;

            //add the parameter value in the ParameterField object
            paramField1.CurrentValues.Add(paramDiscreteValue1);

            //add the parameter in the ParameterFields object
            paramFields1.Add(paramField1);
            ReportView      f2 = new ReportView();
            TableLogOnInfos reportLogonInfos = new TableLogOnInfos();
            TableLogOnInfo  reportLogonInfo  = new TableLogOnInfo();
            ConnectionInfo  reportConInfo    = new ConnectionInfo();
            Tables          tables           = default(Tables);
            //	Table table = default(Table);
            var with1 = reportConInfo;

            with1.ServerName   = "tcp:KyotoServer,49172";
            with1.DatabaseName = "ProductNRelatedDB";
            with1.UserID       = "sa";
            with1.Password     = "******";

            ReportDocument cr = new ReportDocument();

            if (brandid == 1)
            {
                cr = new DOOCOmron();
            }
            else if (brandid == 2)
            {
                cr = new DOOCWithoutLogo();
            }
            else if (brandid == 3)
            {
                cr = new DOOCAzbill();
            }
            else if (brandid == 4)
            {
                cr = new DOOCBusinessAutomation();
            }
            else if (brandid == 5)
            {
                cr = new DOOCIRD();
            }
            else if (brandid == 6)
            {
                cr = new DOOCKawaShima();
            }
            tables = cr.Database.Tables;
            foreach (Table table in tables)
            {
                reportLogonInfo = table.LogOnInfo;
                reportLogonInfo.ConnectionInfo = reportConInfo;
                table.ApplyLogOnInfo(reportLogonInfo);
            }
            BArcode ds = new BArcode();

            var content = comboBox1.Text;
            var writer  = new BarcodeWriter
            {
                Format  = BarcodeFormat.CODE_128,
                Options = new EncodingOptions
                {
                    PureBarcode = true,
                    Height      = 100,
                    Width       = 465
                }
            };
            var png = writer.Write(content);

            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            png.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);

            DataRow dtr = ds.Tables[0].NewRow();

            dtr["REF"]          = comboBox1.Text;
            dtr["BarcodeImage"] = ms.ToArray();
            ds.Tables[0].Rows.Add(dtr);
            cr.Subreports["BarCode.rpt"].DataSourceConnections.Clear();
            cr.Subreports["BarCode.rpt"].SetDataSource(ds);
            f2.crystalReportViewer1.ParameterFieldInfo = paramFields1;
            f2.crystalReportViewer1.ReportSource       = cr;

            this.Visible = false;

            f2.ShowDialog();
            this.Visible = true;
            backgroundWorker1.CancelAsync();
            backgroundWorker1.Dispose();
            progressBar1.Visible = false;
            button1.Enabled      = true;
        }
 public PixelData ToBitmap()
 {
    var writer = new BarcodeWriter { Format = BarcodeFormat.EAN_8 };
    return writer.Write(this);
 }
Beispiel #15
0
        private void reportViewer1_Load(object sender, EventArgs e)
        {
            if (MiEmpleado != null)
            {
                MiEmpleado = new ControladorEmpleado().BuscarEmpleadoPorClavesUnicasPorVista(MiEmpleado.MiPersona.DNI);
                if (MiEmpleado.MiPersona.Foto != null)
                {
                    using (var ms = new MemoryStream(MiEmpleado.Foto))
                        bbb = new Bitmap(Image.FromStream(ms));
                }
                else
                {
                    using (var ms = new MemoryStream())
                    {
                        new Bitmap(global::ProjectGimnasiaYEsgrima.Properties.Resources.Perfil).Save(ms, ImageFormat.Png);
                        MiEmpleado.MiPersona.Foto = ms.ToArray();
                        new ControladorPersona().ActualizarFotoPersona(MiEmpleado.MiPersona.DNI, ms.ToArray());
                    }
                }
            }
            else
            {
                MiSocio = new ControladorSocio().BuscarPorClavesUnicasSocio(MiSocio.MiPersona.DNI);
                if (MiSocio.MiPersona.Foto != null)
                {
                    using (var ms = new MemoryStream(MiSocio.MiPersona.Foto))
                        bbb = new Bitmap(Image.FromStream(ms));
                }
                else
                {
                    using (var ms = new MemoryStream())
                    {
                        new Bitmap(global::ProjectGimnasiaYEsgrima.Properties.Resources.Perfil).Save(ms, ImageFormat.Png);
                        MiSocio.MiPersona.Foto = ms.ToArray();
                        new ControladorPersona().ActualizarFotoPersona(MiSocio.MiPersona.DNI, ms.ToArray());
                    }
                }
            }

            string tipoDoc      = MiSocio == null ? "" : MiSocio.MiSocio.TipoDocumento + "";
            int    numeroDoc    = MiSocio == null ? MiEmpleado.DNI : MiSocio.DNI;
            string nombre       = MiSocio == null ? MiEmpleado.Nombre : MiSocio.Nombre;
            string apellido     = MiSocio == null ? MiEmpleado.Apellido : MiSocio.Apellido;
            string fechaIngreso = MiSocio == null ? new DateTime(MiEmpleado.MiEmpleado.FechaInicio.Year, MiEmpleado.MiEmpleado.FechaInicio.Month, MiEmpleado.MiEmpleado.FechaInicio.Day).ToString("dd'/'MM'/'yyyy") : new DateTime(MiSocio.MiSocio.FechaInicio.Year, MiSocio.MiSocio.FechaInicio.Month, MiSocio.MiSocio.FechaInicio.Day).ToString("dd'/'MM'/'yyyy");
            string tipoEmpleado = MiSocio == null?MiEmpleado.TipoEmpleado.ToString() : MiSocio.MiSocio.CategoriaSocio.ToString();

            string tipoDocumentacion = MiSocio == null ? "Empleado" : "Socio";
            string barratexto        = tipoDocumentacion + "-" + numeroDoc;



            BarcodeWriter barcode = new BarcodeWriter();

            barcode.Format = BarcodeFormat.QR_CODE;

            barcode.Options = new ZXing.Common.EncodingOptions
            {
                Height = 400,
                Width  = 400,
                Margin = 1
            };


            var             b = barcode.Write(barratexto);
            ReportParameter PCodigoBarras;

            using (var ms = new MemoryStream()) {
                b.Save(ms, ImageFormat.Png);
                PCodigoBarras = new ReportParameter()
                {
                    Name   = "ReportParameterCodigoBarras",
                    Values = { Convert.ToBase64String(ms.ToArray()) }
                };
            }
            Bitmap c;

            if (bbb == null)
            {
                c = new Bitmap(global::ProjectGimnasiaYEsgrima.Properties.Resources.Perfil);
            }
            else
            {
                c = bbb;
            }
            ReportParameter PFoto;

            using (var ms = new MemoryStream())
            {
                c.Save(ms, ImageFormat.Png);
                PFoto = new ReportParameter()
                {
                    Name   = "ReportParameterFoto",
                    Values = { Convert.ToBase64String(ms.ToArray()) }
                };
            }



            ReportParameter PTipoDocyNumero = new ReportParameter("ReportParameterTipoDocyNumero", tipoDoc + "   " + numeroDoc);
            ReportParameter PNombre         = new ReportParameter("ReportParameterNombreYApellido", nombre + " " + apellido);
            ReportParameter PApellido       = new ReportParameter("ReportParameterFechaIngreso", fechaIngreso);
            ReportParameter PTipoEmpleado   = new ReportParameter("ReportParameterCategoria", tipoEmpleado);


            this.reportViewer1.LocalReport.SetParameters(new ReportParameter[] { PTipoDocyNumero, PNombre, PApellido, PTipoEmpleado, PCodigoBarras, PFoto });

            this.reportViewer1.RefreshReport();
        }
Beispiel #16
0
        private void Report3()
        {
            button1.Enabled = false;
            backgroundWorker1.RunWorkerAsync();
            progressBar1.Visible = true;

            // To report progress from the background worker we need to set this property
            backgroundWorker1.WorkerReportsProgress = true;
            // This event will be raised on the worker thread when the worker starts
            backgroundWorker1.DoWork += new DoWorkEventHandler(backgroundWorker1_DoWork);
            // This event will be raised when we call ReportProgress
            backgroundWorker1.ProgressChanged += new ProgressChangedEventHandler(backgroundWorker1_ProgressChanged);

            ParameterField paramField1 = new ParameterField();


            //creating an object of ParameterFields class
            ParameterFields paramFields1 = new ParameterFields();

            //creating an object of ParameterDiscreteValue class
            ParameterDiscreteValue paramDiscreteValue1 = new ParameterDiscreteValue();

            //set the parameter field name
            paramField1.Name = "id";

            //set the parameter value
            paramDiscreteValue1.Value = outid;

            //add the parameter value in the ParameterField object
            paramField1.CurrentValues.Add(paramDiscreteValue1);

            //add the parameter in the ParameterFields object
            paramFields1.Add(paramField1);
            ReportViewer    f2 = new ReportViewer();
            TableLogOnInfos reportLogonInfos = new TableLogOnInfos();
            TableLogOnInfo  reportLogonInfo  = new TableLogOnInfo();
            ConnectionInfo  reportConInfo    = new ConnectionInfo();
            Tables          tables           = default(Tables);
            //	Table table = default(Table);
            var with1 = reportConInfo;

            with1.ServerName   = "tcp:KyotoServer,49172";
            with1.DatabaseName = "ProductNRelatedDB";
            with1.UserID       = "sa";
            with1.Password     = "******";
            ReportDocument cr = new ReportDocument();

            if (brandid == 1)
            {
                cr = new DeliOAckOmron();
            }
            else if (brandid == 2)
            {
                cr = new DelOAckWithoutLogo();
            }
            else if (brandid == 3)
            {
                cr = new DelOAckAzbil();
            }
            else if (brandid == 4)
            {
                cr = new DelOAckBusinessAutomation();
            }
            else if (brandid == 5)
            {
                cr = new DelOAckIRD();
            }
            else if (brandid == 6)
            {
                cr = new DelOAckKawashima();
            }
            else if (brandid == 7)
            {
                cr = new DelOAckChigo();
            }
            else if (brandid == 8)
            {
                cr = new DelOAckSamsung();
            }
            tables = cr.Database.Tables;
            foreach (Table table in tables)
            {
                reportLogonInfo = table.LogOnInfo;
                reportLogonInfo.ConnectionInfo = reportConInfo;
                table.ApplyLogOnInfo(reportLogonInfo);
            }

            Sections        m_boSections;
            ReportObjects   m_boReportObjects;
            SubreportObject m_boSubreportObject;

            //create a new ReportDocument


            //get all the sections in the report
            m_boSections = cr.ReportDefinition.Sections;
            //loop through each section of the report
            foreach (Section m_boSection in m_boSections)
            {
                m_boReportObjects = m_boSection.ReportObjects;
                //loop through each report object
                foreach (ReportObject m_boReportObject in m_boReportObjects)
                {
                    if (m_boReportObject.Kind == ReportObjectKind.SubreportObject)
                    {
                        //get the actual subreport object
                        m_boSubreportObject = (SubreportObject)m_boReportObject;

                        //set subreport to the dataset e.g.;
                        // boReportDocument.SetDataSource(oDataSet);
                        // or
                        // boTable.SetDataSource(oDataSet.Tables[tableName]);
                    }
                }
            }
            //show in reportviewer
            //crystalReportViewer1.ReportSource = m_boReportDocument;
            BArcode ds = new BArcode();

            var content = refno;
            var writer  = new BarcodeWriter
            {
                Format  = BarcodeFormat.CODE_128,
                Options = new EncodingOptions
                {
                    PureBarcode = true,
                    Height      = 100,
                    Width       = 465
                }
            };
            var png = writer.Write(content);

            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            png.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);

            DataRow dtr = ds.Tables[0].NewRow();

            dtr["REF"]          = refno;
            dtr["BarcodeImage"] = ms.ToArray();
            ds.Tables[0].Rows.Add(dtr);
            cr.Subreports["BarCode.rpt"].DataSourceConnections.Clear();
            cr.Subreports["BarCode.rpt"].SetDataSource(ds);
            f2.crystalReportViewer1.ParameterFieldInfo = paramFields1;
            f2.crystalReportViewer1.ReportSource       = cr;
            this.Visible = false;
            f2.ShowDialog();
            this.Visible = true;
            backgroundWorker1.CancelAsync();
            backgroundWorker1.Dispose();
            progressBar1.Visible = false;
            button1.Enabled      = true;
        }
Beispiel #17
0
        private void generate(string sk)
        {
            blank_voucher();
            if ((!check_rawsk.Checked) && (!check_mobile.Checked))
            {
                MessageBox.Show("You need to include at least one private key format.", "Select private key format");
                return;
            }

            string address      = AddressEncoding.ToEncoded(0x68, new PublicKey(new PrivateKey(sk)));
            string splitaddress = address.Substring(0, 20) + Environment.NewLine + address.Substring(20, address.Length - 20);

            lbl_Address.Text = splitaddress;

            if (check_mobile.Checked)
            {
                string password = txt_password.Text;
                if ((password.Equals("")) | (password.Length < 6))
                {
                    MessageBox.Show("For mobile wallet support you need to provide a password with at least 6 characters.", "Provide password", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }

                string walletname = txt_walletname.Text;
                if ((walletname.Equals("")) | (walletname.Length < 1))
                {
                    MessageBox.Show("For mobile wallet support you need to provide a wallet name.", "Provide name", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }

                if ((!Regex.IsMatch(walletname, @"^[a-zA-Z0-9]+$")) || (!Regex.IsMatch(password, @"^[a-zA-Z0-9]+$")))
                {
                    MessageBox.Show("Your password or walletname contains special or country specific characters, this is not fully tested, please assure you can import the wallet before sending XEM to it!", "Special characters in use", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }

                // Generate salt
                string salt;
                using (RandomNumberGenerator rng = new RNGCryptoServiceProvider())
                {
                    byte[] tokenData = new byte[32];
                    rng.GetBytes(tokenData);

                    salt = ByteArrayToString(tokenData);
                }

                //To do: ADD WALLET NAME
                //txt_walletname.Text
                String sk_encoded = voucher.GenEncsk(txt_walletname.Text, password, sk, salt);
                //Console.WriteLine (sk_encoded);

                //generate secret encoded key barcode
                IBarcodeWriter writerskencoded = new BarcodeWriter
                {
                    Format  = BarcodeFormat.QR_CODE,
                    Options = new ZXing.Common.EncodingOptions
                    {
                        Width  = 200,
                        Height = 200,
                    }
                };
                var codesk          = writerskencoded.Write(sk_encoded);
                var barcodeBitmapsk = new Bitmap(codesk);
                picbox_sk_mobile.Image = barcodeBitmapsk;

                picbox_sk_mobile.Visible = true;
                lbl_mob_format.Visible   = true;
                if (check_showPW.Checked)
                {
                    lbl_password.Text    = "Import password: "******"";
                for (int i = 0; i < 64; i += 8)
                {
                    lbl_sk.Text = lbl_sk.Text + (sk.Substring(i, 8).ToUpper() + Environment.NewLine);
                }

                //lbl_sk.Text = sk;
                lbl_sk.Visible         = true;
                lbl_raw_format.Visible = true;
            }



            //generate NEM address barcode
            string         address_qr   = "{\"v\":2,\"type\":1,\"data\":{\"addr\":\"" + address + "\",\"name\":\"" + txt_walletname.Text + "\"}}";
            IBarcodeWriter writeradress = new BarcodeWriter
            {
                Format  = BarcodeFormat.QR_CODE,
                Options = new ZXing.Common.EncodingOptions
                {
                    Width  = 150,
                    Height = 150
                }
            };
            var codeadress           = writeradress.Write(address_qr);
            var barcodeBitmapAddress = new Bitmap(codeadress);

            picbox_Address.Image   = barcodeBitmapAddress;
            picbox_Address.Visible = true;
            lbl_Address.Visible    = true;


            //string expected = "NAZQOWGZJ5PKR3QJEUZEMS6MXQX3WZZZAKKTLPZT";
        }
Beispiel #18
0
        private void button1_Click(object sender, EventArgs e)
        {
            if (Init() == false)
            {
                return;
            }

            IntPtr windowsDCHandle = GetWindowDC(IntPtr.Zero);

            if (windowsDCHandle == IntPtr.Zero)
            {
                MessageBox.Show("Cannot open GetWindowDC.");
                return;
            }


            Rectangle rectangle = new Rectangle();

            if (GetWindowRect(WxProcess.MainWindowHandle, ref rectangle) == 0)
            {
                MessageBox.Show("Cannot open GetWindowRect.");
                return;
            }
            //int width = rectangle.Width - rectangle.X;
            //int height = rectangle.Height - rectangle.Y;

            int width  = rectangle.Width;
            int height = rectangle.Height;

            IntPtr createCompatibleBitmap = CreateCompatibleBitmap(windowsDCHandle, width, height);

            if (createCompatibleBitmap == IntPtr.Zero)
            {
                MessageBox.Show("Cannot open CreateCompatibleBitmap.");
                return;
            }


            IntPtr createCompatibleDC = CreateCompatibleDC(windowsDCHandle);


            if (createCompatibleDC == IntPtr.Zero)
            {
                MessageBox.Show("Cannot open CreateCompatibleDC.");
                return;
            }



            if (SelectObject(createCompatibleDC, createCompatibleBitmap) == IntPtr.Zero)
            {
                MessageBox.Show("Cannot open SelectObject.");
                return;
            }



            if (PrintWindow(WxProcess.MainWindowHandle, createCompatibleDC, 0) == 0)
            {
                MessageBox.Show("Cannot open PrintWindow.");
                return;
            }

            this.pictureBox1.Width  = width;
            this.pictureBox1.Height = height;
            this.pictureBox1.Image  = Image.FromHbitmap(createCompatibleBitmap);

            this.pictureBox1.Image.Save(Environment.CurrentDirectory + "\\wx.png", ImageFormat.Png);

            int qrWidth  = 280;
            int qrHeight = 280;

            Image    qrImage  = new Bitmap(qrWidth, qrHeight);
            Graphics graphics = Graphics.FromImage(qrImage);

            graphics.DrawImage(Image.FromHbitmap(createCompatibleBitmap),
                               new Rectangle(0, 0, qrWidth, qrHeight),
                               new Rectangle(40, 80, qrWidth, qrHeight), GraphicsUnit.Pixel);
            graphics.Dispose();

            this.pictureBox2.Width  = qrWidth;
            this.pictureBox2.Height = qrHeight;
            this.pictureBox2.Image  = qrImage;


            DeleteObject(createCompatibleBitmap);
            DeleteDC(createCompatibleBitmap);
            ReleaseDC(WxProcess.MainWindowHandle, windowsDCHandle);


            // create a barcode reader instance
            IBarcodeReader reader = new BarcodeReader();
            // load a bitmap
            var barcodeBitmap = (Bitmap)this.pictureBox1.Image;
            // detect and decode the barcode inside the bitmap
            var result = reader.Decode(barcodeBitmap);

            // do something with the result
            if (result != null)
            {
                this.textBox1.Text = result.Text;
            }

            BarcodeWriter barcodeWriter = new BarcodeWriter();

            barcodeWriter.Format = BarcodeFormat.QR_CODE;
            QrCodeEncodingOptions options = new QrCodeEncodingOptions();

            options.Width         = 280;
            options.Height        = 280;
            options.Margin        = 2;
            barcodeWriter.Options = options;
            Bitmap bitmap = barcodeWriter.Write(this.textBox1.Text);

            this.pictureBox3.Width  = 280;
            this.pictureBox3.Height = 280;
            this.pictureBox3.Image  = bitmap;
        }
        /// <summary>
        /// 生成二维码
        /// </summary>
        /// <param name="contents">待生成二维码的文字</param>
        /// <param name="logoImage">logo图片</param>
        /// <param name="width">宽</param>
        /// <param name="height">高</param>
        /// <param name="disableMargin">是否禁止生成边界</param>
        /// <returns></returns>
        internal static byte[] CreateStream(string contents, Stream logoImage = null, int width = 360, int height = 360, bool disableMargin = true)
        {
            if (string.IsNullOrEmpty(contents))
            {
                return(null);
            }
            //本文地址:http://www.cnblogs.com/Interkey/p/qrcode.html
            EncodingOptions options = null;
            BarcodeWriter   writer  = null;

            options = new QrCodeEncodingOptions
            {
                DisableECI      = true,
                CharacterSet    = "UTF-8",
                Width           = width,
                Height          = height,
                ErrorCorrection = ErrorCorrectionLevel.H,
            };
            if (disableMargin)
            {
                options.Margin = 0;
            }
            writer         = new BarcodeWriter();
            writer.Format  = BarcodeFormat.QR_CODE;
            writer.Options = options;
            // 获取二维码图片
            using (SKBitmap qrBitmap = writer.Write(contents))
            {
                if (qrBitmap == null)
                {
                    throw new ImageException("生成二维码失败");
                }
                using (SKSurface surface = SKSurface.Create(new SKImageInfo(qrBitmap.Width, qrBitmap.Height)))
                {
                    SKCanvas canvas = surface.Canvas;
                    canvas.Clear(SKColors.White);
                    // 绘制二维码
                    canvas.DrawBitmap(qrBitmap, 0, 0);
                    if (logoImage != null && logoImage.Length > 0)
                    {
                        using (SKManagedStream managedStream = new SKManagedStream(logoImage))
                        {
                            using (SKBitmap logoBitmap = SKBitmap.Decode(managedStream))
                            {
                                if (logoBitmap != null)
                                {
                                    int deltaHeight = qrBitmap.Height - logoBitmap.Height;
                                    int deltaWidth  = qrBitmap.Width - logoBitmap.Width;
                                    canvas.DrawBitmap(logoBitmap, deltaWidth / 2, deltaHeight / 2);
                                }
                            }
                        }
                    }
                    using (SKImage image = surface.Snapshot())
                    {
                        using (SKData data = image.Encode(SKEncodedImageFormat.Jpeg, 100))
                        {
                            return(data.ToArray());
                        }
                    }
                }
            }
        }
Beispiel #20
0
        public Bitmap GenerateQRCode(string contents, PictureBox qrimage, string codeType,
                                     string codeColor, string erroCorrectionLevel, bool isShowCode = false)
        {
            if (contents == string.Empty)
            {
                MessageBox.Show("invalid input");
                return(null);
            }

            if (codeColor == null)
            {
                codeColor = "Black";
            }

            BarcodeWriter writer = new BarcodeWriter();

            var encOptions = new ZXing.Common.EncodingOptions
            {
                Width       = qrimage.Width,
                Height      = qrimage.Height,
                Margin      = 0,
                PureBarcode = false
            };

            switch (erroCorrectionLevel)
            {
            case "L":
                encOptions.Hints.Add(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
                break;

            case "M":
                encOptions.Hints.Add(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
                break;

            case "Q":
                encOptions.Hints.Add(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.Q);
                break;

            case "H":
                encOptions.Hints.Add(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
                break;

            default:
                encOptions.Hints.Add(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
                break;
            }

            encOptions.Hints.Add(EncodeHintType.CHARACTER_SET, "UTF-8");

            writer.Renderer = new BitmapRenderer()
            {
                Foreground = Color.FromName(codeColor)
            };

            writer.Options = encOptions;

            switch (codeType)
            {
            case "CODE_128":
                writer.Format = ZXing.BarcodeFormat.CODE_128;
                break;

            case "QR_CODE":
                writer.Format = ZXing.BarcodeFormat.QR_CODE;
                break;

            case "PDF_417":
                writer.Format = ZXing.BarcodeFormat.PDF_417;
                break;

            default:
                writer.Format = ZXing.BarcodeFormat.QR_CODE;
                break;
            }

            Bitmap bitmap = writer.Write(contents);

            if (isShowCode == true)
            {
                qrimage.Image = bitmap;
            }

            return(bitmap);
        }
Beispiel #21
0
        private void btnCreateQRData_Click(object sender, EventArgs e) //2017-11-11 09:20:41 生成二维码数据
        {
            string pwd = txtQRPassword.Text;

            this.dtpActivate.Value   = DateTime.Parse(string.Format("{0} {1}", this.dtpActivate.Value.ToString("yyyy-MM-dd"), "00:00:00"));
            this.dtpDeactivate.Value = DateTime.Parse(string.Format("{0} {1}", this.dtpDeactivate.Value.ToString("yyyy-MM-dd"), this.dateEndHMS1.Value.ToString("HH:mm:ss")));
            byte[] sendData =
            {
                (byte)0, (byte)0, (byte)0, (byte)0, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00,
                (byte)0, (byte)0, (byte)0, (byte)0, (byte)0,    (byte)0,    (byte)0x00, (byte)0x00
            };
            byte[] pwdData =
            {
                (byte)0, (byte)0, (byte)0, (byte)0, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00,
                (byte)0, (byte)0, (byte)0, (byte)0, (byte)0,    (byte)0,    (byte)0x00, (byte)0x00
            };

            sendData[15] = 2; //固定

            //起始日期时间
            DateTime ptm = dtpActivate.Value;
            long     ymd = getYMD(ptm.Year, ptm.Month, ptm.Day);
            long     hms = getHMS(ptm.Hour, ptm.Minute, ptm.Second);

            sendData[8]  = (byte)(ymd & 0xff);
            sendData[9]  = (byte)((ymd >> 8) & 0xff);
            sendData[10] = (byte)((hms >> 8) & 0xff); //高位
            sendData[11] = (byte)(hms & 0xE0);        //低位

            //截止日期时间
            ptm          = dtpDeactivate.Value;
            ymd          = getYMD(ptm.Year, ptm.Month, ptm.Day);
            hms          = getHMS(ptm.Hour, ptm.Minute, ptm.Second);
            sendData[11] = (byte)(sendData[11] + ((hms & 0xE0) >> 4));
            sendData[12] = (byte)(ymd & 0xff);
            sendData[13] = (byte)((ymd >> 8) & 0xff);
            sendData[14] = (byte)((hms >> 8) & 0xff);
            if ((hms & 0xE0) == 0xE0) //2018-09-20 19:17:39 修改部分
            {
                sendData[14] = (byte)(sendData[14] + 1);
            }
            long cardNO = long.Parse(this.txtCardNO.Text);

            if (cardNO > 0)
            {
                sendData[0] = (byte)(cardNO & 0xff);
                sendData[1] = (byte)((cardNO >> 8) & 0xff);
                sendData[2] = (byte)((cardNO >> 16) & 0xff);
                sendData[3] = (byte)((cardNO >> 24) & 0xff);
                sendData[4] = (byte)((cardNO >> 32) & 0xff);
                sendData[5] = (byte)((cardNO >> 40) & 0xff);
                sendData[6] = (byte)((cardNO >> 48) & 0xff);
                sendData[7] = (byte)((cardNO >> 56) & 0xff);
                if (chkCardWithCRCCheck.Checked)     //2017-12-18 22:28:05 需要驱动V8.82版本
                {
                    sendData[7] = crc8(sendData, 7); //2017-12-18 22:03:47 校验和
                }
            }

            byte[] p = Encoding.UTF8.GetBytes(pwd);
            for (int i = 0; i < p.Length && i < 16; i++)
            {
                pwdData[i] = p[i];
            }


            EncryptSM4_ECB(ref sendData, pwdData);

            txtQRData.Text = System.BitConverter.ToString(sendData).Replace("-", "");

            // textBoxText.Text
            string info = System.BitConverter.ToString(sendData).Replace("-", "");

            EncodingOptions options = null;
            BarcodeWriter   writer  = null;

            options = new QrCodeEncodingOptions
            {
                DisableECI   = true,
                CharacterSet = "UTF-8",
                Margin       = 1,
                Width        = pictureBoxQr.Width,
                Height       = pictureBoxQr.Height
            };
            writer         = new BarcodeWriter();
            writer.Format  = BarcodeFormat.QR_CODE;
            writer.Options = options;
            Bitmap bitmap = writer.Write(info);

            pictureBoxQr.Image   = bitmap;
            pictureBoxQr.Visible = true;
        }
Beispiel #22
0
        private void Codify_Load(object sender, EventArgs e)
        {
            Width       = 800;
            Height      = 600;
            MinimizeBox = false;
            MaximizeBox = false;
            //Set the components into screen
            //Picturebox

            qrCode.Height    = 180;
            qrCode.Width     = 180;
            qrCode.Location  = new Point(320, 60);
            qrCode.BackColor = Color.Blue;
            qrCode.Visible   = true;
            qrCode.SizeMode  = PictureBoxSizeMode.StretchImage;

            Controls.Add(qrCode);


            //TextBox Codify

            txtBoxCodify.Width        = 730;
            txtBoxCodify.Height       = 250;
            txtBoxCodify.Location     = new Point(0, 300);
            txtBoxCodify.BackColor    = Color.Black;
            txtBoxCodify.Font         = new Font("Times New Roman", 12, FontStyle.Bold);
            txtBoxCodify.ForeColor    = Color.White;
            txtBoxCodify.TextChanged += delegate
            {
                CreateQRCode(txtBoxCodify.Text);
            };
            Controls.Add(txtBoxCodify);
            //Button Load Image

            btnLoadImage.Width    = 50;
            btnLoadImage.Height   = 30;
            btnLoadImage.AutoSize = true;
            btnLoadImage.Location = new Point(120, 60);
            /*Color*/
            /*Font*/
            /*Forecolor*/
            btnLoadImage.Text = "Carregar a Partir de Uma Imagem";
            Controls.Add(btnLoadImage);

            //Button Save Image
            Button buttonSaveImage = new Button();

            buttonSaveImage.Width    = 50;
            buttonSaveImage.Height   = 30;
            buttonSaveImage.AutoSize = true;
            buttonSaveImage.Location = new Point(120, 90);
            /*Color*/
            /*Font*/
            /*Forecolor*/
            buttonSaveImage.Text = "Salvar QR code";
            Controls.Add(buttonSaveImage);
            buttonSaveImage.Click += delegate
            {
                SaveFileDialog saveQRCode = new SaveFileDialog();
                saveQRCode.DefaultExt   = ".jpg";
                saveQRCode.AddExtension = true;
                //Saves the file
                if (saveQRCode.ShowDialog() == DialogResult.OK)
                {
                    qrCode.Image.Save(saveQRCode.FileName, System.Drawing.Imaging.ImageFormat.Jpeg);
                }
            };

            //Transforms the qr code into a barcode
            btnBarCodeTransform.Width    = 50;
            btnBarCodeTransform.Height   = 30;
            btnBarCodeTransform.AutoSize = true;
            btnBarCodeTransform.Location = new Point(590, 60);
            /*Color*/
            /*Font*/
            /*Forecolor*/
            btnBarCodeTransform.Text = "Transformar em Código de Barras";
            Controls.Add(btnBarCodeTransform);
            btnBarCodeTransform.Click += delegate
            {
                BarcodeWriter createBarcode = new BarcodeWriter();
                createBarcode.Format = BarcodeFormat.MAXICODE;
                try
                {
                    qrCode.Image = createBarcode.Write(txtBoxCodify.Text);
                }
                catch
                {
                }
            };
        }
Beispiel #23
0
        public void printOutSlip(responseSaveVn app)
        {
            try
            {
                string fontName           = "Tahoma";
                Font   fontRegular        = new Font(fontName, 16, FontStyle.Regular, GraphicsUnit.Pixel);
                Font   fontBold           = new Font(fontName, 16, FontStyle.Bold, GraphicsUnit.Pixel);
                Font   fontBoldUnderline  = new Font(fontName, 16, FontStyle.Bold | FontStyle.Underline, GraphicsUnit.Pixel);
                Font   fontSuperBold      = new Font(fontName, 28, FontStyle.Bold, GraphicsUnit.Pixel);
                Font   superBoldUnderline = new Font(fontName, 28, FontStyle.Bold | FontStyle.Underline, GraphicsUnit.Pixel);

                Font superBoldv2 = new Font(fontName, 24, FontStyle.Bold, GraphicsUnit.Pixel);

                byte[] PartialCut = { 0x0A, 0x0A, 0x0A, 0x1B, 0x69 };
                System.Globalization.CultureInfo _cultureTHInfo = new System.Globalization.CultureInfo("th-TH");
                string currDate = DateTime.Now.ToString("dd-MM-yyyy HH:mm:ss", _cultureTHInfo);

                Printer printer = new Printer(smConfig.printerName);

                printer.AlignCenter();

                printer.Image(DrawTextImg($"คิวห้องตรวจ {app.queueNumber}", superBoldv2));
                printer.NewLines(3);

                printer.Image(new Bitmap(Bitmap.FromFile("Images/small-icon.bmp")));
                printer.Image(DrawTextImg(currDate, fontRegular));
                printer.Image(DrawTextImg(app.ex, fontRegular));
                printer.Image(DrawTextImg("HN : " + app.hn, superBoldUnderline));
                printer.Image(DrawTextImg("VN : " + app.vn, superBoldUnderline));
                printer.NewLine();
                printer.Image(DrawTextImg($"ชื่อ : {app.ptname}", fontBold));
                printer.NewLine();
                printer.Image(DrawTextImg($"สิทธิ : {app.ptright}", fontBoldUnderline));
                if (!String.IsNullOrEmpty(app.hospCode))
                {
                    printer.Image(DrawTextImg(app.hospCode, fontRegular));
                }

                printer.Image(DrawTextImg($"อายุ {app.age}", fontRegular));
                printer.Image(DrawTextImg($"บัตร ปชช. : {app.idcard}", fontRegular));
                printer.Image(DrawTextImg(app.mx, fontRegular));
                printer.NewLine();
                printer.Image(DrawTextImg($"คิวซักประวัติที่ {app.fakeQueue}", fontBold));
                printer.NewLine();

                if (!String.IsNullOrEmpty(app.doctor))
                {
                    printer.Image(DrawTextImg(app.doctor, fontRegular));
                }
                else
                {
                    printer.Image(DrawTextImg("แพทย์.....................", fontRegular));
                }

                /*
                 * var writer = new BarcodeWriter
                 * {
                 *  Format = BarcodeFormat.QR_CODE,
                 *  Options = new ZXing.Common.EncodingOptions
                 *  {
                 *      Height = 160,
                 *      Width = 306
                 *  }
                 * };
                 * var qrCodeImg = writer.Write(app.hn);
                 * printer.Image(qrCodeImg);
                 */

                var writer2 = new BarcodeWriter
                {
                    Format  = BarcodeFormat.CODE_39,
                    Options = new ZXing.Common.EncodingOptions
                    {
                        Height      = 60,
                        Width       = 306,
                        PureBarcode = true
                    }
                };
                var barcodeImg = writer2.Write(app.hn);
                printer.Image(barcodeImg);
                printer.Image(DrawTextImg("ยื่นรับยาที่ช่องหมายเลข6", fontBold));
                printer.Image(new Bitmap(Bitmap.FromFile("Images/extra.bmp")));

                //printer.Image(DrawTextImg($"หากที่อยู่ของท่านมีการเปลี่ยนแปลง", fontBold));
                //printer.Image(DrawTextImg($"กรุณาแจ้งแผนกทะเบียน", fontBold));
                //printer.Image(DrawTextImg($"เพื่อประโยชน์และสิทธิ์ของท่านเอง", fontBold));
                printer.NewLines(8);
                printer.Append(PartialCut);

                //////
                if (app.queueStatus == "y")
                {
                    //printer.Image(new Bitmap(Bitmap.FromFile("Images/small-icon2.bmp")));
                    //printer.Image(DrawTextImg(currDate, fontRegular));
                    //printer.NewLine();

                    /*
                     * printer.Image(DrawTextImg("บัตรคิวซักประวัติ", fontBold));
                     * printer.NewLine();
                     * printer.Image(DrawTextImg(app.queueRoom, fontRegular));
                     * printer.NewLine();
                     * printer.Image(DrawTextImg($"HN : {app.hn}", fontSuperBold));
                     * printer.NewLine();
                     * printer.Image(DrawTextImg($"ชื่อ : {app.ptname}", fontRegular));
                     * printer.Image(DrawTextImg($"ประเภท : {app.ptType}", fontRegular));
                     * printer.NewLine();
                     * printer.Image(DrawTextImg(app.queueNumber, fontSuperBold));
                     * printer.NewLine();
                     * printer.Image(DrawTextImg($"คิวพบแพทย์ผู้ป่วยนัด", fontRegular));
                     * printer.NewLines(8);
                     * printer.Append(PartialCut);
                     */

                    //printer.Image(new Bitmap(Bitmap.FromFile("Images/small-icon2.bmp")));
                    //printer.Image(DrawTextImg(currDate, fontRegular));
                    //printer.NewLine();
                    printer.Image(DrawTextImg("คิวพบแพทย์ผู้ป่วยนัด", fontBold));
                    printer.Image(DrawTextImg(currDate, fontRegular));
                    printer.Image(DrawTextImg(app.queueNumber, fontSuperBold));
                    printer.Image(DrawTextImg(app.queueRoom + " คิวที่ " + app.runNumber, fontRegular));
                    //printer.Image(DrawTextImg($"เลขคิวห้องตรวจ {app.runNumber}", fontSuperBold, 32));
                    printer.NewLine();
                    printer.Image(DrawTextImg($"คิวซักประวัติที่ {app.fakeQueue}", fontSuperBold, 32));
                    printer.NewLine();
                    if (!String.IsNullOrEmpty(app.doctor))
                    {
                        printer.Image(DrawTextImg(app.doctor, fontRegular));
                    }
                    else
                    {
                        printer.Image(DrawTextImg("แพทย์.....................", fontRegular));
                    }
                    printer.Image(DrawTextImg($"HN : {app.hn}", fontBold));
                    printer.Image(DrawTextImg($"ชื่อ : {app.ptname}", fontRegular));
                    printer.Image(DrawTextImg($"ประเภท : {app.ptType}", fontRegular));
                    printer.Image(DrawTextImg($"จำนวนคิวที่รอ {app.queueWait} คิว", fontRegular));
                    printer.Image(DrawTextImg($"ใบคิวสำหรับผู้ป่วย โปรดเก็บไว้กับตัว", fontBold));
                    printer.NewLines(8);
                    printer.Append(PartialCut);
                }
                //////
                printer.PrintDocument();
            }
            catch (Exception ex)
            {
                MessageBox.Show("ไม่สามารถพิมพ์ได้ " + ex.Message, "แจ้งเตือน");
                Console.WriteLine(ex.Message);
            }
        }
        public async Task <ReturnBaseMessageModel> MultipleGetQRCode(List <MainQRCodeModel.MultipleQRCodeModel> content)
        {
            try
            {
                //var fName = string.Format(DateTime.Now.ToString() + "- .pdf", DateTime.Now.ToString("s"));

                // HttpResponseMessage result = new HttpResponseMessage();
                string alt    = "QR Code";
                int    height = 500;
                int    width  = 500;
                int    margin = 0;



                var qrWriter = new BarcodeWriter()
                {
                    Format  = BarcodeFormat.QR_CODE,
                    Options = new ZXing.Common.EncodingOptions()
                    {
                        Height = height, Width = width, Margin = margin
                    }
                };
                var    filename = HttpContext.Current.Server.MapPath("~/Images/LogoBarcode2.png");
                Bitmap overlay  = new Bitmap(filename);
                //List<string> list = new List<string>();
                List <MainQRCodeModel.MultipleQRCodeModel> list = new List <MainQRCodeModel.MultipleQRCodeModel>();


                //list.multipleQRCodeModel = new List<MainQRCodeModel.MultipleQRCodeModel>();
                HttpContext.Current.Server.ScriptTimeout = 300;

                await Task.Run(() =>
                {
                    foreach (var item in content)
                    {
                        MainQRCodeModel.MultipleQRCodeModel singlelist = new MainQRCodeModel.MultipleQRCodeModel();
                        using (var q = qrWriter.Write(item.id.Trim()))
                        {
                            //Bitmap overlay=new Bitmap()
                            using (var ms = new MemoryStream())
                            {
                                int deltaHeigth = q.Height - overlay.Height;
                                int deltaWidth  = q.Width - overlay.Width;
                                Graphics g      = Graphics.FromImage(q);
                                g.DrawImage(overlay, new Point(deltaWidth / 2, deltaHeigth / 2));

                                q.Save(ms, ImageFormat.Png);
                                var qrcode = Convert.ToBase64String(ms.ToArray());
                                //list.Add(qrcode);
                                singlelist.generatedQRCode = qrcode;
                                singlelist.custid          = item.custid.Trim();
                                singlelist.custname        = item.custname.Trim();
                            }
                            list.Add(singlelist);
                        }
                    }
                });

                //string result = "";
                // return( list.ToArray());
                var fName = HttpContext.Current.Session;

                //var qrResult = list.ToArray();
                var qrResult = list;
                fName["fName"] = qrResult;
                var Datewithtime = DateTime.Now;
                var date         = Datewithtime.Date;
                returnMessage.Value   = string.Format(date.ToString() + ".jpg");
                returnMessage.Success = true;



                return(returnMessage);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        //20190515
        public Bitmap setProductPage2(Page1 PData)
        {
            Bitmap        bmp       = new Bitmap(212, 104);
            BarcodeWriter barcode_w = new BarcodeWriter();

            /* string[] temp = new string[] { "瑞", "新", "電", "子", "SMC", "Robert", "Lun", "Willy", "永", "晴", "恭", "賀", "Mini", "壓", "單", "提", "剛", "網", "賽", "鑫", "覦", "§"
             * , "●", "€", "$", "わ", "ら", "や", "ま", "は", "な", "た", "さ", "か", "あ", "め", "つ", "ち", "の", "â", "ī", "u", "â", "û", "ô", "电", "子", "货", "价", "标", "签", "折"
             * , "扣", "特", "殺", "杀", "下", "잘", "지", "냈", "어", "요", "수", "께", "끼", "는", "한", "국", "고", "유의", "언어", "문화적", "ESL", "Special"};
             */

            using (Graphics graphics = Graphics.FromImage(bmp))
            {
                graphics.FillRectangle(new SolidBrush(Color.White), 0, 0, 212, 104);
            }


            TextBox t1 = new TextBox();

            t1.Text        = "ESL " + PData.bleAddress;
            t1.Font        = new Font("Cambria", 10, FontStyle.Bold);
            t1.TextAlign   = HorizontalAlignment.Left; //置中
            t1.BorderStyle = BorderStyle.FixedSingle;
            t1.Width       = 140;
            t1.Height      = 22;
            bmp            = mSmcDataToImage.ConvertTextToImage(bmp, t1, Color.Black, 66, 5);

            String StrName = String.Format("{0}", DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"));

            t1.Text        = "科號 " + PData.barcode;
            t1.Font        = new Font("Cambria", 10, FontStyle.Bold);
            t1.TextAlign   = HorizontalAlignment.Left; //置中
            t1.BorderStyle = BorderStyle.FixedSingle;
            t1.Width       = 140;
            t1.Height      = 22;
            bmp            = mSmcDataToImage.ConvertTextToImage(bmp, t1, Color.Black, 66, 29);


            t1.Text        = "品名 " + PData.product_name;;
            t1.Font        = new Font("Cambria", 10, FontStyle.Bold);
            t1.TextAlign   = HorizontalAlignment.Left; //置中
            t1.BorderStyle = BorderStyle.FixedSingle;
            t1.Width       = 140;
            t1.Height      = 22;
            bmp            = mSmcDataToImage.ConvertTextToImage(bmp, t1, Color.Black, 66, 53);

            t1.Text        = "貨架: " + PData.shelf;
            t1.Font        = new Font("Cambria", 10, FontStyle.Bold);
            t1.TextAlign   = HorizontalAlignment.Left; //置中
            t1.BorderStyle = BorderStyle.FixedSingle;
            t1.Width       = 140;
            t1.Height      = 22;
            bmp            = mSmcDataToImage.ConvertTextToImage(bmp, t1, Color.Black, 66, 77);


            Bitmap bar = new Bitmap(70, 70);

            barcode_w.Format         = BarcodeFormat.QR_CODE;
            barcode_w.Options.Width  = 70;
            barcode_w.Options.Height = 70;
            barcode_w.Options.Margin = 0;
            //barcode_w.Options.PureBarcode = true;
            bar = barcode_w.Write(PData.barcode);
            bmp = mSmcDataToImage.ConvertImageToImage(bmp, bar, 0, 16); //QRcode



            return(bmp);
        }
 public Bitmap GetGraphic(string content)
 {
     return(writer.Write(content));
 }
        public Bitmap setPage2E(string MacAddress, string rssi)
        {
            Bitmap bmp = new Bitmap(212, 104);



            using (Graphics graphics = Graphics.FromImage(bmp))
            {
                graphics.FillRectangle(new SolidBrush(Color.White), 0, 0, 212, 104);
            }

            Bitmap        bar       = new Bitmap(210, 30);
            BarcodeWriter barcode_w = new BarcodeWriter();

            barcode_w.Format              = BarcodeFormat.CODE_93;
            barcode_w.Options.Width       = 160;
            barcode_w.Options.Height      = 20;
            barcode_w.Options.PureBarcode = true;
            bar = barcode_w.Write(MacAddress);
            bmp = mSmcDataToImage.ConvertImageToImage(bmp, bar, 30, 80); //QRcode



            TextBox t1 = new TextBox();

            /*  t1.Text = "SMC ESL";
             * t1.Font = new Font("Cambria", 20, FontStyle.Bold);
             * t1.TextAlign = HorizontalAlignment.Center; //置中
             * t1.BorderStyle = BorderStyle.FixedSingle;
             * t1.Width = 150;
             * t1.Height = 25;
             * bmp = mSmcDataToImage.ConvertTextToImage(bmp, t1, Color.Red, 25, 0);*/

            t1.Text        = "FX28387";
            t1.Font        = new Font("新細明體", 11, FontStyle.Bold);
            t1.TextAlign   = HorizontalAlignment.Center; //置中
            t1.BorderStyle = BorderStyle.FixedSingle;
            t1.Width       = 67;
            t1.Height      = 15;
            bmp            = mSmcDataToImage.ConvertTextToImage(bmp, t1, Color.Black, 134, 2);

            t1.Text        = "作业日 2019.02.18";
            t1.Font        = new Font("新細明體", 9, FontStyle.Regular);
            t1.TextAlign   = HorizontalAlignment.Center; //置中
            t1.BorderStyle = BorderStyle.FixedSingle;
            t1.Width       = 98;
            t1.Height      = 12;
            bmp            = mSmcDataToImage.ConvertTextToImage(bmp, t1, Color.Black, 9, 5);

            t1.Text        = "(13 : 11 : 05)";
            t1.Font        = new Font("新細明體", 9, FontStyle.Regular);
            t1.TextAlign   = HorizontalAlignment.Center; //置中
            t1.BorderStyle = BorderStyle.FixedSingle;
            t1.Width       = 98;
            t1.Height      = 12;
            bmp            = mSmcDataToImage.ConvertTextToImage(bmp, t1, Color.Black, 9, 18);

            t1.Text        = "装载量 120 (M) -1";
            t1.Font        = new Font("新細明體", 9, FontStyle.Regular);
            t1.TextAlign   = HorizontalAlignment.Left; //置中
            t1.BorderStyle = BorderStyle.FixedSingle;
            t1.Width       = 96;
            t1.Height      = 12;
            bmp            = mSmcDataToImage.ConvertTextToImage(bmp, t1, Color.Black, 6, 60);

            t1.Text        = "压延日 2019.02.16";
            t1.Font        = new Font("新細明體", 9, FontStyle.Regular);
            t1.TextAlign   = HorizontalAlignment.Left; //置中
            t1.BorderStyle = BorderStyle.FixedSingle;
            t1.Width       = 98;
            t1.Height      = 12;
            bmp            = mSmcDataToImage.ConvertTextToImage(bmp, t1, Color.Black, 6, 32);

            t1.Text        = "18 : 21";
            t1.Font        = new Font("新細明體", 9, FontStyle.Regular);
            t1.TextAlign   = HorizontalAlignment.Left; //置中
            t1.BorderStyle = BorderStyle.FixedSingle;
            t1.Width       = 98;
            t1.Height      = 12;
            bmp            = mSmcDataToImage.ConvertTextToImage(bmp, t1, Color.Black, 49, 46);

            t1.Text        = "作业者 C - 贺小风";
            t1.Font        = new Font("新細明體", 9, FontStyle.Regular);
            t1.TextAlign   = HorizontalAlignment.Left; //置中
            t1.BorderStyle = BorderStyle.FixedSingle;
            t1.Width       = 98;
            t1.Height      = 12;
            bmp            = mSmcDataToImage.ConvertTextToImage(bmp, t1, Color.Black, 110, 60);

            t1.Text        = "特性";
            t1.Font        = new Font("新細明體", 9, FontStyle.Regular);
            t1.TextAlign   = HorizontalAlignment.Center; //置中
            t1.BorderStyle = BorderStyle.FixedSingle;
            t1.Width       = 67;
            t1.Height      = 15;
            bmp            = mSmcDataToImage.ConvertTextToImage(bmp, t1, Color.Black, 110, 18);

            t1.Text        = "设备号 F2201";
            t1.Font        = new Font("新細明體", 9, FontStyle.Regular);
            t1.TextAlign   = HorizontalAlignment.Left; //置中
            t1.BorderStyle = BorderStyle.FixedSingle;
            t1.Width       = 67;
            t1.Height      = 15;
            bmp            = mSmcDataToImage.ConvertTextToImage(bmp, t1, Color.Black, 110, 32);

            t1.Text        = "台车号 F3082 - V";
            t1.Font        = new Font("新細明體", 9, FontStyle.Regular);
            t1.TextAlign   = HorizontalAlignment.Left; //置中
            t1.BorderStyle = BorderStyle.FixedSingle;
            t1.Width       = 67;
            t1.Height      = 15;
            bmp            = mSmcDataToImage.ConvertTextToImage(bmp, t1, Color.Black, 110, 46);

            /* String StrName = String.Format("{0}", DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"));
             * t1.Text = StrName;
             * t1.Font = new Font("Cambria", 15, FontStyle.Bold);
             * t1.TextAlign = HorizontalAlignment.Center; //置中
             * t1.BorderStyle = BorderStyle.FixedSingle;
             * t1.Width = 206;
             * t1.Height = 25;
             * bmp = mSmcDataToImage.ConvertTextToImage(bmp, t1, Color.Red, 2, 23);*/


            /*  t1.Text = MacAddress;
             * t1.Font = new Font("Cambria", 20, FontStyle.Bold);
             * t1.TextAlign = HorizontalAlignment.Center; //置中
             * t1.BorderStyle = BorderStyle.FixedSingle;
             * t1.Width = 206;
             * t1.Height = 25;
             * bmp = mSmcDataToImage.ConvertTextToImage(bmp, t1, Color.Black, 2, 40);
             *
             *
             */

            return(bmp);
        }
        public static void PrintCodeSheet(CodeSheetItem[] codeSheetItems, string title = "Asset repository code sheet")
        {
            // grid
            var numrow   = 4;
            var numcol   = 4;
            var overSize = new System.Windows.Size(12000, 12000);

            var g = new Grid();

            for (int i = 0; i < 1 + 2 * numrow; i++)
            {
                var rd = new RowDefinition();
                rd.Height = GridLength.Auto;
                g.RowDefinitions.Add(rd);
            }
            for (int i = 0; i < numcol; i++)
            {
                var cd = new ColumnDefinition();
                cd.Width = GridLength.Auto;
                g.ColumnDefinitions.Add(cd);
            }
            g.Margin = new Thickness(50);
            g.Children.Clear();

            // title
            var tlb = new Label();

            tlb.Content  = title;
            tlb.FontSize = 24;
            tlb.HorizontalContentAlignment = HorizontalAlignment.Center;
            tlb.VerticalContentAlignment   = VerticalAlignment.Center;
            Grid.SetRow(tlb, 0);
            Grid.SetColumn(tlb, 0);
            Grid.SetColumnSpan(tlb, numcol);
            g.Children.Add(tlb);

            // all items
            foreach (var csi in codeSheetItems)
            {
                var row = (g.Children.Count / 2) / numcol;
                var col = (g.Children.Count / 2) % numcol;

                if (g.Children.Count / 2 >= numrow * numcol)
                {
                    break;
                }

                Bitmap bmp = null;
                if (csi.code.Trim().ToLower() == "dmc")
                {
                    // DMC
                    var barcodeWriter = new BarcodeWriter();

                    // set the barcode format
                    barcodeWriter.Format = BarcodeFormat.DATA_MATRIX;

                    // write text and generate a 2-D barcode as a bitmap
                    bmp = barcodeWriter.Write(csi.id);
                }
                else
                if (csi.code.Trim().ToLower() == "qr")
                {
                    QRCodeGenerator qrGenerator = new QRCodeGenerator();
                    QRCodeData      qrCodeData  = qrGenerator.CreateQrCode(csi.id, QRCodeGenerator.ECCLevel.Q);
                    QRCode          qrCode      = new QRCode(qrCodeData);
                    bmp = qrCode.GetGraphic(20);
                }
                else
                {
                    continue;
                }

                var imgsrc = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
                    bmp.GetHbitmap(),
                    IntPtr.Zero,
                    System.Windows.Int32Rect.Empty,
                    BitmapSizeOptions.FromWidthAndHeight(bmp.Width, bmp.Height));
                var img = new System.Windows.Controls.Image();
                img.Source              = imgsrc;
                img.Height              = 200 * csi.normSize;
                img.Width               = 200 * csi.normSize;
                img.VerticalAlignment   = VerticalAlignment.Bottom;
                img.HorizontalAlignment = HorizontalAlignment.Center;
                img.Margin              = new Thickness(40, 40, 40, 0);
                Grid.SetRow(img, 1 + 2 * row);
                Grid.SetColumn(img, col);
                g.Children.Add(img);

                var lab = new Label();
                lab.Content = csi.description;

                var labview = new Viewbox();
                labview.Child   = lab;
                labview.Stretch = Stretch.Uniform;
                labview.Width   = 200;
                labview.Height  = 40;
                Grid.SetRow(labview, 1 + 2 * row + 1);
                Grid.SetColumn(labview, col);
                g.Children.Add(labview);
            }


            var cb = new Border();

            cb.BorderBrush     = System.Windows.Media.Brushes.Black;
            cb.BorderThickness = new Thickness(1);
            g.Measure(overSize);
            // this will bring down the overSize to adequate values
            g.Arrange(
                new Rect(new System.Windows.Point(0, 0), g.DesiredSize));
            cb.Child = g;
            cb.Measure(overSize);
            // this will bring down the overSize to adequate values
            cb.Arrange(new Rect(new System.Windows.Point(0, 0), cb.DesiredSize));

            Print(cb);
        }
        public Bitmap setESLimage_42(string MacAddress, string battery)
        {
            Bitmap bmp = new Bitmap(400, 300);

            using (Graphics graphics = Graphics.FromImage(bmp))
            {
                graphics.FillRectangle(new SolidBrush(Color.White), 0, 0, 400, 300);
            }



            TextBox t1 = new TextBox();

            t1.Text        = "SMC ESL  " + battery + " V";
            t1.Font        = new Font("Cambria", 38, FontStyle.Bold);
            t1.TextAlign   = HorizontalAlignment.Center; //置中
            t1.BorderStyle = BorderStyle.FixedSingle;
            t1.Width       = 380;
            t1.Height      = 40;
            bmp            = mSmcDataToImage.ConvertTextToImage(bmp, t1, Color.Red, 1, 0);

            String StrName = String.Format("{0}", DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"));

            t1.Text        = StrName;
            t1.Font        = new Font("Cambria", 20, FontStyle.Bold);
            t1.TextAlign   = HorizontalAlignment.Center; //置中
            t1.BorderStyle = BorderStyle.FixedSingle;
            t1.Width       = 380;
            t1.Height      = 40;
            bmp            = mSmcDataToImage.ConvertTextToImage(bmp, t1, Color.Red, 2, 60);


            t1.Text        = MacAddress;
            t1.Font        = new Font("Cambria", 26, FontStyle.Bold);
            t1.TextAlign   = HorizontalAlignment.Center; //置中
            t1.BorderStyle = BorderStyle.FixedSingle;
            t1.Width       = 380;
            t1.Height      = 40;
            bmp            = mSmcDataToImage.ConvertTextToImage(bmp, t1, Color.Black, 2, 85);

            Bitmap        bar       = new Bitmap(400, 80);
            BarcodeWriter barcode_w = new BarcodeWriter();

            barcode_w.Format              = BarcodeFormat.CODE_93;
            barcode_w.Options.Width       = 400;
            barcode_w.Options.Height      = 80;
            barcode_w.Options.PureBarcode = true;
            bar = barcode_w.Write(MacAddress);
            bmp = mSmcDataToImage.ConvertImageToImage(bmp, bar, 4, 210); //QRcode


            Bitmap qr = new Bitmap(400, 70);

            barcode_w.Format              = BarcodeFormat.QR_CODE;
            barcode_w.Options.Width       = 400;
            barcode_w.Options.Height      = 70;
            barcode_w.Options.PureBarcode = true;
            bar = barcode_w.Write("http://www.smartchip.com.tw/");
            bmp = mSmcDataToImage.ConvertImageToImage(bmp, bar, 4, 130); //QRcode



            return(bmp);
        }
Beispiel #30
0
        /// <summary>
        /// ¸ù¾Ý×Ö·û´®Éú³É¶þάÂë
        /// </summary>
        /// <param name="content">×Ö·û´®</param>
        /// <returns></returns>
        public Bitmap GetQRCode(string content)
        {
            Bitmap bmp = _writer.Write(content);

            return(bmp);
        }
        private void printPage(object sender, PrintPageEventArgs ev)
        {
            float  linesPerPage = 0;
            float  yPos         = -3;
            int    count        = 0;
            float  leftMargin;
            string line;

            // Calculate the number of lines per page.
            //linesPerPage = ev.MarginBounds.Height /
            //   printFont.GetHeight(ev.Graphics);
            // Print each line of the file.
            while ((line = streamToPrint.ReadLine()) != null)
            {
                float lastFontSize = 0;
                leftMargin = 0;
                String[] subLine   = line.Split('/');
                String   isComment = line[0].ToString();
                if (subLine[0].Equals("pdf417") || subLine[0].Equals("Qr"))
                {
                    lineStyle = fixedSys;
                }
                else
                {
                    line = addStyles(line);
                }
                if (isComment != "#")
                {
                    SizeF size = new SizeF();
                    size  = ev.Graphics.MeasureString(line, lineStyle);
                    yPos += (size.Height - 1);
                    if (fontSize > 15)
                    {
                        yPos -= 2;
                    }
                    if (fontSize > 10)
                    {
                        yPos -= 3;
                    }
                    if (line != " ")
                    {
                        StringFormat stringFormat = new StringFormat();
                        stringFormat.LineAlignment = StringAlignment.Center;
                        if (textAling == "C")
                        {
                            leftMargin             = 140;
                            stringFormat.Alignment = StringAlignment.Center;
                        }
                        else if (textAling == "R")
                        {
                            leftMargin             = 278;
                            stringFormat.Alignment = StringAlignment.Far;
                        }
                        if (subLine[0].Equals("pdf417") || subLine[0].Equals("Qr"))
                        {
                            if (subLine[0].Equals("pdf417"))
                            {
                                codeFormat = BarcodeFormat.PDF_417;
                            }
                            else if (subLine[0].Equals("Qr"))
                            {
                                codeFormat = BarcodeFormat.QR_CODE;
                            }
                            int confLength = subLine[0].Length + subLine[1].Length + subLine[2].Length + 3;
                            CodeQR = line.Substring(confLength, line.Length - confLength);
                            if (CodeQR != "" && CodeQR != "PDFCODE")
                            {
                                try
                                {
                                    QRWidth  = Int32.Parse(subLine[1]);
                                    QRHeight = Int32.Parse(subLine[2]);
                                }
                                catch (System.Exception)
                                {
                                    Console.Write("Default size selected");
                                    if (codeFormat == BarcodeFormat.PDF_417)
                                    {
                                        QRWidth  = 280;
                                        QRHeight = 200;
                                    }
                                    else
                                    {
                                        QRWidth  = 200;
                                        QRHeight = 200;
                                    }
                                }
                                BarcodeWriter writer = new BarcodeWriter();
                                writer.Format         = codeFormat;
                                writer.Options.Width  = QRWidth;
                                writer.Options.Height = QRHeight;
                                writer.Options.Margin = 0;
                                var       imgBitmap  = writer.Write(CodeQR);
                                int       rectHeight = imgBitmap.Height > 180 ? 140 : imgBitmap.Height;
                                int       rectWidth  = imgBitmap.Width > 280 ? 280 : imgBitmap.Width;
                                Rectangle rect       = new Rectangle(140 - (rectWidth / 2), (int)yPos, rectWidth, rectHeight);
                                ev.Graphics.DrawImage(imgBitmap, rect);
                                yPos += rectHeight;
                            }
                        }
                        else if (size.Width >= 292)
                        {
                            int       lineSize    = line.Length;
                            int       linesNumber = (int)(size.Width / 280) + 1;
                            Rectangle rect        = new Rectangle(0, (int)(yPos -= fontSize / linesNumber), 280, (int)(size.Height * linesNumber));
                            stringFormat.LineAlignment = StringAlignment.Far;
                            ev.Graphics.DrawString(line, lineStyle, Brushes.Black, rect, stringFormat);
                            //ev.Graphics.DrawRectangle(new Pen(Brushes.Black, 1), rect);
                            yPos += rect.Height - (fontSize / linesNumber);
                        }
                        else
                        {
                            ev.Graphics.DrawString(line, lineStyle, Brushes.Black, leftMargin, yPos, stringFormat);
                        }
                        count++;
                        lastFontSize = fontSize;
                    }
                    else
                    {
                        linesPerPage -= 1;
                    }
                    Console.WriteLine("height ypos: " + yPos);
                }
                else
                {
                    Console.Write("commented line");
                }
            }
        }
Beispiel #32
0
        public static Bitmap DrawBarCode(string data, BarcodeFormat format, int width, int height)
        {
            BitMatrix bm;

            try
            {
                switch (format)
                {
                case BarcodeFormat.UPC_A:
                    UPCAWriter writer = new UPCAWriter();
                    bm = writer.encode(data, format, width, height);
                    break;

                case BarcodeFormat.UPC_E:
                    UPCEWriter upcew = new UPCEWriter();
                    bm = upcew.encode(data, format, width, height);
                    break;

                case BarcodeFormat.EAN_8:
                    EAN8Writer ean8w = new EAN8Writer();
                    bm = ean8w.encode(data, format, width, height);
                    break;

                case BarcodeFormat.EAN_13:
                    EAN13Writer ean13w = new EAN13Writer();
                    bm = ean13w.encode(data, format, width, height);
                    break;

                case BarcodeFormat.CODE_39:
                    Code39Writer c39w = new Code39Writer();
                    bm = c39w.encode(data, format, width, height);
                    break;

                case BarcodeFormat.ITF:
                    ITFWriter iw = new ITFWriter();
                    bm = iw.encode(data, format, width, height);
                    break;

                case BarcodeFormat.CODABAR:
                    CodaBarWriter cbw = new CodaBarWriter();
                    bm = cbw.encode(data, format, width, height);
                    break;

                case BarcodeFormat.CODE_93:
                    Code93Writer c93w = new Code93Writer();
                    bm = c93w.encode(data, format, width, height);
                    break;

                case BarcodeFormat.CODE_128:
                    Code128Writer c128w = new Code128Writer();
                    bm = c128w.encode(data, format, width, height);
                    break;

                default:
                    return(null);
                }
                BarcodeWriter bw = new BarcodeWriter();
                return(bw.Write(bm));
            }
            catch
            {
                return(new Bitmap(10, 10));
            }
        }
 public Bitmap ToBitmap(BarcodeFormat format, String content)
 {
     var writer = new BarcodeWriter { Format = format };
     return writer.Write(content);
 }
        public static string GenerateBarCode(string barcode)
        {
            string barcodeimage = string.Empty;

            //using (MemoryStream memoryStream = new MemoryStream())
            //{
            //    using (Bitmap bitMap = new Bitmap(barcode.Length * 40, 80))
            //    {
            //        using (Graphics graphics = Graphics.FromImage(bitMap))
            //        {
            //            Font oFont = new Font("IDAutomationHC39M", 16);
            //            PointF point = new PointF(2f, 2f);
            //            SolidBrush whiteBrush = new SolidBrush(Color.White);
            //            graphics.FillRectangle(whiteBrush, 0, 0, bitMap.Width, bitMap.Height);
            //            SolidBrush blackBrush = new SolidBrush(Color.DarkBlue);
            //            graphics.DrawString("*" + barcode + "*", oFont, blackBrush, point);
            //        }

            //        bitMap.Save(memoryStream, ImageFormat.Jpeg);

            //        barcodeimage = "data:image/png;base64," + Convert.ToBase64String(memoryStream.ToArray());
            //    }
            //}

            //return barcodeimage;

            //byte[] BarCode;
            //string BarCodeImage;
            //Bitmap objBitmap = new Bitmap(barcode.Length * 28, 100);
            //using (Graphics graphic = Graphics.FromImage(objBitmap))
            //{
            //    Font newFont = new Font("IDAutomationHC39M Free Version", 18, FontStyle.Regular);
            //    PointF point = new PointF(2f, 2f);
            //    SolidBrush balck = new SolidBrush(Color.Black);
            //    SolidBrush white = new SolidBrush(Color.White);
            //    graphic.FillRectangle(white, 0, 0, objBitmap.Width, objBitmap.Height);
            //    graphic.DrawString("*" + barcode + "*", newFont, balck, point);
            //}
            //using (MemoryStream Mmst = new MemoryStream())
            //{
            //    objBitmap.Save(Mmst, ImageFormat.Png);
            //    BarCode = Mmst.GetBuffer();
            //    BarCodeImage = BarCode != null ? "data:image/jpg;base64," + Convert.ToBase64String((byte[])BarCode) : "";
            //    return BarCodeImage;
            //}

            Image img = null;

            using (var ms = new MemoryStream())
            {
                var writer = new BarcodeWriter()
                {
                    Format = BarcodeFormat.CODE_128
                };
                writer.Options.Height      = 20;
                writer.Options.Width       = 120;
                writer.Options.PureBarcode = true;
                img = writer.Write(barcode);
                img.Save(ms, ImageFormat.Jpeg);
                byte[] BarCode = ms.GetBuffer();
                barcodeimage = "data:image/jpeg;base64," + Convert.ToBase64String(BarCode);
            }

            return(barcodeimage);
        }
      public void test_Random_Encoding_Decoding_Cycles_Up_To_1000()
       {
           int bigEnough = 256;

           byte[] data = new byte[256];
           Random random = new Random(2344);

           for (int i = 0; i < 1000; i++)
           {
              random.NextBytes(data);
              //string content = "U/QcYPdz4MTR2nD2+vv88mZVnLA9/h+EGrEu3mwRIP65DlM6vLwlAwv/Ztd5LkHsio3UEJ29C1XUl0ZGRAFYv7pxPeyowjWqL5ilPZhICutvQlTePBBg+wP+ZiR2378Jp6YcB/FVRMdXKuAEGM29i41a1gKseYKpEEHpqlwRNE/Zm5bxKwL5Gv2NhxIvXOM1QNqWGwm9XC0jcvawbJprRfaRK3w3y2CKYbwEH/FwerRds2mBehhFHD5ozbgLSa1iIkIbnjBn/XV6DLpNuD08s/hCUrgx6crdSw89z/2nfxcOov2vVNuE9rbzB25e+GQBLBq/yfb1MTh3PlMhKS530w==";
              string content = Convert.ToBase64String(data);

              BarcodeWriter writer = new BarcodeWriter
                 {
                    Format = BarcodeFormat.QR_CODE,
                    Options = new EncodingOptions
                       {
                          Height = bigEnough,
                          Width = bigEnough
                       }
                 };
              Bitmap bmp = writer.Write(content);

              var reader = new BarcodeReader
                 {
                    Options = new DecodingOptions
                       {
                          PureBarcode = true,
                          PossibleFormats = new List<BarcodeFormat> {BarcodeFormat.QR_CODE}
                       }
                 };
              var decodedResult = reader.Decode(bmp);

              Assert.IsNotNull(decodedResult);
              Assert.AreEqual(content, decodedResult.Text);
           }
       }
        /************************************************
        * Function name : generatePDF
        * Description : 生成小票
        * Variables : string filePath
        ************************************************/
        public void generatePDF(string filePath, double receive)
        {
            // 判断路径是否存在
            this.filePath = filePath;
            if (!Directory.Exists(filePath))
            {
                Directory.CreateDirectory(filePath);
            }

            // 结算
            analyse(receive);

            // 生成条码
            EncodingOptions encodeOption = new EncodingOptions();

            encodeOption.Height = 40;
            encodeOption.Width  = 180;
            ZXing.BarcodeWriter wr = new BarcodeWriter();
            wr.Options = encodeOption;
            wr.Format  = BarcodeFormat.CODE_39;
            Bitmap img = wr.Write(ticketID);

            img.Save(filePath + "\\" + ticketID + ".jpg", System.Drawing.Imaging.ImageFormat.Jpeg);

            // 生成PDF小票
            time = System.DateTime.Now.ToString();
            iTextSharp.text.Rectangle pageSize = new iTextSharp.text.Rectangle(width, height);
            Document document = new Document(pageSize, border_left, border_right, border_head, border_tail);

            PdfWriter.GetInstance(document, new FileStream(filePath + "\\" + ticketID + ".pdf", FileMode.Create));
            document.Open();
            BaseFont.AddToResourceSearch("iTextAsian.dll");
            BaseFont baseFT = BaseFont.CreateFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);

            iTextSharp.text.Font font = new iTextSharp.text.Font(baseFT, fontSize);

            document.Add(new Paragraph(seperator, font));
            document.Add(new Paragraph(storeName, font));
            document.Add(new Paragraph("票号:" + ticketID + " 机号:" + casherID + " 工号:" + employeeID, font));
            document.Add(new Paragraph("交易时间:" + time, font));
            document.Add(new Paragraph("合计金额:" + deal + " 卡券:" + card, font));
            document.Add(new Paragraph("据此联购物一个月内开发票!", font));
            document.Add(new Paragraph(seperator, font));
            document.Add(new Paragraph(storeName, font));
            document.Add(new Paragraph("票号:" + ticketID + " 机号:" + casherID + " 工号:" + employeeID, font));
            document.Add(new Paragraph("交易时间:" + time, font));
            document.Add(new Paragraph("*#" + casherID + ticketID + " #*", font));
            document.Add(new Paragraph(seperator, font));
            document.Add(new Paragraph("序号   商品编码(名称)   数量   金额", font));
            string str = "          ";

            for (int i = 0; i < overallAmount; i++)
            {
                document.Add(new Paragraph((i + 1) + str + gname[i] + str + amount[i] + str + price[i], font));
            }
            document.Add(new Paragraph(seperator, font));
            document.Add(new Paragraph("金额: " + deal + " 找零: " + refund, font));
            document.Add(new Paragraph("支付宝单号:" + AlipayID, font));
            if (AlipayID != "")
            {
                document.Add(new Paragraph("支付宝接口:" + deal, font));
            }
            else
            {
                document.Add(new Paragraph("支付宝接口:", font));
            }
            document.Add(new Paragraph(seperator, font));
            for (int i = 0; i < noteAmount; i++)
            {
                document.Add(new Paragraph(notes[i], font));
            }
            document.Add(new Paragraph(seperator, font));
            if (codeCreatorOpened)
            {
                iTextSharp.text.Image img2 = iTextSharp.text.Image.GetInstance(filePath + "\\" + ticketID + ".jpg");
                img2.Alignment = iTextSharp.text.Image.ALIGN_LEFT;
                document.Add(img2);
            }

            document.Close();
        }