C# 条码打印程序(一维码和二维码)

C# 条码打印程序(一维码和二维码)

实现方案

1. 选择条码生成库

对于条码生成,推荐使用以下NuGet包:

2. 安装必要的NuGet包

Install-Package ZXing.Net
Install-Package BarcodeLib

3. 完整实现代码

using System;
using System.Drawing;
using System.Drawing.Printing;
using System.Windows.Forms;
using ZXing;
using ZXing.QrCode;
using BarcodeLib; // 用于一维码生成

namespace BarcodePrinterApp
{
    public partial class MainForm : Form
    {
        private Barcode barcode; // 一维码生成器
        private PrintDocument printDocument;
        private Image barcodeImage; // 要打印的条码图像

        public MainForm()
        {
            InitializeComponent();
            InitializeComponents();
        }

        private void InitializeComponents()
        {
            // 初始化条码生成器
            barcode = new Barcode();
            barcode.IncludeLabel = true; // 包含文本标签
            
            // 初始化打印文档
            printDocument = new PrintDocument();
            printDocument.PrintPage += PrintDocument_PrintPage;
            
            // 创建UI控件
            this.Text = "条码打印程序";
            this.Size = new Size(500, 400);
            
            var lblText = new Label { Text = "条码内容:", Location = new Point(20, 20), Size = new Size(80, 20) };
            var txtContent = new TextBox { Location = new Point(100, 20), Size = new Size(200, 20), Text = "1234567890" };
            
            var lblType = new Label { Text = "条码类型:", Location = new Point(20, 50), Size = new Size(80, 20) };
            var cmbType = new ComboBox { Location = new Point(100, 50), Size = new Size(200, 20) };
            cmbType.Items.AddRange(new object[] { "一维码 - Code128", "一维码 - Code39", "二维码 - QR Code" });
            cmbType.SelectedIndex = 0;
            
            var btnGenerate = new Button { Text = "生成条码", Location = new Point(20, 80), Size = new Size(100, 30) };
            var btnPrint = new Button { Text = "打印条码", Location = new Point(130, 80), Size = new Size(100, 30) };
            
            var picBarcode = new PictureBox { Location = new Point(20, 120), Size = new Size(300, 200), BorderStyle = BorderStyle.FixedSingle };
            
            // 添加事件处理
            btnGenerate.Click += (s, e) => 
            {
                if (string.IsNullOrEmpty(txtContent.Text))
                {
                    MessageBox.Show("请输入条码内容");
                    return;
                }
                
                try
                {
                    if (cmbType.SelectedItem.ToString().Contains("一维码"))
                    {
                        // 生成一维码
                        TYPE barcodeType = cmbType.SelectedIndex == 0 ? TYPE.CODE128 : TYPE.CODE39;
                        barcodeImage = barcode.Encode(barcodeType, txtContent.Text, Color.Black, Color.White, 300, 100);
                    }
                    else
                    {
                        // 生成二维码
                        var qrWriter = new BarcodeWriter
                        {
                            Format = BarcodeFormat.QR_CODE,
                            Options = new QrCodeEncodingOptions
                            {
                                Height = 200,
                                Width = 200,
                                Margin = 1
                            }
                        };
                        barcodeImage = qrWriter.Write(txtContent.Text);
                    }
                    
                    picBarcode.Image = barcodeImage;
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"生成条码时出错: {ex.Message}");
                }
            };
            
            btnPrint.Click += (s, e) => 
            {
                if (barcodeImage == null)
                {
                    MessageBox.Show("请先生成条码");
                    return;
                }
                
                try
                {
                    // 显示打印对话框
                    PrintDialog printDialog = new PrintDialog();
                    printDialog.Document = printDocument;
                    
                    if (printDialog.ShowDialog() == DialogResult.OK)
                    {
                        printDocument.Print();
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"打印时出错: {ex.Message}");
                }
            };
            
            // 添加控件到窗体
            this.Controls.AddRange(new Control[] { lblText, txtContent, lblType, cmbType, btnGenerate, btnPrint, picBarcode });
        }

        private void PrintDocument_PrintPage(object sender, PrintPageEventArgs e)
        {
            if (barcodeImage != null)
            {
                // 计算居中位置
                int x = (e.PageBounds.Width - barcodeImage.Width) / 2;
                int y = (e.PageBounds.Height - barcodeImage.Height) / 2;
                
                // 绘制条码
                e.Graphics.DrawImage(barcodeImage, x, y);
            }
        }

        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new MainForm());
        }
    }
}

 

功能说明

  1. 条码生成

    • 支持一维码(Code128和Code39)
    • 支持二维码(QR Code)
    • 可自定义条码内容
  2. 打印功能

    • 使用标准打印对话框
    • 自动居中打印条码
    • 支持选择打印机和设置打印参数

推荐项目 C# 条码打印程序(一维码和二维码) www.youwenfan.com/contentzhe/52029.html

扩展功能

如果您需要更高级的功能,可以考虑以下扩展:

1. 添加条码设置选项

// 可以添加设置条码大小、颜色、边距等选项的UI控件
var nudWidth = new NumericUpDown { Minimum = 100, Maximum = 500, Value = 200 };
var nudHeight = new NumericUpDown { Minimum = 50, Maximum = 500, Value = 100 };

2. 批量打印功能

// 可以添加数据源(如数据库或Excel文件)来批量生成和打印条码
public void PrintBatches(List<string> barcodeContents)
{
    foreach (var content in barcodeContents)
    {
        // 生成条码
        // 打印条码
        // 可添加分页逻辑
    }
}

3. 保存条码图像

// 添加保存功能
var btnSave = new Button { Text = "保存条码", Location = new Point(240, 80), Size = new Size(100, 30) };
btnSave.Click += (s, e) => 
{
    if (barcodeImage != null)
    {
        SaveFileDialog saveDialog = new SaveFileDialog();
        saveDialog.Filter = "PNG Image|*.png|JPEG Image|*.jpg|BMP Image|*.bmp";
        if (saveDialog.ShowDialog() == DialogResult.OK)
        {
            barcodeImage.Save(saveDialog.FileName);
        }
    }
};

 

专注于matlab/simulink,电子电路,编程