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

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

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

    /// 
    /// 打印模式枚举
    /// 
    [Flags]
    public enum PrintMode
    {
        /// 
        /// 条形码Code128
        /// 
        Code128 = 1,
        /// 
        /// 二维码QRCode
        /// 
        QRCode = 2,
        /// 
        /// 纯文本
        /// 
        Text = 4,
        /// 
        /// 图片
        /// 
        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
    {
        /// 
        /// 打印配置json文件路径
        /// 
        private static string configJsonPath = AppDomain.CurrentDomain.BaseDirectory + "printConfig.json";

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

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

        /// 
        /// 生成需要打印的条码和文本等组合的图片
        /// 
        /// 
        /// 
        public static Bitmap GeneratePrintImage(List printConfigList)
        {
            List listbitmap = new List();
            //合并图像
            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;
        }

        /// 
        /// 生成条码图片【barcodeFormat一维条形码,二维码】
        /// 
        /// 打印条码对应的字符串
        /// 
        /// 
        /// 条码格式:CODE_128代表一维条码,QR_CODE代表二维码
        /// 
        /// 
        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;
        }

        /// 
        /// 生成字符串图片
        /// 
        /// 
        /// 
        /// 
        /// 
        /// 
        /// 
        /// 
        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;
        }

        /// 
        /// 调用打印机 打印条码和文本 图片
        /// 
        /// 打印机名称
        /// 
        /// 
        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
    {
        /// 
        /// Required designer variable.
        /// 
        private System.ComponentModel.IContainer components = null;

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

        #region Windows Form Designer generated code

        /// 
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// 
        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 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);
            }
        }

        /// 
        /// 检查输入的配置信息
        /// 
        /// 
        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 printConfigList = new List();
            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
    {
        /// 
        /// 必需的设计器变量。
        /// 
        private System.ComponentModel.IContainer components = null;

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

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

        /// 
        /// 设计器支持所需的方法 - 不要修改
        /// 使用代码编辑器修改此方法的内容。
        /// 
        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();
            }
        }

        /// 
        /// 显示推送消息
        /// 
        /// 
        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 printConfigList = CommonUtil.ReadPrintConfig();
            Task 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}");
        }

        /// 
        /// 在PictureBox上显示文本,需要在Paint重绘事件中
        /// 
        /// 
        /// 
        private void pictureBox1_Paint(object sender, PaintEventArgs e)
        {
            PictureBox pictureBox = sender as PictureBox;
            if (pictureBox == null || pictureBox.Tag == null) 
            {
                return;
            }
            List printConfigList = pictureBox.Tag as List;
            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);
                }
            }
        }
    }
}

七、程序运行如图:

打印内容配置 

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

显示图片与打印界面 使用GDI画图片生成合成图片并调用打印机进行图片打印_第2张图片

你可能感兴趣的:(GDI,C#,图片打印,GDI,图片打印,打印内容展示)