使用GDI画图片生成合成图片并调用打印机进行图片打印

news2024/11/15 18:22:36

使用GDI画图片生成合成图片并调用打印机进行图片打印

新建窗体应用程序PrinterDemo,将默认的Form1重命名为FormPrinter,添加对

Newtonsoft.Json.dll用于读写Json字符串

zxing.dll,zxing.presentation.dll用于生成条形码,二维码

三个类库的引用。

一、新建打印配置类PrintConfig:

PrintConfig.cs源程序为:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PrinterDemo
{
    /// <summary>
    /// 打印某一个矩形Rectangle的配置,所有文本,图片,条码都认为是一个矩形区域,由(x,y,width,height)组成
    /// </summary>
    public class PrintConfig
    {
        /// <summary>
        /// 打印的具体内容,条形码,二维码对应的字符串内容
        /// </summary>
        public string PrintMessage { get; set; }
        /// <summary>
        /// 打印的左上角X坐标,以像素为单位
        /// </summary>
        public int X { set; get; }
        /// <summary>
        /// 打印的左上角Y坐标,以像素为单位
        /// </summary>
        public int Y { set; get; }
        /// <summary>
        /// 宽度,以像素为单位
        /// </summary>
        public int Width { set; get; }
        /// <summary>
        /// 高度,以像素为单位
        /// </summary>
        public int Height { set; get; }

        /// <summary>
        /// 打印模式枚举:条形码,二维码,纯文本,图片【显示枚举类型为字符串,而不是整数】
        /// </summary>
        [Newtonsoft.Json.JsonConverter(typeof(Newtonsoft.Json.Converters.StringEnumConverter))]
        public PrintMode PrintMode { set; get; }
        /// <summary>
        /// 字体大小
        /// </summary>
        public float FontSize { set; get; }
        /// <summary>
        /// 图片路径,当打印模式为图片PrintMode.Image时有效,其他默认为空
        /// </summary>
        public string ImagePath { get; set; }
    }

    /// <summary>
    /// 打印模式枚举
    /// </summary>
    [Flags]
    public enum PrintMode
    {
        /// <summary>
        /// 条形码Code128
        /// </summary>
        Code128 = 1,
        /// <summary>
        /// 二维码QRCode
        /// </summary>
        QRCode = 2,
        /// <summary>
        /// 纯文本
        /// </summary>
        Text = 4,
        /// <summary>
        /// 图片
        /// </summary>
        Image = 8
    }
}

二、新建打印配置读写类CommonUtil

CommonUtil.cs源程序如下:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PrinterDemo
{
    public class CommonUtil
    {
        /// <summary>
        /// 打印配置json文件路径
        /// </summary>
        private static string configJsonPath = AppDomain.CurrentDomain.BaseDirectory + "printConfig.json";

        /// <summary>
        /// 读取打印配置
        /// </summary>
        /// <returns></returns>
        public static List<PrintConfig> ReadPrintConfig() 
        {
            List<PrintConfig> printConfigList = new List<PrintConfig>();
            if (!File.Exists(configJsonPath))
            {
                return printConfigList;
            }
            string contents = File.ReadAllText(configJsonPath, Encoding.UTF8);
            printConfigList = Newtonsoft.Json.JsonConvert.DeserializeObject<List<PrintConfig>>(contents);
            return printConfigList;
        }

        /// <summary>
        /// 保存打印配置
        /// </summary>
        /// <param name="printConfigList"></param>
        /// <returns></returns>
        public static void SavePrintConfig(List<PrintConfig> printConfigList)
        {
            string contents = Newtonsoft.Json.JsonConvert.SerializeObject(printConfigList, Newtonsoft.Json.Formatting.Indented);
            File.WriteAllText(configJsonPath, contents, Encoding.UTF8);
        }
    }
}

三、对应的配置json文件 printConfig.json

 printConfig.json的测试内容是:

[
  {
    "PrintMessage": "Snake123456789ABCDEF",
    "X": 10,
    "Y": 10,
    "Width": 320,
    "Height": 80,
    "PrintMode": "Code128",
    "FontSize": 16.0,
    "ImagePath": ""
  },
  {
    "PrintMessage": "Snake123456789ABCDEF",
    "X": 80,
    "Y": 120,
    "Width": 180,
    "Height": 180,
    "PrintMode": "QRCode",
    "FontSize": 15.0,
    "ImagePath": ""
  },
  {
    "PrintMessage": "打印图片",
    "X": 370,
    "Y": 80,
    "Width": 120,
    "Height": 120,
    "PrintMode": "Image",
    "FontSize": 12.0,
    "ImagePath": "images\\test.png"
  },
  {
    "PrintMessage": "这是测试纯文本ABC8,需要在Paint事件中显示文字",
    "X": 10,
    "Y": 320,
    "Width": 400,
    "Height": 30,
    "PrintMode": "Text",
    "FontSize": 13.0,
    "ImagePath": ""
  }
]

四、新建关键类文件PrinterUtil,用于合成图片【文本,条形码均为图片】 

