Esempio n. 1
0
        public void Test_Barcode()
        {
            var barcode = BarcodeDrawFactory.GetSymbology(BarcodeSymbology.Code25InterleavedNC);
            var image   = barcode.Draw("82620159918434718610", 40, 2);

            image.Save("C:\\TEST\\Test1.png");
        }
Esempio n. 2
0
        private void RefreshBarcodeImage()
        {
            // Allocate new barcode image as needed
            if (_symbology != BarcodeSymbology.Unknown && !string.IsNullOrEmpty(Text))
            {
                try
                {
                    BackgroundImage = BarcodeDrawFactory.GetSymbology(_symbology).Draw(Text, _maxBarHeight);
                }
                catch
                {
                    BackgroundImage = null;
                }
            }
            else
            {
                BackgroundImage = null;
            }

            // Setup the auto-scroll minimum size
            if (BackgroundImage == null)
            {
                AutoScrollMinSize = new Size(0, 0);
            }
            else
            {
                AutoScrollMinSize = BackgroundImage.Size;
            }
        }
Esempio n. 3
0
        public ActionResult ReportDnevnikNovi(int id = 0)
        {
            ViewData["IdDnevnik"] = id;

            var    dnevnik      = db.DnevnikPrevoza.Find(id);
            String SerijskiBroj = dnevnik.SerijskiBroj;

            String kobasica = dnevnik.GostPristup;


            using (System.Drawing.Image imagen = BarcodeDrawFactory.GetSymbology(BarcodeSymbology.CodeQr).Draw(AppSettings.GetSettings()["domain_name"] + "/DnevnikPrevoza/GuestDetail?s=" + kobasica, 50, 2))
            {
                String path = Server.MapPath("~/BARCODE/" + SerijskiBroj + ".png");
                if (System.IO.File.Exists(path))
                {
                    System.IO.File.Delete(path);
                }

                imagen.Save(path, System.Drawing.Imaging.ImageFormat.Png);

                ViewData["BarCode"] = path;
            }

            return(View());
        }
Esempio n. 4
0
        private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
        {
            Graphics g = e.Graphics;

            CodeQrBarcodeDraw QRcode = BarcodeDrawFactory.CodeQr; // to generate QR code

            System.Drawing.Image QRcodeImage = QRcode.Draw(coilID.Text, 100);
            // RectangleF(The coordinates of the upper-left corner of the rectangle, width, height)
            RectangleF QRcodeRect = new RectangleF(50.0F, 40.0F, 150.0F, 150.0F);

            g.DrawImage(QRcodeImage, QRcodeRect);

            BarcodeDraw bdraw = BarcodeDrawFactory.GetSymbology(BarcodeSymbology.Code128);

            System.Drawing.Image barcodeImage = bdraw.Draw(coilID.Text, 100);
            RectangleF           barcodeRect  = new RectangleF(250.0F, 40.0F, 400.0F, 100.0F);

            g.DrawImage(barcodeImage, barcodeRect);

            // Create string to draw.
            String drawString = coilID.Text;

            // Create font and brush.
            System.Drawing.Font drawFont  = new System.Drawing.Font("Times New Roman", 16);
            SolidBrush          drawBrush = new SolidBrush(Color.Black);

            // Create point for upper-left corner of drawing.
            float x = 250.0F;
            float y = 150.0F;

            g.DrawString(drawString, drawFont, drawBrush, x, y);
        }
Esempio n. 5
0
        void RefreshImage()
        {
            if (Symbology == BarcodeSymbology.Unknown || string.IsNullOrEmpty(Code) || ActualHeight <= 0)
            {
                ErrorMessage = null;
                BarcodeImage = null;
            }
            else
            {
                var bc = BarcodeDrawFactory.GetSymbology(Symbology);
                bc.Background = Background;
                bc.Foreground = Foreground;

                try
                {
                    ErrorMessage = null;
                    BarcodeImage = bc.DrawImage(Code, Math.Max(1, (int)ActualHeight), Math.Max(1, Scale));
                }
                catch (Exception ex)
                {
                    ErrorMessage = ex.Message;
                    BarcodeImage = null;
                }
            }
            InvalidateVisual();
        }
Esempio n. 6
0
        private void RefreshBarcodeImage()
        {
            // Allocate new barcode image as needed
            if (_symbology != BarcodeSymbology.Unknown && !string.IsNullOrEmpty(Text))
            {
                try
                {
                    var drawObject = BarcodeDrawFactory.GetSymbology(_symbology);
                    var metrics    = drawObject.GetDefaultMetrics(_maxBarHeight);
                    metrics.Scale   = 2;
                    BackgroundImage = drawObject.Draw(Text, metrics);
                }
                catch
                {
                    BackgroundImage = null;
                }
            }
            else
            {
                BackgroundImage = null;
            }

            // Setup the auto-scroll minimum size
            if (BackgroundImage == null)
            {
                AutoScrollMinSize = new Size(0, 0);
            }
            else
            {
                AutoScrollMinSize = BackgroundImage.Size;
            }
        }
