C#(Winform)实现条码打印

电脑上安装了39条码字体:C39HrP24DlTt

先看下控件界面截图

C#(Winform)实现条码打印_第1张图片

转换条码字体
        private void button1_Click(object sender, EventArgs e)
{
Bitmap b1 = new Bitmap(Convert.ToInt32(textBox2.Text), Convert.ToInt32 ( textBox3.Text));
Graphics g1 = Graphics.FromImage(b1);
Font font1 = new Font("C39HrP24DlTt", Convert.ToInt32(textBox4.Text));
g1.DrawString(textBox1.Text.ToString(), font1, Brushes.Black, new PointF(Convert.ToInt32(textBox5.Text), Convert.ToInt32(textBox6.Text)));
pictureBox1.BackgroundImage = b1;
pictureBox1.BackgroundImageLayout = ImageLayout.Zoom;
}

pageSetupDialog1、printDialog1、printPreviewDialog1的document属性都选择为printDocument1

给printDocument1添加一个PrintPage事件printDocument1_PrintPage

打印设置
        private void button2_Click(object sender, EventArgs e)
{
this.pageSetupDialog1.ShowDialog();

}
打印预览
        private void button3_Click(object sender, EventArgs e)
{
this.printPreviewDialog1.ShowDialog();

}
打印
        private void button4_Click(object sender, EventArgs e)
{
if (this.printDialog1.ShowDialog() == DialogResult.OK)
{
this.printDocument1.Print();
}
}
打印内容的设置
        private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
//打印内容 为 整个Form
//Image myFormImage;
//myFormImage = new Bitmap(this.Width, this.Height);
//Graphics g = Graphics.FromImage(myFormImage);
//g.CopyFromScreen(this.Location.X, this.Location.Y, 0, 0, this.Size);
//e.Graphics.DrawImage(myFormImage, 0, 0);

//打印内容 为 局部的 this.groupBox1
Bitmap _NewBitmap = new Bitmap(groupBox1.Width, groupBox1.Height);
groupBox1.DrawToBitmap(_NewBitmap, new Rectangle(0, 0, _NewBitmap.Width, _NewBitmap.Height));
e.Graphics.DrawImage(_NewBitmap, 0, 0, _NewBitmap.Width, _NewBitmap.Height);

//打印内容 为 自定义文本内容
/*Font font = new Font("宋体", 12);
Brush bru = Brushes.Blue;
for (int i = 1; i <= 5; i++)
{
e.Graphics.DrawString("Hello world ", font, bru, i*20, i*20);
}
*/
}
public Form1()
        public Form1()
{
InitializeComponent();
this.printDocument1.OriginAtMargins = true;//启用页边距
this.pageSetupDialog1.EnableMetric = true; //以毫米为单位
}

没有做异常处理,比如没有启动打印服务的情况下,程序会不友好地报错。

转成39条码字体,支持的字符有
A-Z,26个字母,不分大小写,都表示成大写;
0-9,10个数字;
+-*/%$.,7个符号;
space,空格。

C#(Winform)实现条码打印_第2张图片

C#(Winform)实现条码打印_第3张图片

你可能感兴趣的:(WinForm)