C#生成条形码打印

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Printing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ZXing;
using ZXing.Common;
using ZXing.QrCode;
using System.IO;


namespace Jbarcode
{
    public partial class Form1 : Form
    {

        PrintDocument pd = new PrintDocument();
        Bitmap printImage = null;
        public Form1()
        {
            InitializeComponent();
            pd.PrintPage += new PrintPageEventHandler(this.pd_PrintPage);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //this.pictureBox1.BackColor = Color.Red;
            //ITF偶数码 MSI长度随意
            EncodingOptions options = new EncodingOptions
            {
                Width = 400,
                Height = 100 
            };
            BarcodeWriter writer = new BarcodeWriter
            {
                //Format = BarcodeFormat.MSI,
                Format = BarcodeFormat.CODE_128,
                Options = options
            };
            Bitmap bitmap = writer.Write("5294106");
            
            Bitmap newbm = KiSetText(bitmap, "5294106", 10, 5);
            pictureBox1.Image = newbm;
            printImage = newbm;
            newbm.Save("C:\\A.png", System.Drawing.Imaging.ImageFormat.Png);
            //pd.Print();

        }

        //打印事件处理
        private void pd_PrintPage(object sender, PrintPageEventArgs e)
        {
            int x = e.MarginBounds.X;
            int y = e.MarginBounds.Y;
            int width = printImage.Width;
            int height = printImage.Height;
            Rectangle destRect = new Rectangle(x, y, width, height);
            e.Graphics.DrawImage(printImage, destRect, 0, 0, printImage.Width, printImage.Height, System.Drawing.GraphicsUnit.Pixel);
        }

        public static Bitmap KiSetText(Bitmap b, string txt, int x, int y)
        {
            if (b == null)
            {
                return null;
            }

            Bitmap resizeImage = new Bitmap(440,140);
            Graphics gfx = Graphics.FromImage(resizeImage);
            gfx.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;

            gfx.FillRectangle(Brushes.White, new Rectangle(0, 0, resizeImage.Width, resizeImage.Height));
            
            gfx.DrawImageUnscaled(b, 20, 30);


            // 作为演示,我们用Arial字体,大小为32,红色。
            FontFamily fm = new FontFamily("Arial");
            Font font = new Font(fm, 20, FontStyle.Regular, GraphicsUnit.Pixel);
            SolidBrush sb = new SolidBrush(Color.Black);

            gfx.DrawString(txt, font, sb, new PointF(x, y));
            gfx.Dispose();

            return resizeImage;
        }

    }
}

 

你可能感兴趣的:(C#)