PrinterUtil.cs源程序如下:

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Printing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ZXing;
using ZXing.QrCode;

namespace PrinterDemo
{
    /// <summary>
    /// 调用打印机打印图片和文字
    /// </summary>
    public class PrinterUtil
    {
        /// <summary>
        /// 使用打印机打印由文本、二维码等合成的图片
        /// 自动生成图片后打印
        /// 斯内科 20240206
        /// </summary>
        /// <param name="printConfigList">打印设置列表</param>
        /// <param name="printerName">打印机名称</param>
        /// <returns></returns>
        public static bool PrintCompositePicture(List<PrintConfig> printConfigList, string printerName)
        {    
            try
            {
                Bitmap printImg = GeneratePrintImage(printConfigList);
                return PrintImage(printerName, printImg);
            }
            catch (Exception ex)
            {
                System.Windows.Forms.MessageBox.Show($"打印异常:{ex.Message}", "出错");
                return false;
            }
        }

        /// <summary>
        /// 生成需要打印的条码和文本等组合的图片
        /// </summary>
        /// <param name="listPrintset"></param>
        /// <returns></returns>
        public static Bitmap GeneratePrintImage(List<PrintConfig> printConfigList)
        {
            List<Bitmap> listbitmap = new List<Bitmap>();
            //合并图像
            for (int i = 0; i < printConfigList.Count; i++)
            {
                Bitmap bitmap = new Bitmap(10, 10);
                switch (printConfigList[i].PrintMode)
                {
                    case PrintMode.Code128:
                        bitmap = GenerateBarcodeImage(printConfigList[i].PrintMessage, printConfigList[i].Width, printConfigList[i].Height, BarcodeFormat.CODE_128, 1);
                        break;
                    case PrintMode.QRCode:
                        bitmap = GenerateBarcodeImage(printConfigList[i].PrintMessage, printConfigList[i].Width, printConfigList[i].Height, BarcodeFormat.QR_CODE, 1);
                        break;
                    case PrintMode.Text:
                        bitmap = GenerateStringImage(printConfigList[i].PrintMessage, printConfigList[i].Width, printConfigList[i].Height, printConfigList[i].X, printConfigList[i].Y, printConfigList[i].FontSize);
                        break;
                    case PrintMode.Image:
                        bitmap = (Bitmap)Image.FromFile(AppDomain.CurrentDomain.BaseDirectory + printConfigList[i].ImagePath);
                        break;
                }
                listbitmap.Add(bitmap);
            }
            //创建要显示的图片对象,根据参数的个数设置宽度
            Bitmap backgroudImg = new Bitmap(600, 400);
            Graphics g = Graphics.FromImage(backgroudImg);
            //清除画布,背景设置为白色
            g.Clear(System.Drawing.Color.White);
            //设置为 抗锯齿 
            g.SmoothingMode = SmoothingMode.AntiAlias;
            g.SmoothingMode = SmoothingMode.HighQuality;
            g.CompositingQuality = CompositingQuality.HighQuality;
            g.InterpolationMode = InterpolationMode.HighQualityBicubic;
            for (int i = 0; i < printConfigList.Count; i++)
            {
                g.DrawImage(listbitmap[i], printConfigList[i].X, printConfigList[i].Y, listbitmap[i].Width, listbitmap[i].Height);
            }
            return backgroudImg;
        }

        /// <summary>
        /// 生成条码图片【barcodeFormat一维条形码,二维码】
        /// </summary>
        /// <param name="codeContent">打印条码对应的字符串</param>
        /// <param name="width"></param>
        /// <param name="height"></param>
        /// <param name="barcodeFormat">条码格式:CODE_128代表一维条码,QR_CODE代表二维码</param>
        /// <param name="margin"></param>
        /// <returns></returns>
        public static Bitmap GenerateBarcodeImage(string codeContent, int width, int height, BarcodeFormat barcodeFormat, int margin = 1)
        {
            // 1.设置QR二维码的规格
            QrCodeEncodingOptions qrEncodeOption = new QrCodeEncodingOptions();
            qrEncodeOption.DisableECI = true;
            qrEncodeOption.CharacterSet = "UTF-8"; // 设置编码格式,否则读取'中文'乱码
            qrEncodeOption.Height = height;
            qrEncodeOption.Width = width;
            qrEncodeOption.Margin = margin; // 设置周围空白边距
            qrEncodeOption.PureBarcode = true;
            // 2.生成条形码图片
            BarcodeWriter wr = new BarcodeWriter();
            wr.Format = barcodeFormat; // 二维码 BarcodeFormat.QR_CODE
            wr.Options = qrEncodeOption;
            Bitmap img = wr.Write(codeContent);
            return img;
        }