Esempio n. 7
0
        // On each printed page...
        protected override void OnPrintPage(PrintPageEventArgs e)
        {
            Graphics graphics = e.Graphics;

            // For the barcode printing
            BarcodeDraw bdraw        = BarcodeDrawFactory.GetSymbology(BarcodeSymbology.Code128);
            Image       barcodeImage = bdraw.Draw(ContainerCode, 40);

            Pen _pen = new Pen(Brushes.Black);

            _pen.DashPattern = new float[] { 4.0F, 2.0F, 1.0F, 3.0F };

            Pager.Active = false;
            AddArea(EnumDocumentZones.BODY);

            // Set font
            //this.CurrentFont = new Font("Courier New", 15, FontStyle.Bold);
            for (var i = 0; i < 2; i++)
            {
                AddText("DEALER PICK PACK CONTAINER", new EspackFont("Courier New", 11, FontStyle.Bold | FontStyle.Underline), pEOL: true);
                AddText($"{ContainerCode,-10}", new EspackFont("Courier New", 26, FontStyle.Bold), pEOL: true);
                AddImage(barcodeImage, pWidth: 600, pEOL: true);
                AddText($"ROUTE: {Route,-8}", new EspackFont("Courier New", 12, FontStyle.Bold), pEOL: true);
                AddText($"DATE : {Date,-10}", new EspackFont("Courier New", 12, FontStyle.Bold), pEOL: true);
                AddText("", pEOL: true);
            }

            AddDrawing(0, 140, 400, 140, EnumDrawingType.LINE, _pen);
            // Base code
            base.OnPrintPage(e);
        }
Esempio n. 8
0
        public ActionResult Report(int id = 0, String Lan = "SR")
        {
            ViewData["IdDnevnik"] = id;
            ViewData["Korisnik"]  = db.Korisnik.Single(c => c.KorisnickoIme.Equals(HttpContext.User.Identity.Name)).Ime;
            ViewData["Jezik"]     = Lan;


            var    dnevnik      = db.DnevnikPrevoza.Find(id);
            String SerijskiBroj = dnevnik.SerijskiBroj;

            String kobasica = dnevnik.GostPristup;

            using (System.Drawing.Image imagen = BarcodeDrawFactory.GetSymbology(BarcodeSymbology.CodeQr).Draw(AppSettings.GetSettings()["domain_name"] + "/DnevnikPrevoza/GuestDetail?s=" + kobasica, 50, 2))

            {
                String path = Server.MapPath("~/BARCODE/" + SerijskiBroj + ".png");
                if (System.IO.File.Exists(path))
                {
                    System.IO.File.Delete(path);
                }

                imagen.Save(path, System.Drawing.Imaging.ImageFormat.Png);

                ViewData["BarCode"] = path;
            }



            return(View());
        }
Esempio n. 9
0
        public void Print()
        {
            BarcodeDraw barcode = BarcodeDrawFactory.GetSymbology(BarcodeSymbology.Code93);
            Image       img     = barcode.Draw("1578", 25);

            img.Save("barcode93.png");
        }
Esempio n. 10
0
        /// <summary>
        /// Draws the design-time representation of the barcode.
        /// </summary>
        /// <param name="g">The g.</param>
        /// <param name="dp">The dp.</param>
        public override void Draw(Graphics g, ReportItemDrawParams dp)
        {
            // Our background is always white
            if (dp.DrawBackground)
            {
                g.Clear(Color.White);
            }

            // Delegate drawing of outlines
            if (dp.DrawOutlines)
            {
                base.Draw(g, dp.AsOutlinesOnly());
            }

            // Draw content if we can...
            if (dp.DrawContent &&
                Symbology != BarcodeSymbology.Unknown &&
                !string.IsNullOrEmpty(Text))
            {
                BarcodeDraw drawObject =
                    BarcodeDrawFactory.GetSymbology(Symbology);
                using (System.Drawing.Image image = drawObject.Draw(
                           Text,
                           InterGlyphSpacing,
                           MinimumBarHeight,
                           MaximumBarHeight,
                           MinimumBarWidth,
                           MaximumBarWidth))
                {
                    g.DrawImage(image, new Point(0, 0));
                }
            }
        }
Esempio n. 11
0
        private byte[] DrawImage()
        {
            // Determine barcode symbology
            BarcodeSymbology symbology     = BarcodeSymbology.Unknown;
            string           symbologyText = (string)GetCustomProperty("barcode:Symbology");

            symbology = (BarcodeSymbology)Enum.Parse(typeof(BarcodeSymbology), symbologyText);
            if (symbology != BarcodeSymbology.Unknown)
            {
                // Create draw object
                BarcodeDraw drawObject = BarcodeDrawFactory.GetSymbology(symbology);

                // Get default metrics and override with values specified in CRI
                BarcodeMetrics metrics = drawObject.GetDefaultMetrics(
                    GetCustomPropertyInt32("barcode:MaximumBarHeight", 30));
                metrics.MinHeight =
                    GetCustomPropertyInt32("barcode:MinimumBarHeight", metrics.MinHeight);
                metrics.MinWidth =
                    GetCustomPropertyInt32("barcode:MinimumBarWidth", metrics.MinWidth);
                metrics.MaxWidth =
                    GetCustomPropertyInt32("barcode:MaximumBarWidth", metrics.MaxWidth);
                metrics.InterGlyphSpacing =
                    GetCustomPropertyInt32("barcode:InterGlyphSpacing", metrics.InterGlyphSpacing);

                // Get the text to render
                string textToRender = (string)GetCustomProperty("barcode:Text");

                // Determine available space for rendering
                int criWidth  = (int)(_cri.Width.ToInches() * DPI);
                int criHeight = (int)(_cri.Height.ToInches() * DPI);

                // Create bitmap of the appropriate size
                System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(
                    criWidth, criHeight, PixelFormat.Format32bppArgb);
                using (System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bmp))
                {
                    // Clear entire background
                    g.Clear(System.Drawing.Color.White);

                    // Get barcode image
                    System.Drawing.Image barcodeImage =
                        drawObject.Draw(textToRender, metrics);

                    // Centre the image
                    int x = (bmp.Width - barcodeImage.Width) / 2;
                    int y = (bmp.Height - barcodeImage.Height) / 2;
                    g.DrawImageUnscaled(barcodeImage, x, y);
                }

                // Create memory stream for new image
                using (MemoryStream stream = new MemoryStream())
                {
                    // Save image and setup CRI image
                    bmp.Save(stream, ImageFormat.Bmp);
                    return(stream.ToArray());
                }
            }
            return(null);
        }
