C# WinForms 条形码生成器(含保存和打印预览功能)

C# WinForms应用程序,可以生成多种格式的条形码,支持保存到本地文件和打印预览功能。

源代码

csharp 复制代码
using System;
using System.Drawing;
using System.Drawing.Printing;
using System.IO;
using System.Windows.Forms;
using ZXing;
using ZXing.Common;
using ZXing.QrCode;
using ZXing.Rendering;

namespace BarcodeGenerator
{
    public partial class MainForm : Form
    {
        private Bitmap barcodeBitmap = null;
        private PrintDocument printDocument = new PrintDocument();
        private string lastGeneratedContent = "";

        public MainForm()
        {
            InitializeComponent();
            InitializeUI();
            printDocument.PrintPage += PrintDocument_PrintPage;
        }

        private void InitializeUI()
        {
            // 窗体设置
            this.Text = "条形码生成器";
            this.Size = new Size(800, 600);
            this.StartPosition = FormStartPosition.CenterScreen;
            this.BackColor = Color.FromArgb(240, 240, 240);

            // 主布局
            TableLayoutPanel mainLayout = new TableLayoutPanel
            {
                Dock = DockStyle.Fill,
                ColumnCount = 2,
                RowCount = 4,
                Padding = new Padding(10)
            };
            mainLayout.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 30F));
            mainLayout.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 70F));
            mainLayout.RowStyles.Add(new RowStyle(SizeType.Absolute, 80));
            mainLayout.RowStyles.Add(new RowStyle(SizeType.Percent, 40F));
            mainLayout.RowStyles.Add(new RowStyle(SizeType.Percent, 40F));
            mainLayout.RowStyles.Add(new RowStyle(SizeType.Absolute, 80));

            // 标题
            Label titleLabel = new Label
            {
                Text = "条形码生成器",
                Font = new Font("微软雅黑", 18, FontStyle.Bold),
                ForeColor = Color.DarkBlue,
                Dock = DockStyle.Fill,
                TextAlign = ContentAlignment.MiddleCenter
            };
            mainLayout.Controls.Add(titleLabel, 0, 0);
            mainLayout.SetColumnSpan(titleLabel, 2);

            // 左侧控制面板
            Panel controlPanel = CreateControlPanel();
            mainLayout.Controls.Add(controlPanel, 0, 1);
            mainLayout.SetRowSpan(controlPanel, 2);

            // 右侧预览面板
            Panel previewPanel = CreatePreviewPanel();
            mainLayout.Controls.Add(previewPanel, 1, 1);
            mainLayout.SetRowSpan(previewPanel, 2);

            // 底部按钮面板
            Panel buttonPanel = CreateButtonPanel();
            mainLayout.Controls.Add(buttonPanel, 0, 3);
            mainLayout.SetColumnSpan(buttonPanel, 2);

            this.Controls.Add(mainLayout);
        }

        private Panel CreateControlPanel()
        {
            Panel panel = new Panel
            {
                Dock = DockStyle.Fill,
                BorderStyle = BorderStyle.FixedSingle,
                Padding = new Padding(10),
                BackColor = Color.White
            };

            // 条码类型选择
            Label typeLabel = new Label
            {
                Text = "条码类型:",
                Location = new Point(10, 15),
                AutoSize = true,
                Font = new Font("微软雅黑", 10)
            };
            panel.Controls.Add(typeLabel);

            ComboBox typeCombo = new ComboBox
            {
                DropDownStyle = ComboBoxStyle.DropDownList,
                Location = new Point(100, 12),
                Size = new Size(150, 25),
                Font = new Font("微软雅黑", 9)
            };
            typeCombo.Items.AddRange(new object[] { "QR Code", "Code 128", "EAN-13", "UPC-A", "Code 39", "ITF" });
            typeCombo.SelectedIndex = 0;
            panel.Controls.Add(typeCombo);

            // 内容输入
            Label contentLabel = new Label
            {
                Text = "条码内容:",
                Location = new Point(10, 50),
                AutoSize = true,
                Font = new Font("微软雅黑", 10)
            };
            panel.Controls.Add(contentLabel);

            TextBox contentBox = new TextBox
            {
                Location = new Point(100, 47),
                Size = new Size(150, 25),
                Font = new Font("微软雅黑", 9),
                Text = "https://github.com"
            };
            panel.Controls.Add(contentBox);

            // 尺寸设置
            Label sizeLabel = new Label
            {
                Text = "条码尺寸:",
                Location = new Point(10, 85),
                AutoSize = true,
                Font = new Font("微软雅黑", 10)
            };
            panel.Controls.Add(sizeLabel);

            NumericUpDown widthBox = new NumericUpDown
            {
                Location = new Point(100, 82),
                Size = new Size(70, 25),
                Minimum = 100,
                Maximum = 1000,
                Value = 300,
                Font = new Font("微软雅黑", 9)
            };
            panel.Controls.Add(widthBox);

            Label xLabel = new Label
            {
                Text = "x",
                Location = new Point(175, 85),
                AutoSize = true,
                Font = new Font("微软雅黑", 10)
            };
            panel.Controls.Add(xLabel);

            NumericUpDown heightBox = new NumericUpDown
            {
                Location = new Point(190, 82),
                Size = new Size(70, 25),
                Minimum = 100,
                Maximum = 1000,
                Value = 300,
                Font = new Font("微软雅黑", 9)
            };
            panel.Controls.Add(heightBox);

            // 生成按钮
            Button generateBtn = new Button
            {
                Text = "生成条形码",
                Location = new Point(100, 120),
                Size = new Size(150, 35),
                BackColor = Color.SteelBlue,
                ForeColor = Color.White,
                FlatStyle = FlatStyle.Flat,
                Font = new Font("微软雅黑", 10, FontStyle.Bold)
            };
            generateBtn.Click += (sender, e) =>
            {
                GenerateBarcode(
                    contentBox.Text,
                    typeCombo.SelectedItem.ToString(),
                    (int)widthBox.Value,
                    (int)heightBox.Value
                );
                lastGeneratedContent = contentBox.Text;
            };
            panel.Controls.Add(generateBtn);

            return panel;
        }

        private Panel CreatePreviewPanel()
        {
            Panel panel = new Panel
            {
                Dock = DockStyle.Fill,
                BorderStyle = BorderStyle.FixedSingle,
                Padding = new Padding(10),
                BackColor = Color.WhiteSmoke
            };

            // 预览标签
            Label previewLabel = new Label
            {
                Text = "条码预览",
                Dock = DockStyle.Top,
                TextAlign = ContentAlignment.MiddleCenter,
                Font = new Font("微软雅黑", 12, FontStyle.Bold),
                Height = 30,
                BackColor = Color.LightSteelBlue
            };
            panel.Controls.Add(previewLabel);

            // 预览区域
            PictureBox previewBox = new PictureBox
            {
                Name = "previewBox",
                Dock = DockStyle.Fill,
                SizeMode = PictureBoxSizeMode.Zoom,
                BorderStyle = BorderStyle.FixedSingle,
                BackColor = Color.White
            };
            panel.Controls.Add(previewBox);

            return panel;
        }

        private Panel CreateButtonPanel()
        {
            Panel panel = new Panel
            {
                Dock = DockStyle.Fill,
                BackColor = Color.Transparent
            };

            // 保存按钮
            Button saveBtn = new Button
            {
                Text = "保存条码",
                Size = new Size(120, 40),
                Location = new Point(150, 20),
                BackColor = Color.ForestGreen,
                ForeColor = Color.White,
                FlatStyle = FlatStyle.Flat,
                Font = new Font("微软雅黑", 10, FontStyle.Bold)
            };
            saveBtn.Click += SaveBarcode;
            panel.Controls.Add(saveBtn);

            // 打印预览按钮
            Button printPreviewBtn = new Button
            {
                Text = "打印预览",
                Size = new Size(120, 40),
                Location = new Point(300, 20),
                BackColor = Color.DarkOrange,
                ForeColor = Color.White,
                FlatStyle = FlatStyle.Flat,
                Font = new Font("微软雅黑", 10, FontStyle.Bold)
            };
            printPreviewBtn.Click += ShowPrintPreview;
            panel.Controls.Add(printPreviewBtn);

            // 退出按钮
            Button exitBtn = new Button
            {
                Text = "退出程序",
                Size = new Size(120, 40),
                Location = new Point(450, 20),
                BackColor = Color.Firebrick,
                ForeColor = Color.White,
                FlatStyle = FlatStyle.Flat,
                Font = new Font("微软雅黑", 10, FontStyle.Bold)
            };
            exitBtn.Click += (sender, e) => this.Close();
            panel.Controls.Add(exitBtn);

            return panel;
        }

        private void GenerateBarcode(string content, string barcodeType, int width, int height)
        {
            try
            {
                BarcodeFormat format = BarcodeFormat.QR_CODE;
                switch (barcodeType)
                {
                    case "QR Code": format = BarcodeFormat.QR_CODE; break;
                    case "Code 128": format = BarcodeFormat.CODE_128; break;
                    case "EAN-13": format = BarcodeFormat.EAN_13; break;
                    case "UPC-A": format = BarcodeFormat.UPC_A; break;
                    case "Code 39": format = BarcodeFormat.CODE_39; break;
                    case "ITF": format = BarcodeFormat.ITF; break;
                }

                var writer = new BarcodeWriterPixelData
                {
                    Format = format,
                    Options = new EncodingOptions
                    {
                        Width = width,
                        Height = height,
                        Margin = 2,
                        PureBarcode = false
                    }
                };

                var pixelData = writer.Write(content);
                barcodeBitmap = new Bitmap(pixelData.Width, pixelData.Height, PixelFormat.Format32bppRgb);
                using (var graphics = Graphics.FromImage(barcodeBitmap))
                {
                    var bitmapData = new BitmapData
                    {
                        Width = pixelData.Width,
                        Height = pixelData.Height,
                        PixelFormat = PixelFormat.Format32bppRgb,
                        Stride = pixelData.Width * 4,
                        Scan0 = pixelData.Pixels
                    };
                    var rect = new Rectangle(0, 0, pixelData.Width, pixelData.Height);
                    graphics.DrawImage(Bitmap.FromHbitmap(barcodeBitmap.GetHbitmap()), rect);
                }

                // 显示预览
                PictureBox previewBox = (PictureBox)this.Controls[0].Controls[1].Controls[0].Controls[1];
                previewBox.Image = barcodeBitmap;
            }
            catch (Exception ex)
            {
                MessageBox.Show($"生成条形码时出错: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void SaveBarcode(object sender, EventArgs e)
        {
            if (barcodeBitmap == null)
            {
                MessageBox.Show("请先生成条形码!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            using (SaveFileDialog saveDialog = new SaveFileDialog())
            {
                saveDialog.Filter = "PNG 图片|*.png|JPEG 图片|*.jpg|BMP 图片|*.bmp|所有文件|*.*";
                saveDialog.Title = "保存条形码";
                saveDialog.FileName = $"Barcode_{DateTime.Now:yyyyMMddHHmmss}";

                if (saveDialog.ShowDialog() == DialogResult.OK)
                {
                    ImageFormat format = ImageFormat.Png;
                    string ext = Path.GetExtension(saveDialog.FileName).ToLower();
                    if (ext == ".jpg" || ext == ".jpeg") format = ImageFormat.Jpeg;
                    else if (ext == ".bmp") format = ImageFormat.Bmp;

                    try
                    {
                        barcodeBitmap.Save(saveDialog.FileName, format);
                        MessageBox.Show("条形码保存成功!", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show($"保存失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
        }

        private void ShowPrintPreview(object sender, EventArgs e)
        {
            if (barcodeBitmap == null)
            {
                MessageBox.Show("请先生成条形码!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            PrintPreviewDialog previewDialog = new PrintPreviewDialog
            {
                Document = printDocument,
                WindowState = FormWindowState.Maximized
            };
            previewDialog.ShowDialog();
        }

        private void PrintDocument_PrintPage(object sender, PrintPageEventArgs e)
        {
            if (barcodeBitmap != null)
            {
                // 计算居中位置
                int x = (e.MarginBounds.Width - barcodeBitmap.Width) / 2 + e.MarginBounds.Left;
                int y = (e.MarginBounds.Height - barcodeBitmap.Height) / 2 + e.MarginBounds.Top;

                // 绘制条形码
                e.Graphics.DrawImage(barcodeBitmap, x, y);

                // 添加文本信息
                Font textFont = new Font("Arial", 12);
                Brush textBrush = Brushes.Black;
                string displayText = lastGeneratedContent.Length > 50 
                    ? lastGeneratedContent.Substring(0, 47) + "..." 
                    : lastGeneratedContent;
                
                e.Graphics.DrawString(displayText, textFont, textBrush, 
                    new PointF(x, y + barcodeBitmap.Height + 10));

                // 添加页脚
                Font footerFont = new Font("Arial", 10);
                e.Graphics.DrawString($"打印时间: {DateTime.Now:yyyy-MM-dd HH:mm:ss}", 
                    footerFont, textBrush, 
                    new PointF(e.MarginBounds.Left, e.MarginBounds.Bottom - 30));
            }
        }
    }
}

使用说明

1. 准备工作

  • 创建新的WinForms项目

  • 安装NuGet包:Install-Package ZXing.Net

2. 功能特点

  • 支持多种条码格式:QR Code、Code 128、EAN-13、UPC-A、Code 39、ITF

  • 可自定义条码尺寸

  • 实时预览生成的条码

  • 保存为多种图片格式(PNG/JPG/BMP)

  • 打印预览功能(带文本信息)

  • 美观的用户界面

3. 使用步骤

  1. 选择条码类型

  2. 输入条码内容

  3. 设置条码尺寸

  4. 点击"生成条形码"按钮

  5. 使用"保存条码"按钮保存到本地

  6. 使用"打印预览"按钮查看打印效果

4. 界面说明

  • 顶部:标题栏

  • 左侧控制面板

    • 条码类型选择下拉框

    • 条码内容输入框

    • 条码尺寸设置(宽度和高度)

    • 生成按钮

  • 右侧预览面板

    • 条码预览区域
  • 底部按钮面板

  • 保存条码按钮

  • 打印预览按钮

  • 退出程序按钮

扩展功能建议

  1. 添加更多条码格式

    csharp 复制代码
    // 在GenerateBarcode方法中添加更多格式
    case "PDF417": format = BarcodeFormat.PDF_417; break;
    case "Data Matrix": format = BarcodeFormat.DATA_MATRIX; break;
  2. 添加条码颜色设置

    csharp 复制代码
    // 在GenerateBarcode方法中添加颜色设置
    var writer = new BarcodeWriterPixelData
    {
        Format = format,
        Renderer = new BitmapRenderer { Foreground = Color.Black, Background = Color.White },
        Options = new EncodingOptions { /* ... */ }
    };
  3. 添加批量生成功能

    csharp 复制代码
    // 添加批量生成按钮和逻辑
    private void BatchGenerate()
    {
        OpenFileDialog openDialog = new OpenFileDialog { Multiselect = true };
        if (openDialog.ShowDialog() == DialogResult.OK)
        {
            foreach (string file in openDialog.FileNames)
            {
                string content = File.ReadAllText(file);
                GenerateBarcode(content, "QR Code", 300, 300);
                SaveBarcodeToFile($"{Path.GetFileNameWithoutExtension(file)}.png");
            }
        }
    }
  4. 添加数据库支持

    csharp 复制代码
    // 添加数据库连接和存储功能
    using (SqlConnection conn = new SqlConnection(connectionString))
    {
        conn.Open();
        SqlCommand cmd = new SqlCommand("INSERT INTO Barcodes (Content, Type, Image) VALUES (@content, @type, @image)", conn);
        cmd.Parameters.AddWithValue("@content", content);
        cmd.Parameters.AddWithValue("@type", barcodeType);
        cmd.Parameters.AddWithValue("@image", Convert.ToBase64String(imageBytes));
        cmd.ExecuteNonQuery();
    }

参考代码 C# Winform生成条形码源码下载,可保存本地和打印预览 www.youwenfan.com/contentcss/122435.html

技术要点

  1. ZXing.NET库:使用ZXing.NET库生成各种格式的条形码

  2. GDI+绘图:使用System.Drawing进行图像处理和打印

  3. 打印功能:使用PrintDocument和PrintPreviewDialog实现打印预览

  4. UI设计:使用TableLayoutPanel和FlowLayoutPanel创建响应式布局

  5. 错误处理:全面的异常处理确保程序稳定性

相关推荐
霑潇雨2 小时前
题解 | 深入分析各款产品年总销售额与竞品的年度对比
大数据·开发语言·数据库
2401_864959282 小时前
C++与Python混合编程实战
开发语言·c++·算法
左左右右左右摇晃2 小时前
Java并发——锁的状态演变
java·开发语言·笔记
2501_945424802 小时前
C++与硬件交互编程
开发语言·c++·算法
2301_818419012 小时前
C++中的表达式模板
开发语言·c++·算法
Roselind_Yi2 小时前
排查Visual C++堆损坏(HEAP CORRUPTION)错误:从报错到解决的完整复盘
java·开发语言·c++·spring·bug·学习方法·远程工作
蒙塔基的钢蛋儿2 小时前
告别内存泄露与空指针:用C#与.NET 10开启STM32H7高性能单片机开发新纪元
stm32·c#·.net
ZoeJoy82 小时前
C# Windows Forms 学生成绩管理器(StudentGradeManager)—— 方法重载、out、ref、params 参数示例
开发语言·c#
千百元2 小时前
网络图标显示不正常
开发语言·网络·php