        /// <summary>
        /// 生成字符串图片
        /// </summary>
        /// <param name="codeContent"></param>
        /// <param name="width"></param>
        /// <param name="height"></param>
        /// <param name="x"></param>
        /// <param name="y"></param>
        /// <param name="emSize"></param>
        /// <returns></returns>
        public static Bitmap GenerateStringImage(string codeContent, int width, int height, int x, int y, float emSize = 9f)
        {
            Bitmap imageTxt = new Bitmap(width, height);
            Graphics graphics = Graphics.FromImage(imageTxt);
            Font font = new Font("黑体", emSize, FontStyle.Regular);
            Rectangle destRect = new Rectangle(x, y, width, height);
            LinearGradientBrush brush = new LinearGradientBrush(destRect, Color.Black, Color.Black, 0, true);
            RectangleF rectangleF = new RectangleF(x, y, width, height);
            graphics.DrawString(codeContent, font, brush, rectangleF);
            return imageTxt;
        }

        /// <summary>
        /// 调用打印机 打印条码和文本 图片
        /// </summary>
        /// <param name="printerName">打印机名称</param>
        /// <param name="image"></param>
        /// <returns></returns>
        private static bool PrintImage(string printerName, Bitmap image)
        {
            if (image != null)
            {
                PrintDocument pd = new PrintDocument();
                //打印事件设置
                pd.PrintPage += new PrintPageEventHandler((w, e) =>
                {
                    int x = 0;
                    int y = 5;
                    int width = image.Width;
                    int height = image.Height;
                    Rectangle destRect = new Rectangle(x, y, width + 200, height + 200);
                    e.Graphics.DrawImage(image, destRect, 2, 2, image.Width, image.Height, System.Drawing.GraphicsUnit.Millimeter);
                });

                PrinterSettings printerSettings = new PrinterSettings
                {
                    PrinterName = printerName
                };
                pd.PrinterSettings = printerSettings;
                pd.PrintController = new StandardPrintController();//隐藏打印时屏幕左上角会弹出的指示窗
                try
                {
                    //设置纸张高度和大小
                    int w = 800;//(int)(PaperWidth * 40);原600,300
                    int h = 200;//(int)(PaperHeight * 40);20
                    pd.DefaultPageSettings.PaperSize = new PaperSize("custom", w, h);
                    pd.Print();
                    return true;
                }
                catch (Exception ex)
                {
                    pd.PrintController.OnEndPrint(pd, new PrintEventArgs());
                    System.Windows.Forms.MessageBox.Show($"【PrintImage】打印出错:{ex.Message}", "使用打印机打印");
                    return false;
                }
            }
            else
            {
                return false;
            }
        }
    }
}

五、新建打印内容配置窗体FormPrintSetting

窗体设计器源程序如下: 

FormPrintSetting.Designer.cs文件