Esempio n. 12
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="voucherNumber">82620159918434718610</param>
        /// <param name="height">40</param>
        /// <param name="size">2</param>
        /// <returns></returns>
        public static Bitmap BinaryWritePicture(string voucherNumber, int height, int size, BarcodeSymbology type = BarcodeSymbology.Code25InterleavedNC)
        {
            Debug.Assert(!voucherNumber.IsNullOrEmpty());
            var barcode = BarcodeDrawFactory.GetSymbology(type);
            var image   = barcode.Draw(voucherNumber, height, size);

            return((Bitmap)image);
        }
Esempio n. 13
0
        /// <summary>
        /// Draws the design-time representation of the barcode.
        /// </summary>
        /// <param name="g">
        /// A <see cref="Graphics"/> object representing the designer surface.
        /// </param>
        /// <param name="dp">
        /// A <see cref="ReportItemDrawParams"/> containing draw parameters.
        /// </param>
        public override void Draw(Graphics g, ReportItemDrawParams dp)
        {
            // Our background is always white
            if (dp.DrawBackground)
            {
                g.Clear(Color.White);
            }

            // Delegate drawing of outlines
            if (dp.DrawOutlines)
            {
                base.Draw(g, dp.AsOutlinesOnly());
            }

            // Draw content if we can...
            if (dp.DrawContent &&
                Symbology != BarcodeSymbology.Unknown &&
                !string.IsNullOrEmpty(Text))
            {
                BarcodeDraw drawObject =
                    BarcodeDrawFactory.GetSymbology(Symbology);

                BarcodeMetrics metrics = drawObject.GetDefaultMetrics(30);
                metrics.Scale = Scale;

                BarcodeMetrics1d metrics1d = metrics as BarcodeMetrics1d;
                if (metrics1d != null)
                {
                    metrics1d.InterGlyphSpacing = InterGlyphSpacing;
                    metrics1d.MaxHeight         = MaximumBarHeight;
                    metrics1d.MinHeight         = MinimumBarHeight;
                    metrics1d.MaxWidth          = MaximumBarWidth;
                    metrics1d.MinWidth          = MinimumBarWidth;
                    metrics1d.RenderVertically  = RenderVertically;
                }
                else if (Symbology == BarcodeSymbology.CodeQr)
                {
                    BarcodeMetricsQr qrMetrics = (BarcodeMetricsQr)metrics;
                    if (QrVersion != null)
                    {
                        qrMetrics.Version = QrVersion.Value;
                    }
                    if (QrEncodingMode != null)
                    {
                        qrMetrics.EncodeMode = QrEncodingMode.Value;
                    }
                    if (QrErrorCorrectionMode != null)
                    {
                        qrMetrics.ErrorCorrection = QrErrorCorrectionMode.Value;
                    }
                }
                using (System.Drawing.Image image = drawObject.Draw(Text, metrics))
                {
                    g.DrawImage(image, new Point(0, 0));
                }
            }
        }
Esempio n. 14
0
        /// <summary>
        /// Generates a barcode URI.
        /// </summary>
        /// <param name="helper">The HTML helper.</param>
        /// <param name="text">The text to be encoded.</param>
        /// <param name="symbology">The barcode symbology to use.</param>
        /// <param name="height">The height.</param>
        /// <param name="scale">
        /// The scale factor to use (null = use default for symbology).
        /// </param>
        /// <param name="useExtensionlessUri">
        /// <c>true</c> to use extensionless URI; otherwise, <c>false</c>.
        /// </param>
        /// <returns></returns>
        public static string Barcode(
            this UrlHelper helper,
            string text,
            BarcodeSymbology symbology,
            int height = 30,
            int?scale  = null,
            bool useExtensionlessUri = true)
        {
            BarcodeImageUriBuilder builder = null;

            // We cheat and get the default metrics
            var temp    = BarcodeDrawFactory.GetSymbology(symbology);
            var metrics = temp.GetDefaultMetrics(height);

            if (scale != null)
            {
                metrics.Scale = scale.Value;
            }
            BarcodeMetrics1d metrics1d = metrics as BarcodeMetrics1d;

            if (metrics1d != null)
            {
                builder =
                    new BarcodeImageUriBuilder
                {
                    EncodingScheme      = symbology,
                    Text                = text,
                    BarMaxHeight        = metrics1d.MaxHeight,
                    BarMinHeight        = metrics1d.MinHeight,
                    BarMaxWidth         = metrics1d.MaxWidth,
                    BarMinWidth         = metrics1d.MinWidth,
                    Scale               = metrics.Scale,
                    UseExtensionlessUri = useExtensionlessUri
                };
            }
            else
            {
                BarcodeMetricsQr metricsQr = metrics as BarcodeMetricsQr;
                if (metricsQr != null)
                {
                    builder =
                        new BarcodeImageUriBuilder
                    {
                        EncodingScheme      = BarcodeSymbology.CodeQr,
                        Text                = text,
                        QrEncodingMode      = metricsQr.EncodeMode,
                        QrErrorCorrect      = metricsQr.ErrorCorrection,
                        QrVersion           = metricsQr.Version,
                        Scale               = metrics.Scale,
                        UseExtensionlessUri = useExtensionlessUri
                    };
                }
            }
            return(helper.Content(builder.ToString()));
        }
