使用BarcodeLib库创建barcode是很容易的,实现打印页很容易。
界面如下:
第一文本框是生成条码的内容,这个依据自己的实际需要。Width是定义条码的宽度,Height是定义条码的高度,接下来的2个文本宽是定义打印时一行放置几个Label,打印多少行。
首先添加barcodeLib库:
代码创建方式如下,仅以Code128为例:
BarcodeLib.Barcode barcode = new Barcode();
private void btnGenerator_Click(object sender, EventArgs e)
{
if (txtBarcode.Text.Trim() == "")
{
MessageBox.Show("Input Barcode", "Message", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
if (txtWidth.Text.Trim() == "")
{
MessageBox.Show("Input Width", "Message", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
if (txtHeight.Text.Trim() == "")
{
MessageBox.Show("Input Height", "Message", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
errorProvider1.Clear();
int nW = Convert.ToInt32(txtWidth.Text.Trim());
int nH = Convert.ToInt32(txtHeight.Text.Trim());
barcode.Alignment = BarcodeLib.AlignmentPositions.CENTER;
BarcodeLib.TYPE ty = BarcodeLib.TYPE.UNSPECIFIED;
ty = BarcodeLib.TYPE.CODE128;
try
{
if (ty != BarcodeLib.TYPE.UNSPECIFIED)
{
barcode.IncludeLabel = true;
barcode.RotateFlipType = (RotateFlipType)Enum.Parse(typeof(RotateFlipType), "RotateNoneFlipNone", true);
pictureBox1.Image = barcode.Encode(ty, txtBarcode.Text, Color.Black, Color.White, nW, nH);
}
pictureBox1.Height = barcode.Height;
pictureBox1.Width = barcode.Width;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
打印代码:
private void printDoc\_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
//int rowNums = Convert.ToInt32(txtRowNumbers.Text);
//int colNums = Convert.ToInt32(txtColNumbers.Text);
using (Graphics graph = e.Graphics)
{
int rowY = 0;
for (int x = 0; x < 5; x++)
{
int rowX = 0;
for (int j = 0; j < 8; j++)
{
graph.DrawImage(pictureBox1.Image, rowY + 10, 5 + rowX);
rowX = rowX + barcode.Height + 32;
}
rowY = rowY + barcode.Width + 22;
}
}
}
private void btnPrint\_Click(object sender, EventArgs e)
{
printDoc.Print();
}
固定5列8行,打印效果如下:
|