namespace PrinterDemo
{
    partial class FormPrintSetting
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.btnSave = new System.Windows.Forms.Button();
            this.dgvConfig = new System.Windows.Forms.DataGridView();
            this.btnRead = new System.Windows.Forms.Button();
            this.dgvcPrintMessage = new System.Windows.Forms.DataGridViewTextBoxColumn();
            this.dgvcX = new System.Windows.Forms.DataGridViewTextBoxColumn();
            this.dgvcY = new System.Windows.Forms.DataGridViewTextBoxColumn();
            this.dgvcWidth = new System.Windows.Forms.DataGridViewTextBoxColumn();
            this.dgvcHeight = new System.Windows.Forms.DataGridViewTextBoxColumn();
            this.dgvcPrintMode = new System.Windows.Forms.DataGridViewComboBoxColumn();
            this.dgvcFontSize = new System.Windows.Forms.DataGridViewTextBoxColumn();
            this.dgvcImagePath = new System.Windows.Forms.DataGridViewTextBoxColumn();
            ((System.ComponentModel.ISupportInitialize)(this.dgvConfig)).BeginInit();
            this.SuspendLayout();
            // 
            // btnSave
            // 
            this.btnSave.Font = new System.Drawing.Font("宋体", 16F);
            this.btnSave.Location = new System.Drawing.Point(238, 3);
            this.btnSave.Name = "btnSave";
            this.btnSave.Size = new System.Drawing.Size(113, 32);
            this.btnSave.TabIndex = 0;
            this.btnSave.Text = "保存配置";
            this.btnSave.UseVisualStyleBackColor = true;
            this.btnSave.Click += new System.EventHandler(this.btnSave_Click);
            // 
            // dgvConfig
            // 
            this.dgvConfig.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
            this.dgvConfig.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
            this.dgvcPrintMessage,
            this.dgvcX,
            this.dgvcY,
            this.dgvcWidth,
            this.dgvcHeight,
            this.dgvcPrintMode,
            this.dgvcFontSize,
            this.dgvcImagePath});
            this.dgvConfig.Location = new System.Drawing.Point(3, 41);
            this.dgvConfig.Name = "dgvConfig";
            this.dgvConfig.RowTemplate.Height = 23;
            this.dgvConfig.Size = new System.Drawing.Size(1085, 397);
            this.dgvConfig.TabIndex = 1;
            this.dgvConfig.DataError += new System.Windows.Forms.DataGridViewDataErrorEventHandler(this.dgvConfig_DataError);
            // 
            // btnRead
            // 
            this.btnRead.Font = new System.Drawing.Font("宋体", 16F);
            this.btnRead.Location = new System.Drawing.Point(93, 3);
            this.btnRead.Name = "btnRead";
            this.btnRead.Size = new System.Drawing.Size(113, 32);
            this.btnRead.TabIndex = 2;
            this.btnRead.Text = "刷新配置";
            this.btnRead.UseVisualStyleBackColor = true;
            this.btnRead.Click += new System.EventHandler(this.btnRead_Click);
            // 
            // dgvcPrintMessage
            // 
            this.dgvcPrintMessage.HeaderText = "打印内容";
            this.dgvcPrintMessage.Name = "dgvcPrintMessage";
            this.dgvcPrintMessage.Width = 180;
            // 
            // dgvcX
            // 
            this.dgvcX.HeaderText = "X坐标";
            this.dgvcX.Name = "dgvcX";
            this.dgvcX.Width = 120;
            // 
            // dgvcY
            // 
            this.dgvcY.HeaderText = "Y坐标";
            this.dgvcY.Name = "dgvcY";
            this.dgvcY.Width = 120;
            // 
            // dgvcWidth
            // 
            this.dgvcWidth.HeaderText = "宽度";
            this.dgvcWidth.Name = "dgvcWidth";
            this.dgvcWidth.Width = 120;
            // 
            // dgvcHeight
            // 
            this.dgvcHeight.HeaderText = "高度";
            this.dgvcHeight.Name = "dgvcHeight";
            this.dgvcHeight.Width = 120;
            // 
            // dgvcPrintMode
            // 
            this.dgvcPrintMode.HeaderText = "打印模式枚举";
            this.dgvcPrintMode.Items.AddRange(new object[] {
            "Code128",
            "QRCode",
            "Text",
            "Image"});
            this.dgvcPrintMode.Name = "dgvcPrintMode";
            // 
            // dgvcFontSize
            // 
            this.dgvcFontSize.HeaderText = "字体大小";
            this.dgvcFontSize.Name = "dgvcFontSize";
            // 
            // dgvcImagePath
            // 
            this.dgvcImagePath.HeaderText = "图片路径";
            this.dgvcImagePath.Name = "dgvcImagePath";
            this.dgvcImagePath.Width = 180;
            // 
            // FormPrintSetting
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(1093, 450);
            this.Controls.Add(this.btnRead);
            this.Controls.Add(this.dgvConfig);
            this.Controls.Add(this.btnSave);
            this.Name = "FormPrintSetting";
            this.Text = "打印内容配置";
            this.Load += new System.EventHandler(this.FormPrintSetting_Load);
            ((System.ComponentModel.ISupportInitialize)(this.dgvConfig)).EndInit();
            this.ResumeLayout(false);

        }

        #endregion

        private System.Windows.Forms.Button btnSave;
        private System.Windows.Forms.DataGridView dgvConfig;
        private System.Windows.Forms.Button btnRead;
        private System.Windows.Forms.DataGridViewTextBoxColumn dgvcPrintMessage;
        private System.Windows.Forms.DataGridViewTextBoxColumn dgvcX;
        private System.Windows.Forms.DataGridViewTextBoxColumn dgvcY;
        private System.Windows.Forms.DataGridViewTextBoxColumn dgvcWidth;
        private System.Windows.Forms.DataGridViewTextBoxColumn dgvcHeight;
        private System.Windows.Forms.DataGridViewComboBoxColumn dgvcPrintMode;
        private System.Windows.Forms.DataGridViewTextBoxColumn dgvcFontSize;
        private System.Windows.Forms.DataGridViewTextBoxColumn dgvcImagePath;
    }
}