Esempio n. 15
0
        public static void PrintStickerFromMnf(string path)
        {
            FSharpOption <Tuple <FSharpOption <Bitmap>, string, FSharpList <Tuple <string, string> > > > fSharpOption  = EtiketParse(path);
            FSharpOption <Tuple <FSharpOption <Bitmap>, string, FSharpList <Tuple <string, string> > > > fSharpOption2 = fSharpOption;
            FSharpOption <Tuple <FSharpOption <Bitmap>, string, FSharpList <Tuple <string, string> > > > fSharpOption3 = fSharpOption2;

            if (fSharpOption3 != null)
            {
                FSharpOption <Tuple <FSharpOption <Bitmap>, string, FSharpList <Tuple <string, string> > > > fSharpOption4 = fSharpOption3;
                if (fSharpOption4.Value.Item1 != null)
                {
                    FSharpOption <Bitmap> item = fSharpOption4.Value.Item1;
                    FSharpList <Tuple <string, string> > lst2 = fSharpOption4.Value.Item3;
                    Bitmap bmp   = item.Value;
                    string barc2 = fSharpOption4.Value.Item2;
                    using (MemoryStream stream = new MemoryStream(File.ReadAllBytes(Path.Combine(libPath, "stickerImp.xaml"))))
                    {
                        object obg  = XamlReader.Load((Stream)stream);
                        Window win2 = (Window)obg;
                        //Window win2 = (Window)XamlReader.Load((Stream)stream);
                        Grid sticker2 = (Grid)win2.FindName("sticker");
                        System.Windows.Controls.Image barcod2 = (System.Windows.Controls.Image)win2.FindName("barcod");
                        System.Windows.Controls.Image imgWin  = (System.Windows.Controls.Image)win2.FindName("imgWin");
                        imgWin.Source = /*Bitmap.*/ get_Source(bmp);
                        ListModule.Iterate(new PrintStickerFromMnf_132_1(win2), lst2);
                        BarcodeDraw brc2 = BarcodeDrawFactory.GetSymbology(BarcodeSymbology.Code128);
                        barcod2.Source = /*Bitmap.*/ get_Source((Bitmap)brc2.Draw(barc2, 30));
                        PrintGrid(sticker2);
                        Unit unit = null;
                    }
                }
                else
                {
                    FSharpList <Tuple <string, string> > lst = fSharpOption4.Value.Item3;
                    string barc = fSharpOption4.Value.Item2;
                    using (MemoryStream ms = new MemoryStream(File.ReadAllBytes(Path.Combine(libPath, "stickerBlk.xaml"))))
                    {
                        object obg = XamlReader.Load((Stream)ms);
                        Window win = (Window)obg;
                        //Window win = (Window)XamlReader.Load((Stream)ms);
                        Grid sticker = (Grid)win.FindName("sticker");
                        System.Windows.Controls.Image barcod = (System.Windows.Controls.Image)win.FindName("barcod");
                        ListModule.Iterate(new PrintStickerFromMnf_121(win), lst);
                        BarcodeDraw brc = BarcodeDrawFactory.GetSymbology(BarcodeSymbology.Code128);
                        barcod.Source = /*Bitmap.*/ get_Source((Bitmap)brc.Draw(barc, 30));
                        PrintGrid(sticker);
                        Unit unit2 = null;
                    }
                }
            }
        }
Esempio n. 16
0
        private BarcodeDraw InstallBarcodeDraw(BarcodeDraw draw)
        {
            switch ("Code11C")
            {
            case "Code11C":
                draw = BarcodeDrawFactory.GetSymbology(BarcodeSymbology.Code11C); break;

            case "Code39NC":
                draw = BarcodeDrawFactory.GetSymbology(BarcodeSymbology.Code11NC); break;

            default: break;
            }
            return(draw);
        }
Esempio n. 17
0
        private void button1_Click(object sender, EventArgs e)
        {
            //Zen.Barcode.Code128BarcodeDraw barcode = Zen.Barcode.BarcodeDrawFactory.Code128WithChecksum;
            //pictureBox1.Image = barcode.Draw(textBox1.Text, 50);

            if (textBox1.Text != "")
            {
                BarcodeSymbology s          = BarcodeSymbology.Code128;
                BarcodeDraw      drawObject = BarcodeDrawFactory.GetSymbology(s);
                var metrics = drawObject.GetDefaultMetrics(60);
                metrics.Scale     = 2;
                pictureBox1.Image = drawObject.Draw(textBox1.Text, metrics);
            }
        }
Esempio n. 18
0
 private Image GenerateBarcode(string text)
 {
     try
     {
         using (MemoryStream mStream = new MemoryStream())
         {
             BarcodeSymbology _symbology = BarcodeSymbology.Code128;
             Image            image      = BarcodeDrawFactory.GetSymbology(_symbology).Draw(text, maxBarHeight: 70);
             image.Save(mStream, ImageFormat.Jpeg);
             return(image);
         }
     }
     catch (Exception exception)
     {
         return(null);
     }
 }
Esempio n. 19
0
        private static string getBarcode(string barcode)
        {
            BarcodeSymbology s          = BarcodeSymbology.Code39NC;
            BarcodeDraw      drawObject = BarcodeDrawFactory.GetSymbology(s);
            var metrics = drawObject.GetDefaultMetrics(45);

            metrics.Scale = 1;
            var barcodeImage = drawObject.Draw(barcode, metrics);

            using (MemoryStream ms = new MemoryStream())
            {
                barcodeImage.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
                byte[] imageBytes = ms.ToArray();

                return(Convert.ToBase64String(imageBytes));
            }
        }
