C#通过ZXing 打印条形码
1、通过nuget 安装 Zxing 插件并引用
using ZXing;
using ZXing.QrCode.Internal;
using ZXing.Common;
using ZXing.QrCode;
2、演示界面
3、打印效果
4、主要代码
双击 printDocument1控件,编写如下示例代码:
private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
string batchNo;
batchNo = textBox1.Text;
Bitmap btm = BarCode(batchNo);
int num1 = 200;
//标签文字开始X点
//文字从第几列开始打,横坐标
int x1 = 280;
//文字开始打印的高度
int y1 = 111;
int yStep = 50; //行间距
Pen pen = new Pen(Color.Black, 1f);
Font font = new Font("宋体", 17f, FontStyle.Bold);
//黑色笔
Brush fontColor = Brushes.Black;
// 绘制到屏幕上。
e.Graphics.DrawString(textBox1.Text, font, fontColor, x1, y1);
x1 = x1 + 100;
//消除锯齿
e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
e.Graphics.DrawImage(btm, x1,y1, btm.Width, btm.Height);
}
“打印”按钮的事件,就是调用printDocument1的print()函数
private void button1_Click(object sender, EventArgs e)
{
printDocument1.Print();
}
条形码生成函数
//根据文字生成一维条形码函数
public static Bitmap BarCode(string text)
{
BarcodeWriter writer = new BarcodeWriter();
writer.Format = BarcodeFormat.CODE_128;
EncodingOptions options = new EncodingOptions()
{
Width = 150,
Height = 50,
Margin = 0,
//true:一维码下方不显示文字 false:显示文字,默认是显示
PureBarcode = false
};
writer.Options = options;
Bitmap map = writer.Write(text);
return map;
}
活到老,学到老。