FormPrintSetting.cs文件

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace PrinterDemo
{
    public partial class FormPrintSetting : Form
    {
        
        public FormPrintSetting()
        {
            InitializeComponent();
        }

        private void FormPrintSetting_Load(object sender, EventArgs e)
        {
            btnRead_Click(null, null);
        }

        private void btnRead_Click(object sender, EventArgs e)
        {
            dgvConfig.Rows.Clear();
            List<PrintConfig> printConfigList = CommonUtil.ReadPrintConfig();
            for (int i = 0; i < printConfigList.Count; i++)
            {
                dgvConfig.Rows.Add(printConfigList[i].PrintMessage, printConfigList[i].X, printConfigList[i].Y, printConfigList[i].Width, printConfigList[i].Height,
                    printConfigList[i].PrintMode.ToString(), printConfigList[i].FontSize, printConfigList[i].ImagePath);
            }
        }

        /// <summary>
        /// 检查输入的配置信息
        /// </summary>
        /// <returns></returns>
        private bool CheckInput() 
        {
            int validCount = 0;
            for (int i = 0; i < dgvConfig.Rows.Count; i++)
            {
                string strPrintMessage = Convert.ToString(dgvConfig["dgvcPrintMessage", i].Value);
                string strX = Convert.ToString(dgvConfig["dgvcX", i].Value);
                string strY = Convert.ToString(dgvConfig["dgvcY", i].Value);
                string strWidth = Convert.ToString(dgvConfig["dgvcWidth", i].Value);
                string strHeight = Convert.ToString(dgvConfig["dgvcHeight", i].Value);
                string strPrintMode = Convert.ToString(dgvConfig["dgvcPrintMode", i].Value);
                string strFontSize = Convert.ToString(dgvConfig["dgvcFontSize", i].Value);
                string strImagePath = Convert.ToString(dgvConfig["dgvcImagePath", i].Value);
                if (string.IsNullOrWhiteSpace(strPrintMessage)) 
                {
                    continue;
                }
                int X;
                int Y;
                int Width;
                int Height;
                float FontSize;
                if (!int.TryParse(strX, out X)) 
                {
                    dgvConfig["dgvcX", i].Selected = true;
                    MessageBox.Show("X坐标必须为整数", "出错");
                    return false;
                }
                if (!int.TryParse(strY, out Y))
                {
                    dgvConfig["dgvcY", i].Selected = true;
                    MessageBox.Show("Y坐标必须为整数", "出错");
                    return false;
                }
                if (!int.TryParse(strWidth, out Width) || Width < 0)
                {
                    dgvConfig["dgvcWidth", i].Selected = true;
                    MessageBox.Show("宽度必须为正整数", "出错");
                    return false;
                }
                if (!int.TryParse(strHeight, out Height) || Height < 0)
                {
                    dgvConfig["dgvcHeight", i].Selected = true;
                    MessageBox.Show("高度必须为正整数", "出错");
                    return false;
                }
                if (!float.TryParse(strFontSize, out FontSize) || FontSize < 0)
                {
                    dgvConfig["dgvcFontSize", i].Selected = true;
                    MessageBox.Show("字体大小必须为正实数", "出错");
                    return false;
                }
                if (string.IsNullOrWhiteSpace(strPrintMode)) 
                {
                    dgvConfig["dgvcPrintMode", i].Selected = true;
                    MessageBox.Show("请选择打印模式", "出错");
                    return false;
                }
                if (Enum.TryParse(strPrintMode, out PrintMode printMode) && printMode == PrintMode.Image && string.IsNullOrWhiteSpace(strImagePath)) 
                {
                    dgvConfig["dgvcImagePath", i].Selected = true;
                    MessageBox.Show("已选择打印模式为Image,必须配置图片路径", "出错");
                    return false;
                }
                validCount++;
            }
            if (validCount == 0) 
            {
                MessageBox.Show("没有设置任何打印配置", "出错");
                return false;
            }
            return true;
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            if (!CheckInput()) 
            {
                return;
            }
            List<PrintConfig> printConfigList = new List<PrintConfig>();
            for (int i = 0; i < dgvConfig.Rows.Count; i++)
            {
                string strPrintMessage = Convert.ToString(dgvConfig["dgvcPrintMessage", i].Value);
                string strX = Convert.ToString(dgvConfig["dgvcX", i].Value);
                string strY = Convert.ToString(dgvConfig["dgvcY", i].Value);
                string strWidth = Convert.ToString(dgvConfig["dgvcWidth", i].Value);
                string strHeight = Convert.ToString(dgvConfig["dgvcHeight", i].Value);
                string strPrintMode = Convert.ToString(dgvConfig["dgvcPrintMode", i].Value);
                string strFontSize = Convert.ToString(dgvConfig["dgvcFontSize", i].Value);
                string strImagePath = Convert.ToString(dgvConfig["dgvcImagePath", i].Value);
                if (string.IsNullOrWhiteSpace(strPrintMessage))
                {
                    continue;
                }
                printConfigList.Add(new PrintConfig()
                {
                    PrintMessage = strPrintMessage.Trim(),
                    X = int.Parse(strX),
                    Y = int.Parse(strY),
                    Width = int.Parse(strWidth),
                    Height = int.Parse(strHeight),
                    PrintMode = (PrintMode)Enum.Parse(typeof(PrintMode), strPrintMode),
                    FontSize = float.Parse(strFontSize),
                    ImagePath = strImagePath.Trim()
                });
            }
            CommonUtil.SavePrintConfig(printConfigList);
            //重新刷新
            btnRead_Click(null, null);
            MessageBox.Show("保存打印配置信息成功", "提示");
        }

        private void dgvConfig_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {
            MessageBox.Show($"出错的列索引【{e.ColumnIndex}】,行索引【{ e.RowIndex}】,{e.Exception.Message}");
        }
    }
}

六、窗体 FormPrinter设计器与源程序如下:

FormPrinter.Designer.cs文件


namespace PrinterDemo
{
    partial class FormPrinter
    {
        /// <summary>
        /// 必需的设计器变量。
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// 清理所有正在使用的资源。
        /// </summary>
        /// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows 窗体设计器生成的代码