Esempio n. 20
0
        /// <summary>
        /// Генерирует BarCode в формате Code128
        /// </summary>
        /// <param name="id">ID договора</param>
        /// <param name="contractNumber">Номер договора</param>
        /// <returns>BarCode в формате Base64</returns>
        public static string GetBarcode(string id, string contractNumber)
        {
            const BarcodeSymbology type = BarcodeSymbology.Code128;
            var drawObject = BarcodeDrawFactory.GetSymbology(type);
            var metrics    = drawObject.GetDefaultMetrics(60);

            metrics.Scale = 2;

            var endodedIdAndContractNumber = Encoder.BuildCode(id, contractNumber);
            var barcodeImage = drawObject.Draw(endodedIdAndContractNumber, metrics);

            using (var memoryStream = new MemoryStream())
            {
                barcodeImage.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Png);
                var imageBytes = memoryStream.ToArray();

                return(Convert.ToBase64String(imageBytes));
            }
        }
Esempio n. 21
0
            private void StartAsyncTask(object state)
            {
                try
                {
                    // We want to respond to image requests of the form;
                    //
                    //	<encoded barcode>.Barcode

                    // Cache information from context
                    _request  = _context.Request;
                    _response = _context.Response;

                    // Filename is the encoded design ID
                    BarcodeImageUri uri = new BarcodeImageUri(_request.Url);

                    // Lookup design and retrieve image data
                    // Stream JPEG image to client
                    _response.ContentType = "image/jpeg";
                    _response.Clear();
                    _response.BufferOutput = true;

                    // Get the object capable of rendering the barcode
                    BarcodeDraw drawObject = BarcodeDrawFactory.GetSymbology(
                        uri.EncodingScheme);

                    // Render barcode and save directly onto response stream
                    using (Image image = drawObject.Draw(uri.Text,
                                                         uri.BarMinHeight, uri.BarMaxHeight,
                                                         uri.BarMinWidth, uri.BarMaxWidth))
                    {
                        image.Save(_response.OutputStream, ImageFormat.Jpeg);
                    }
                }
                catch (Exception e)
                {
                    _error = e;
                }
                finally
                {
                    _response.End();
                    SetComplete();
                }
            }
        /// <summary>
        /// Redraws the whole barcode
        /// </summary>
        public override void RedrawAll()
        {
            Children.Clear();


            if (Value != null)
            {
                var DrawObject = BarcodeDrawFactory.GetSymbology((BarcodeSymbology)(int)BarcodeSymbology);
                var img        = DrawObject.Draw(Value.ToString(), 30);
                var bmpImage   = ImageToBitmapImage(new Bitmap(img));

                var BarcodeImage = new Image();
                BarcodeImage.Stretch = Stretch.UniformToFill;
                BarcodeImage.Source  = bmpImage;
                BarcodeImage.Width   = this.Width;
                BarcodeImage.Height  = this.Height;
                Children.Add(BarcodeImage);
            }
        }
Esempio n. 23
0
        public byte[] creabarcode(String barcode)
        {
            BarcodeMetrics tamccbb = new BarcodeMetrics(2, 90);

            System.Drawing.Image imagen;

            imagen = BarcodeDrawFactory.GetSymbology(BarcodeSymbology.Code128).Draw(barcode, tamccbb);

            ImageFormat format = ImageFormat.Bmp;

            MemoryStream mm = new MemoryStream();

            imagen.Save(mm, format);
            imagen.Dispose();

            byte[] bytearray = mm.ToArray();
            mm.Close();
            mm.Dispose();

            return(bytearray);
        }
        public string getBarcode(int type, long n)
        {
            Zen.Barcode.BarcodeSymbology s = Zen.Barcode.BarcodeSymbology.Code39C;
            BarcodeDraw drawObject         = BarcodeDrawFactory.GetSymbology(s);

            var metrics = drawObject.GetDefaultMetrics(100);

            metrics.Scale = 1;
            var barcodeImage = drawObject.Draw(n.ToString(), metrics);

            Bitmap bm = ResizeImage(barcodeImage, 398, 60);

            using (MemoryStream ms = new MemoryStream())
            {
                //barcodeImage.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
                bm.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                //bm.Save(@"C:\test\BarCode(3).jpeg", System.Drawing.Imaging.ImageFormat.Jpeg);
                byte[] imageBytes = ms.ToArray();
                return(string.Format("data:image/png;base64,{0}", Convert.ToBase64String(imageBytes)));
            }
        }
Esempio n. 25
0
        /// <summary>
        /// Gets the barcode image based on the current barcode builder
        /// properties.
        /// </summary>
        /// <returns>
        /// Returns a raw byte array of the barcode in standard BMP format.
        /// </returns>
        public byte[] GetBarcodeImage()
        {
            // Sanity check
            if (Symbology == BarcodeSymbology.Unknown)
            {
                return(null);
            }

            // Draw image
            BarcodeDraw drawObject = BarcodeDrawFactory.GetSymbology(Symbology);

            using (Image image = drawObject.Draw(Text, _metrics))
            {
                // Create memory stream for new image
                using (MemoryStream stream = new MemoryStream())
                {
                    // Save image and return raw byte array
                    image.Save(stream, ImageFormat.Bmp);
                    return(stream.ToArray());
                }
            }
        }