        /// <summary>
        /// 设计器支持所需的方法 - 不要修改
        /// 使用代码编辑器修改此方法的内容。
        /// </summary>
        private void InitializeComponent()
        {
            this.lblCode = new System.Windows.Forms.Label();
            this.pictureBox1 = new System.Windows.Forms.PictureBox();
            this.btnConfig = new System.Windows.Forms.Button();
            this.btnManualPrint = new System.Windows.Forms.Button();
            this.rtxtMessage = new System.Windows.Forms.RichTextBox();
            ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit();
            this.SuspendLayout();
            // 
            // lblCode
            // 
            this.lblCode.AutoSize = true;
            this.lblCode.Font = new System.Drawing.Font("宋体", 12F);
            this.lblCode.Location = new System.Drawing.Point(12, 429);
            this.lblCode.Name = "lblCode";
            this.lblCode.Size = new System.Drawing.Size(152, 16);
            this.lblCode.TabIndex = 27;
            this.lblCode.Text = "NG1234567890ABCDEF";
            // 
            // pictureBox1
            // 
            this.pictureBox1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
            this.pictureBox1.Location = new System.Drawing.Point(3, 9);
            this.pictureBox1.Name = "pictureBox1";
            this.pictureBox1.Size = new System.Drawing.Size(600, 400);
            this.pictureBox1.TabIndex = 26;
            this.pictureBox1.TabStop = false;
            this.pictureBox1.Paint += new System.Windows.Forms.PaintEventHandler(this.pictureBox1_Paint);
            // 
            // btnConfig
            // 
            this.btnConfig.Font = new System.Drawing.Font("宋体", 16F);
            this.btnConfig.Location = new System.Drawing.Point(125, 524);
            this.btnConfig.Name = "btnConfig";
            this.btnConfig.Size = new System.Drawing.Size(171, 41);
            this.btnConfig.TabIndex = 70;
            this.btnConfig.Text = "打印模板配置";
            this.btnConfig.UseVisualStyleBackColor = true;
            this.btnConfig.Click += new System.EventHandler(this.btnConfig_Click);
            // 
            // btnManualPrint
            // 
            this.btnManualPrint.Font = new System.Drawing.Font("宋体", 16F);
            this.btnManualPrint.Location = new System.Drawing.Point(95, 460);
            this.btnManualPrint.Name = "btnManualPrint";
            this.btnManualPrint.Size = new System.Drawing.Size(306, 52);
            this.btnManualPrint.TabIndex = 69;
            this.btnManualPrint.Text = "根据打印模板配置进行打印";
            this.btnManualPrint.UseVisualStyleBackColor = true;
            this.btnManualPrint.Click += new System.EventHandler(this.btnManualPrint_Click);
            // 
            // rtxtMessage
            // 
            this.rtxtMessage.Location = new System.Drawing.Point(620, 9);
            this.rtxtMessage.Name = "rtxtMessage";
            this.rtxtMessage.ReadOnly = true;
            this.rtxtMessage.Size = new System.Drawing.Size(553, 559);
            this.rtxtMessage.TabIndex = 71;
            this.rtxtMessage.Text = "";
            // 
            // FormPrinter
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(1185, 580);
            this.Controls.Add(this.rtxtMessage);
            this.Controls.Add(this.btnConfig);
            this.Controls.Add(this.btnManualPrint);
            this.Controls.Add(this.lblCode);
            this.Controls.Add(this.pictureBox1);
            this.Name = "FormPrinter";
            this.Text = "条码打印示教";
            ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit();
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private System.Windows.Forms.Label lblCode;
        private System.Windows.Forms.PictureBox pictureBox1;
        private System.Windows.Forms.Button btnConfig;
        private System.Windows.Forms.Button btnManualPrint;
        private System.Windows.Forms.RichTextBox rtxtMessage;
    }
}

FormPrinter.cs文件

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace PrinterDemo
{
    public partial class FormPrinter : Form
    {
        public FormPrinter()
        {
            InitializeComponent();
        }

        FormPrintSetting formPrintSetting;
        private void btnConfig_Click(object sender, EventArgs e)
        {
            if (formPrintSetting == null || formPrintSetting.IsDisposed)
            {
                formPrintSetting = new FormPrintSetting();
                formPrintSetting.Show();
            }
            else
            {
                formPrintSetting.Activate();
            }
        }

        /// <summary>
        /// 显示推送消息
        /// </summary>
        /// <param name="msg"></param>
        private void DisplayMessage(string msg)
        {
            this.BeginInvoke(new Action(() =>
            {
                if (rtxtMessage.TextLength > 20480)
                {
                    rtxtMessage.Clear();
                }
                rtxtMessage.AppendText($"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")}->{msg}\n");
                rtxtMessage.ScrollToCaret();
            }));
        }

        private async void btnManualPrint_Click(object sender, EventArgs e)
        {
            List<PrintConfig> printConfigList = CommonUtil.ReadPrintConfig();
            Task<int> task = Task.Run(() =>
            {
                pictureBox1.Tag = printConfigList;//为标签Tag赋值,用于PictureBox对文字的显示处理【Paint重绘事件】
                DisplayMessage($"即将打印【{printConfigList.Count}】个内容,该内容描述集合为:\n{string.Join(",\n", printConfigList.Select(x => x.PrintMessage))}");
                int okCount = 0;
                try
                {
                    string printContents = string.Join(",", printConfigList.Select(x => x.PrintMessage));
                    //开始打印
                    this.BeginInvoke(new Action(() =>
                    {
                        lblCode.Text = printContents;
                        pictureBox1.SizeMode = PictureBoxSizeMode.CenterImage;
                        Bitmap bitmap = PrinterUtil.GeneratePrintImage(printConfigList);
                        pictureBox1.Image = bitmap;
                    }));
                    bool rst = PrinterUtil.PrintCompositePicture(printConfigList, printerName: "Zebra 8848T");
                    DisplayMessage($"条码打印{(rst ? "成功" : "失败")}.打印内容:{printContents}");
                    if (rst)
                    {
                        okCount++;
                    }
                }
                catch (Exception ex)
                {
                    DisplayMessage($"条码打印出错,原因:{ex.Message}");
                }
                return okCount;
            });
            await task;
            DisplayMessage($"条码打印已完成,打印成功条码个数:{task.Result}");
        }

        /// <summary>
        /// 在PictureBox上显示文本,需要在Paint重绘事件中
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void pictureBox1_Paint(object sender, PaintEventArgs e)
        {
            PictureBox pictureBox = sender as PictureBox;
            if (pictureBox == null || pictureBox.Tag == null) 
            {
                return;
            }
            List<PrintConfig> printConfigList = pictureBox.Tag as List<PrintConfig>;
            for (int i = 0; printConfigList != null && i < printConfigList.Count; i++)
            {
                //因PictureBox不能直接显示文本,需要在Paint事件中独自处理文字显示
                if (printConfigList[i].PrintMode == PrintMode.Text) 
                {
                    Graphics graphics = e.Graphics;
                    Font font = new Font("黑体", printConfigList[i].FontSize, FontStyle.Regular);
                    Rectangle destRect = new Rectangle(printConfigList[i].X, printConfigList[i].Y, printConfigList[i].Width, printConfigList[i].Height);
                    System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.LinearGradientBrush(destRect, Color.Black, Color.Black, 0, true);
                    RectangleF rectangleF = new RectangleF(printConfigList[i].X, printConfigList[i].Y, printConfigList[i].Width, printConfigList[i].Height);
                    graphics.DrawString(printConfigList[i].PrintMessage, font, brush, rectangleF);
                }
            }
        }
    }
}