Esempio n. 26
0
        public static Image GetImageBarcode(string barcode)
        {
            BarcodeSymbology s          = BarcodeSymbology.CodeEan13;
            BarcodeDraw      drawObject = BarcodeDrawFactory.GetSymbology(s);
            var metrics = drawObject.GetDefaultMetrics(60);

            metrics.Scale = 2;
            string temp        = barcode.Remove(barcode.Length - 1, 1);
            var    img         = drawObject.Draw(temp, metrics);
            var    resultImage = new Bitmap(img.Width, img.Height + 20); // 20 is bottom padding, adjust to your text

            using (var graphics = Graphics.FromImage(resultImage))
                using (var font = new Font("Consolas", 10))
                    using (var brush = new SolidBrush(Color.Black))
                        using (var format = new StringFormat
                        {
                            Alignment = StringAlignment.Center, // Also, horizontally centered text, as in your example of the expected output
                            LineAlignment = StringAlignment.Far
                        })
                        {
                            graphics.Clear(Color.White);
                            graphics.DrawImage(img, 0, 0);
                            graphics.DrawString(barcode, font, brush, resultImage.Width / 2, resultImage.Height, format);
                        }
            //Image img = code.Draw(barcode, 20);
            //float scale = 120F/25.4F;
            //float widthImg = 37.29F;
            //float heightImg = 25.93F;
            //float heightLine = 22.85F * scale;
            //float widthLine = 0.33F* scale;
            //string encrypteBarcode = GrtEncryptBarcode(GetType(int.Parse(barcode[0].ToString())), barcode);
            ////Bitmap img = new Bitmap((int)(widthImg * scale), (int)(heightImg * scale));
            //Graphics drawing = Graphics.FromImage(img);
            //GraphicsState gs = drawing.Save();
            //drawing.PageUnit = GraphicsUnit.Pixel;
            //drawing.PageScale = 1;
            //RectangleF rect = new RectangleF(0, 0, widthImg * scale, heightImg * scale);
            //drawing.FillRectangle(new SolidBrush(Color.White), rect);
            //float curPosX = 11 * widthLine;
            //foreach (var enBar in encrypteBarcode)
            //{
            //    if (enBar == '1')
            //    {
            //        rect = new RectangleF(curPosX, 0, widthLine, heightLine);
            //        drawing.FillRectangle(new SolidBrush(Color.Black), rect);
            //    }
            //    else if (enBar == '2')
            //    {
            //        rect = new RectangleF(curPosX, 0, widthLine, heightLine + 5 * widthLine);
            //        drawing.FillRectangle(new SolidBrush(Color.Black), rect);
            //    }
            //    curPosX += widthLine;
            //}

            //curPosX = 11 * widthLine - 3.63F* scale;
            //for (int i = 0; i < barcode.Length; i++)
            //{
            //    drawing.DrawString(barcode[i].ToString(), new Font("Arial", 2.75F * scale), new SolidBrush(Color.Black), curPosX,
            //        heightLine + 0.5F * widthLine);
            //    if (i == 0)
            //    {
            //        curPosX = 14 * widthLine;
            //    }
            //    if(i != 0)
            //    {
            //        curPosX += drawing.MeasureString(barcode[i].ToString(),
            //            new Font("Arial", 2.75F * scale)).Width;
            //    }
            //}

            //drawing.Restore(gs);


            //Bitmap res = new Bitmap((int)Math.Round(widthImg), (int)Math.Round(heightImg));
            //Graphics rdrawing = Graphics.FromImage(res);
            //rdrawing.DrawImage(img, 0, 0, widthImg*scale, heightImg*scale);
            //drawing.Dispose();
            //img.Dispose();
            //rdrawing.Dispose();
            return(resultImage);
        }
        private byte[] DrawImage()
        {
            // Determine barcode symbology
            BarcodeSymbology symbology     = BarcodeSymbology.Unknown;
            string           symbologyText = (string)GetCustomProperty("barcode:Symbology");

            symbology = (BarcodeSymbology)Enum.Parse(typeof(BarcodeSymbology), symbologyText);
            if (symbology != BarcodeSymbology.Unknown)
            {
                // Create draw object
                BarcodeDraw drawObject = BarcodeDrawFactory.GetSymbology(symbology);

                // Get default metrics and override with values specified in CRI
                // TODO: Need more elegant method for doing this...
                BarcodeMetrics metrics = drawObject.GetDefaultMetrics(30);
                metrics.Scale =
                    GetCustomPropertyInt32("barcode:Scale", metrics.Scale);

                BarcodeMetrics1d metrics1d = metrics as BarcodeMetrics1d;
                if (metrics1d != null)
                {
                    metrics1d.MaxHeight =
                        GetCustomPropertyInt32("barcode:MaximumBarHeight", metrics1d.MaxHeight);
                    metrics1d.MinHeight =
                        GetCustomPropertyInt32("barcode:MinimumBarHeight", metrics1d.MinHeight);
                    metrics1d.MinWidth =
                        GetCustomPropertyInt32("barcode:MinimumBarWidth", metrics1d.MinWidth);
                    metrics1d.MaxWidth =
                        GetCustomPropertyInt32("barcode:MaximumBarWidth", metrics1d.MaxWidth);
                    int interGlyphSpacing =
                        GetCustomPropertyInt32("barcode:InterGlyphSpacing", -1);
                    if (interGlyphSpacing >= 0)
                    {
                        metrics1d.InterGlyphSpacing = interGlyphSpacing;
                    }
                    metrics1d.RenderVertically =
                        GetCustomPropertyBool("barcode:RenderVertically", metrics1d.RenderVertically);
                }
                else if (symbology == BarcodeSymbology.CodeQr)
                {
                    BarcodeMetricsQr qrMetrics = (BarcodeMetricsQr)metrics;
                    qrMetrics.Version =
                        GetCustomPropertyInt32("barcode:QrVersion", qrMetrics.Version);
                    qrMetrics.EncodeMode = (QrEncodeMode)
                                           GetCustomPropertyInt32("barcode:QrEncodeMode", (int)qrMetrics.EncodeMode);
                    qrMetrics.ErrorCorrection = (QrErrorCorrection)
                                                GetCustomPropertyInt32("barcode:QrErrorCorrection", (int)qrMetrics.ErrorCorrection);
                }

                // Get the text to render
                string textToRender = (string)GetCustomProperty("barcode:Text");

                // Determine available space for rendering
                int criWidth  = (int)(_cri.Width.ToInches() * DPI);
                int criHeight = (int)(_cri.Height.ToInches() * DPI);

                // Create bitmap of the appropriate size
                System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(
                    criWidth, criHeight, PixelFormat.Format32bppArgb);
                using (System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bmp))
                {
                    // Clear entire background
                    g.Clear(System.Drawing.Color.White);

                    // Get barcode image
                    System.Drawing.Image barcodeImage =
                        drawObject.Draw(textToRender, metrics);

                    // Centre the image
                    int x = (bmp.Width - barcodeImage.Width) / 2;
                    int y = (bmp.Height - barcodeImage.Height) / 2;
                    g.DrawImageUnscaled(barcodeImage, x, y);
                }

                // Create memory stream for new image
                using (MemoryStream stream = new MemoryStream())
                {
                    // Save image and setup CRI image
                    bmp.Save(stream, ImageFormat.Bmp);
                    return(stream.ToArray());
                }
            }
            return(null);
        }
        /// <summary>
        /// Enables processing of HTTP Web requests by a custom HttpHandler
        /// that implements the <see cref="T:System.Web.IHttpHandler"/> interface.
        /// </summary>
        /// <param name="context">
        /// An <see cref="T:System.Web.HttpContext"/> object that provides
        /// references to the intrinsic server objects (for example, Request,
        /// Response, Session, and Server) used to service HTTP requests.
        /// </param>
        public void ProcessRequest(HttpContext context)
        {
            try
            {
                // We want aggressive caching since the barcode will not change
                //	for a given set of request parameters however we disable
                //	caching on proxy servers...
                context.Response.Cache.SetCacheability(HttpCacheability.ServerAndPrivate);

                // Determine the symbology desired
                string           symbologyText = context.Request.QueryString["sym"];
                BarcodeSymbology symbology;
                if (!TryParseEnum <BarcodeSymbology>(symbologyText, true, out symbology) ||
                    symbology == BarcodeSymbology.Unknown)
                {
                    throw new ArgumentException("Unable to determine symbology.");
                }

                // Get the text to render from the context
                // NOTE: We URL decode it first...
                string textToRender =
                    context.Server.UrlDecode(
                        context.Request.QueryString["text"]);
                if (string.IsNullOrEmpty(textToRender))
                {
                    throw new ArgumentException("Must have text to render as barcode.");
                }

                // Get the rendering metrics from the context
                BarcodeMetrics metrics = GetBarcodeMetricsFromContext(context, symbology);

                // Determine the image format (default is jpeg)
                RenderImageFormat format;
                string            imageFormatText = context.Request.QueryString["itype"];
                if (!TryParseEnum <RenderImageFormat>(imageFormatText, true, out format))
                {
                    format = RenderImageFormat.Jpeg;
                }

                // Setup content-type and image format for saving
                ImageFormat imageFormat;
                switch (format)
                {
                case RenderImageFormat.Jpeg:
                    imageFormat = ImageFormat.Jpeg;
                    context.Response.ContentType = "image/jpeg";
                    break;

                case RenderImageFormat.Png:
                    imageFormat = ImageFormat.Png;
                    context.Response.ContentType = "image/png";
                    break;

                default:
                    throw new ArgumentException(
                              "Unexpected rendering image format encountered.");
                }

                // If we can find an encoder for the image type then attempt
                //	to set top quality and monochrome colour depth.
                ImageCodecInfo codecInfo = ImageCodecInfo.GetImageEncoders()
                                           .FirstOrDefault((item) => item.FormatID == imageFormat.Guid);
                EncoderParameters codecParameters = null;
                if (codecInfo != null)
                {
                    // Two parameters; maximum quality and monochrome
                    codecParameters          = new EncoderParameters(2);
                    codecParameters.Param[0] = new EncoderParameter(Encoder.Quality, 100L);
                    codecParameters.Param[1] = new EncoderParameter(Encoder.ColorDepth, 2);
                }

                // Create instance of barcode rendering engine
                BarcodeDraw drawObject = BarcodeDrawFactory.GetSymbology(symbology);
                using (Image image = drawObject.Draw(textToRender, metrics))
                {
                    // Save image to the response stream directly
                    // TODO: Should the response have buffer enabled?
                    if (codecInfo == null)
                    {
                        image.Save(context.Response.OutputStream, imageFormat);
                    }
                    else
                    {
                        image.Save(context.Response.OutputStream, codecInfo, codecParameters);
                    }
                }

                // Set status and finalise request handling.
                context.Response.StatusCode = 200;
                context.Response.End();
            }
            catch (Exception)
            {
                // TODO: Log the error and return a 500...
                context.Response.StatusCode = 500;
                context.Response.End();
            }
        }
        private static BarcodeMetrics GetBarcodeMetricsFromContext(
            HttpContext context, BarcodeSymbology symbology)
        {
            BarcodeDraw    drawObject = BarcodeDrawFactory.GetSymbology(symbology);
            BarcodeMetrics metrics    = drawObject.GetDefaultMetrics(30);

            BarcodeMetrics1d metrics1d = metrics as BarcodeMetrics1d;

            if (metrics1d != null)
            {
                // Get query parameter strings
                string barHeightText        = context.Request.QueryString["bh"];
                string barWidthText         = context.Request.QueryString["bw"];
                string minimumBarHeightText = context.Request.QueryString["mbh"];
                string maximumBarHeightText = context.Request.QueryString["xbh"];
                string minimumBarWidthText  = context.Request.QueryString["mbw"];
                string maximumBarWidthText  = context.Request.QueryString["xbw"];
                string interGlyphSpaceText  = context.Request.QueryString["igs"];

                int value;
                if (int.TryParse(barWidthText, out value))
                {
                    metrics1d.MinWidth = metrics1d.MaxWidth = value;
                }
                if (int.TryParse(minimumBarWidthText, out value))
                {
                    metrics1d.MinWidth = value;
                }
                if (int.TryParse(maximumBarWidthText, out value))
                {
                    metrics1d.MaxWidth = value;
                }
                if (int.TryParse(barHeightText, out value))
                {
                    metrics1d.MinHeight = metrics1d.MaxHeight = value;
                }
                if (int.TryParse(minimumBarHeightText, out value))
                {
                    metrics1d.MinHeight = value;
                }
                if (int.TryParse(maximumBarHeightText, out value))
                {
                    metrics1d.MaxHeight = value;
                }
                if (int.TryParse(interGlyphSpaceText, out value))
                {
                    metrics1d.InterGlyphSpacing = value;
                }
            }
            else if (symbology == BarcodeSymbology.CodeQr)
            {
                BarcodeMetricsQr qrMetrics = (BarcodeMetricsQr)metrics;

                string encodeMode   = context.Request.QueryString["em"];
                string errorCorrect = context.Request.QueryString["ec"];
                string scale        = context.Request.QueryString["sca"];
                string version      = context.Request.QueryString["ver"];

                int value;
                if (int.TryParse(encodeMode, out value))
                {
                    qrMetrics.EncodeMode = (QrEncodeMode)value;
                }
                if (int.TryParse(errorCorrect, out value))
                {
                    qrMetrics.ErrorCorrection = (QrErrorCorrection)value;
                }
                if (int.TryParse(scale, out value))
                {
                    qrMetrics.Scale = value;
                }
                if (int.TryParse(version, out value))
                {
                    qrMetrics.Version = value;
                }
            }

            return(metrics);
        }