七、程序运行如图:

打印内容配置 

显示图片与打印界面 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1440551.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

STM32内存管理

一.什么是内存管理 内存管理是计算机系统中的一个重要组成部分&#xff0c;它负责管理计算机的内存资源。内存管理的主要目标是有效地分配、使用和释放内存&#xff0c;以满足程序的运行需求。 内存是计算机用于存储程序和数据的地方&#xff0c;它由一系列内存单元组成&#…

Java后端技术助力,党员学习平台更稳定

✍✍计算机编程指导师 ⭐⭐个人介绍&#xff1a;自己非常喜欢研究技术问题&#xff01;专业做Java、Python、微信小程序、安卓、大数据、爬虫、Golang、大屏等实战项目。 ⛽⛽实战项目&#xff1a;有源码或者技术上的问题欢迎在评论区一起讨论交流&#xff01; ⚡⚡ Java实战 |…

mysql按周统计数据简述

概述 业务中经常会遇到按年月日统计的场景&#xff1b; 但有时会有按周统计的情况&#xff1b; 我一般是用3种方法去解决&#xff1a; 利用mysql的weekday函数。计算出当前日期是一周中的第几天&#xff0c;然后当前日期 - 这个数值&#xff0c;就可以得到当前周的周一的日期…

停车场|基于Springboot的停车场管理系统设计与实现(源码+数据库+文档)

停车场管理系统目录 目录 基于Springboot的停车场管理系统设计与实现 一、前言 二、系统功能设计 三、系统实现 1、管理员功能实现 &#xff08;1&#xff09;车位管理 &#xff08;2&#xff09;车位预订管理 &#xff08;3&#xff09;公告管理 &#xff08;4&#…

分布式系统架构介绍

1、为什么需要分布式架构&#xff1f; 增大系统容量&#xff1a;单台系统的性能瓶颈&#xff0c;多台机器才能应对大规模的应用场景&#xff0c;所以就需要我们的应用支撑平台具备分布式架构。 加强系统的可用&#xff1a;为了满足业务的SLA要求&#xff0c;需要通过分布式架构…

汇编笔记 01

小蒟蒻的汇编自学笔记&#xff0c;如有错误&#xff0c;望不吝赐教 文章目录 笔记编辑器&#xff0c;启动&#xff01;debug功能CS & IPmovaddsub汇编语言寄存器的英文全称中英对照表muldivandor 笔记 编辑器&#xff0c;启动&#xff01; 进入 debug 模式 debug功能 …

C语言:分支与循环

创造不易&#xff0c;友友们给个三连吧&#xff01;&#xff01; C语⾔是结构化的程序设计语⾔&#xff0c;这⾥的结构指的是顺序结构、选择结构、循环结构&#xff0c;C语⾔是能够实 现这三种结构的&#xff0c;其实我们如果仔细分析&#xff0c;我们⽇常所⻅的事情都可以拆分…