Esempio n. 30
0
        private void RefreshBarcodeImage()
        {
            // Allocate new barcode image as needed
            if (_symbology != BarcodeSymbology.Unknown && !string.IsNullOrEmpty(Text))
            {
                try
                {
                    var drawObject = BarcodeDrawFactory.GetSymbology(_symbology);

                    var metrics = drawObject.GetDefaultMetrics(_maxBarHeight);
                    metrics.Scale = _scaleBarWidth;

                    var barcodeImage = drawObject.Draw(Text, metrics);

                    Bitmap resultImage = null;

                    if (IsDisplayPriceLabel)
                    {
                        resultImage = new Bitmap(barcodeImage.Width, barcodeImage.Height + 37); // is bottom padding, adjust to your text
                    }
                    else
                    {
                        resultImage = new Bitmap(barcodeImage.Width, barcodeImage.Height + 30); // is bottom padding, adjust to your text
                    }
                    using (var graphics = Graphics.FromImage(resultImage))
                    {
                        using (var font = new Font("Consolas", 10))
                        {
                            using (var brush = new SolidBrush(Color.Black))
                            {
                                using (var format = new StringFormat()
                                {
                                    Alignment = StringAlignment.Center,
                                    LineAlignment = StringAlignment.Far
                                })
                                {
                                    graphics.Clear(Color.White);

                                    float headerLabelY  = 70f;
                                    float barcodeImageY = 15f;
                                    float barcodeY      = 7f;

                                    if (!IsDisplayPriceLabel)
                                    {
                                        headerLabelY  = 65f;
                                        barcodeImageY = 14f;
                                        barcodeY      = 0f;
                                    }

                                    // draw barcode header
                                    graphics.DrawString(HeaderLabel, font, brush, resultImage.Width / 2, resultImage.Height - headerLabelY, format);

                                    // draw barcode image
                                    graphics.DrawImage(barcodeImage, 0, barcodeImageY);

                                    // draw barcode code
                                    graphics.DrawString(Text, font, brush, resultImage.Width / 2, resultImage.Height - barcodeY, format);

                                    // draw barcode price
                                    if (IsDisplayPriceLabel)
                                    {
                                        graphics.DrawString(string.Format("Rp.{0:N0}", PriceLabel), font, brush, resultImage.Width / 2, resultImage.Height + 3, format);
                                    }
                                }
                            }
                        }
                    }

                    BackgroundImage = resultImage;
                }
                catch
                {
                    BackgroundImage = null;
                }
            }
            else
            {
                BackgroundImage = null;
            }

            // Setup the auto-scroll minimum size
            if (BackgroundImage == null)
            {
                AutoScrollMinSize = new Size(0, 0);
            }
            else
            {
                AutoScrollMinSize = BackgroundImage.Size;
            }
        }