SQL拆分字段内容(含分隔符)

问题描述&#xff1a; 在做数据迁移的过程中&#xff0c;我们希望对表中的某个字段根据分隔符进行拆分&#xff0c;得到多条数据&#xff0c;原代码有点意思&#xff0c;因此记录一下。 我们假设某条数据如下&#xff1a; IDSTRS1公司名称不能小于四个字&#xff0c;行业类别…

春运也要“信号升格”:中兴通讯助运营商打造高铁精品网

一年一度的春运&#xff0c;承载了游子的思乡情。据官方预计&#xff0c;今年春运跨区域人员流动量将达到90亿人次&#xff0c;创下历史新高&#xff0c;铁路、公路、水路、民航等营业性客运量全面回升&#xff0c;其中铁路预计发送旅客4.8亿人次&#xff0c;日均1200万人次&am…

网络设备如何巡检?这些命令必不可少

一、查看交换机的端口使用情况&#xff1a; dis interface brief查看交换机的哪个端口是万兆端口&#xff0c;以及端口状态&#xff0c;那个端口在使用。 如下图&#xff0c;使用这个命令。 其中端口0/0/1与端口0/0/2处于使用中。其它接口没有使用&#xff1b;如果在实际项目…

[Python进阶] 制作动态二维码

11.1 制作动态二维码 二维码&#xff08;QR code&#xff09;是一种二维条形码&#xff08;bar code&#xff09;&#xff0c;它的起源可以追溯到20世纪90年代初。当时&#xff0c;日本的汽车工业开始使用一种被称为QR码的二维条码来追踪汽车零部件的信息。 QR码是Quick Respo…

机器人学、机器视觉与控制 上机笔记(第一版译文版 2.1章节)

机器人学、机器视觉与控制 上机笔记&#xff08;第一版译文版 2.1章节&#xff09; 1、前言2、本篇内容3、代码记录3.1、新建se23.2、生成坐标系3.3、将T1表示的变换绘制3.4、完整绘制代码3.5、获取点*在坐标系1下的表示3.6、相对坐标获取完整代码 4、结语 1、前言 工作需要&a…

JRebel激活-nginx版本

nginx转发流量&#xff08;代替其他网上说的那个工具&#xff09; proxy_pass http://idea.lanyus.com; 工具激活 填写内容说明&#xff1a; 第一行的激活网址是&#xff1a;http://127.0.0.1:8888/ 正确的GUID。GUID 可以通过专门的网站来生成&#xff08;点击打开&#…

问题:创业者在组建创业团队时,在个人特征和动机方面更应该注重创业者的( ) #知识分享#微信#媒体

问题&#xff1a;创业者在组建创业团队时&#xff0c;在个人特征和动机方面更应该注重创业者的&#xff08; &#xff09; 参考答案如图所示

C++分支语句

个人主页&#xff1a;PingdiGuo_guo 收录专栏&#xff1a;C干货专栏 大家新年快乐&#xff0c;今天&#xff0c;我们来了解一下分支语句。 文章目录 1.什么是分支语句 1.if语句 基本形式 用法说明 练习 2.if-else语句 基本形式 用法说明 练习 3.switch语句 基本形式…

推荐研发度量思码逸的研发度量工具及视频教学

目前国内做研发度量中&#xff0c;思码逸的研发度量工具的确做的不错&#xff0c;网址是&#xff1a;思码逸-专业的软件研发效能度量分析平台 看到一个不错的介绍视频&#xff1a;《让数据说话&#xff0c;高效盘点企业研发效能》&#xff0c; 地址是&#xff1a;视频课程&…

bert+np.memap+faiss文本相似度匹配 topN

目录 任务 代码 结果说明 任务 使用 bert-base-chinese 预训练模型将文本数据向量化后&#xff0c;使用 np.memap 进行保存&#xff0c;再使用 faiss 进行相似度匹配出每个文本与它最相似的 topN 此篇文章使用了地址数据&#xff0c;目的是为了跑通这个流程&#xff0c;数…

Mac使用AccessClient打开Linux堡垒机跳转闪退问题解决

登录公司的服务器需要使用到堡垒机&#xff0c;但是mac使用AccessClient登录会出现问题 最基础的AccessClient配置 AccessClient启动需要设置目录权限&#xff0c;可以直接设置为 权限 777 chmod 777 /Applications/AccessClient.app注: 如果不是这个路径,可以打开终端,将访达中…

uniapp设置不显示顶部返回按钮

一、pages文件中&#xff0c;在相应的页面中设置 "titleNView": {"autoBackButton": false} 二、对应的页面文件设置隐藏元素 document.querySelector(.uni-page-head-hd).style.display none

Tomcat组件架构与数据流

一、背景与简介 Tomcat我们都知道是一个开源的、实现了大部分Java EE、Servlet、JSP规范的Servlet容器, 允许我们将实现了Serlvet接口的Web程序war包进行部署运行。 但是你有对Tomcat做过细致的学习么? 我相信大部分同学和我一样&#xff0c;之前也是只会进行简单使用&#x…