django做的电子商务网站/东莞网络优化排名
使用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_CODEwr.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,300int h = 200;//(int)(PaperHeight * 40);20pd.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);}#endregionprivate 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();}#endregionprivate 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);}}}}
}
七、程序运行如图:
打印内容配置
显示图片与打印界面 
相关文章:

使用GDI画图片生成合成图片并调用打印机进行图片打印
使用GDI画图片生成合成图片并调用打印机进行图片打印 新建窗体应用程序PrinterDemo,将默认的Form1重命名为FormPrinter,添加对 Newtonsoft.Json.dll用于读写Json字符串 zxing.dll,zxing.presentation.dll用于生成条形码,二维码…...

【PyQt】04-Designer
文章目录 前言一、初级 Designer1.1 拖拽设计界面1.2 搞定之后记得保存ui文件1.3 载入代码1.4 运行结果 二、登入界面代码效果展示账号密码错误时账号和密码正确 总结 前言 自然还是跟着王铭东老师学的 一、初级 Designer 1.1 拖拽设计界面 进度条是这个 1.2 搞定之后记得保…...

第4节、电机多段转动【51单片机+L298N步进电机系列教程】
↑↑↑点击上方【目录】,查看本系列全部文章 摘要:本节介绍用控制步进电机三个主要参数角度、速度、方向,实现简单的步进电机多段控制 一、目标功能 输入多个目标角度,以及每个角度对应的速度,实现步进电机的多段多速…...

算法学习——华为机考题库1(HJ1 - HJ10)
算法学习——华为机考题库1(HJ1 - HJ10) HJ1 字符串最后一个单词的长度 描述 计算字符串最后一个单词的长度,单词以空格隔开,字符串长度小于5000。(注:字符串末尾不以空格为结尾) 输入描述&…...

PSQL常用操作
目录 前言 准备工作 添加postgres用户 初始化数据库 启动服务 创建数据库 psql连接数据库 常规操作 数据库 schema相关 插件 其他 前言 老折腾,还是记录点啥吧...... 基于本地PG数据库(打包为绿色版本了),实操记录,版本pgsql12…...

C++ “万能血“ void*指针
本篇文章我们来介绍一下C “万能血” void指针 为什么说他万能呢? 原因:C void* 是一种特殊的指针类型,可用于存放任意对象的地址。在函数传参中也可以作为任何实参的形参 void型详细介绍 void* 是C中的一种特殊的指针类型,被称为"无类…...

微信小程序新手入门教程四:样式设计
WXSS (WeiXin Style Sheets)是一套样式语言,用于描述 WXML 的组件样式,决定了 WXML 的组件会怎么显示。 WXSS 具有 CSS 大部分特性,同时为了更适合开发微信小程序,WXSS 对 CSS 进行了扩充以及修改。与 CSS 相比,WXSS …...

类银河恶魔城学习记录1-6 Flip基本设置源代码 P33
Alex教程每一P的教程原代码加上我自己的理解初步理解写的注释,可供学习Alex教程的人参考 【Unity教程】从0编程制作类银河恶魔城游戏_哔哩哔哩_bilibili Player.cs using System.Collections; using System.Collections.Generic; using Unity.VisualScripting; us…...

【Git教程】(一)基本概念 ——工作流、分布式版本控制、版本库 ~
Git教程 基本概念 1️⃣ 为什么要用 Git2️⃣ 为什么要用工作流3️⃣ 分布式版本控制4️⃣ 版本库5️⃣ 简单的分支创建与合并🌾 总结 在本章中,将介绍一个分布式版本控制系统的设计思路,以及它与集中式版本控制系统的不同之处。除此之外&am…...

【QT】VS-code报错:LNK2019: 无法解析的外部符号
目录 0.环境 1.问题简述 2.分析报错原因 3.解决方法 1)set() 相关语句 2)target_link_libraries() 相关语句 4.参考 0.环境 windows11 、 vs-code 、 qt 、 c、编译器为vs2019-x86_amd64 1.问题简述 项目编译release版本时会报错:报错…...

基于 NXP S32K344 的汽车通用评估板方案
S32K3xx 系列是 NXP 基于 ARMCortex-M7 的汽车工业级 MCU,符合 ISO26262 ASIL-D 汽车功能安全等级,支持 ASIL B/D 安全应用,提供了一个可扩展的平台,具有下一代安全性、可扩展性、连接性和低功耗特性。适用于可能会在严酷环境下工…...

WebAssembly002 FFmpegWasmLocalServer项目
项目介绍 https://github.com/incubated-geek-cc/FFmpegWasmLocalServer.git可将音频或视频文件转换为其他可选的多媒体格式,并导出转码的结果 $ bash run.sh FFmpeg App is listening on port 3000!运行效果 相关依赖 Error: Cannot find module ‘express’ …...

瑞_力扣LeetCode_二叉树相关题
文章目录 说明题目 144. 二叉树的前序遍历题解 题目 94. 二叉树的中序遍历题解 题目 145. 二叉树的后序遍历题解 题目 105. 从前序与中序遍历序列构造二叉树题解 题目 106. 从中序与后序遍历序列构造二叉树题解 🙊 前言:本文章为瑞_系列专栏之《刷题》的…...

Axios设置token到请求头的三种方式
1、为什么要携带token? 用户登录时,后端会返回一个token,并且保存到浏览器的localstorage中,可以根据localstorage中的token判断用户是否登录,登录后才有权限访问相关的页面,所以当发送请求时,都要携带to…...

微服务介绍、使用 Nacos 实现远程调用以及 OpenFeign 的使用
1 微服务的概念 区别于单体项目 单体项目拆分成微服务项目的目标:高内聚、低耦合 拆分思路 纵向拆分:根据功能模块 横向拆分:抽取可复用模块 2 微服务拆分——远程调用 背景:微服务单一职责,每个服务只有自己的功能…...

Arthas使用教程—— 阿里开源线上监控诊断产品
文章目录 1 简介2背景3 图形界面工具 arthas 阿里开源3.1 :启动 arthas3.2 help :查看arthas所有命令3.3 查看 dashboard3.4 thread 列出当前进程所有线程占用CPU和内存情况3.5 jvm 查看该进程的各项参数 (类比 jinfo)3.6 通过 jad 来反编译 …...

mac电脑快捷指令实现拼图
mac访达,搜索输入‘快捷指令’,找到‘快捷指令’, 点击快捷指令,进入快捷指令中心,搜索‘拼图’ ,选中‘照片拼图’, 点击‘添加快捷指令’, 在‘所有快捷键指令’中可以看到添加的快…...

R语言入门笔记2.1
分支、循环与函数(1) 1.if语句 在R语言中,if语句用于根据条件执行不同的代码块。其基本语法如下: if (condition) {# 如果条件为真,执行这里的代码块 } else {# 如果条件为假,执行这里的代码块 } 其中&…...

补题:leetcode第382场周赛 3022. 给定操作次数内使剩余元素的或值最小
3022. 给定操作次数内使剩余元素的或值最小 - 力扣(LeetCode) 拆位 n个数进行或运算的结果最小,每次操作可以对相邻的两个数进行与运算,至多进行k次操作 n个数进行或运算,可以对每个数进行拆解,拆解成最小…...

创建型模式-单例模式:定义、实现及应用
目录 一、模式定义二、针对问题1.解决的问题2.解决方案3.举个例子4.设计模式适合场景5.实现方式6.优缺点7.与其他模式的关系 三、代码实现 一、模式定义 单例模式(Singleton Pattern)是一种创建型模式,用于限制某个类只能创建一个对象。它提…...

Prime(VulnHub)
Prime 文章目录 Prime1、nmap2、web渗透随便看看首页隐写查看目录爆破gobusterferoxbusterdirsearchdirb whatwebsearchsploit WordPress 5.2.2/dev/secret.txtFuzz_For_Webwfuzzimage.phpindex.php location.txtsecrettier360文件包含漏洞包含出password.txt尝试ssh登入尝试登…...

爬虫工作量由小到大的思维转变---<第四十二章 Scrapy Redis 重试机制(ip相关)>
前言: 之前讲过一篇关于scrapy的重试机制的文章,那个是针对当时那哥们的代码讲的,但是,发现后面还是有很多问题; 本章节就着scrapy的重试机制来讲一下!!! 正文: 首先,要清楚一个概念,在scrapy的中间件中,默认会有一个scrapy重试中间件;只要你在settings.py设置中写上: RETR…...

python日志管理配置
日志基础配置文件 日志回转查看:参考:https://blog.csdn.net/B11050729/article/details/132353220 项目使用注解实现 """ settings.py logging配置 """ import osroot_dir os.path.normpath(os.path.join(os.path.ab…...

2024.1.28力扣每日一题——水壶问题
2024.1.28 题目来源我的题解方法一 深度搜索(DFS)/广度搜索(BFS)方法二 数学 题目来源 力扣每日一题;题序:365 我的题解 方法一 深度搜索(DFS)/广度搜索(BFSÿ…...

orin nx 安装paddlespeech记录
nx配置: 模块 版本说明 CPU 8核 内存 16G Cuda版本 11.4 Opencv版本 4.5.4 Tensorrt版本 5.1 Cudnn版本 8.6.0.166 Deepstream版本 6.2 Python版本 3.8 算力 100T 安装paddlepaddle: 去飞桨官网下载jetpack版本的:下…...

系统架构设计师-21年-上午答案
系统架构设计师-21年-上午答案 更多软考资料 https://ruankao.blog.csdn.net/ 1 ~ 10 1 前趋图(Precedence Graph)是一个有向无环图,记为:→{(Pi,Pj)|Pi must complete before Pj may strat},假设系统中进程P{P1,P2,P3…...

外包干了10个月,技术退步明显...
先说一下自己的情况,大专生,18年通过校招进入武汉某软件公司,干了接近4年的功能测试,今年年初,感觉自己不能够在这样下去了,长时间呆在一个舒适的环境会让一个人堕落! 而我已经在一个企业干了四年的功能测…...

树莓派Pico入门
文章目录 1. Pico概述1.1 微处理器1.2 GPIO引脚1.3 MicroPython优点 2. 硬件准备2.1 购买清单2.2 软件需求 3. 安装MicroPython3.1下载固件3.2把固件安装到硬件里3.3补充 4. 第一个程序5. 验证运行效果6. 扩展应用 1. Pico概述 1.1 微处理器 ARM Cortex-M0 (频率 133MHz) 1.…...

yolov8使用旋转框自己做数据集检测
主要在数据集制作,训练的步骤和目标检测是一样的 1.数据集标注主要使用rolabelimg工具,这个工具不能在线安装 得下载源代码 然后运行 标注好数据保存会是一个xml文件 2.把xml文件转换成dota的xml文件,然后把dota的xml文件转换成dota的txt文件…...

docker重建镜像
DockerFile如下: FROM k8s-registry.qhtx.local/base/centos7-jdk8-haitong0704RUN yum -y update && yum install -y python3-devel && yum install -y python36 RUN mv /usr/bin/python /usr/bin/python_old RUN ln -s /usr/bin/python3 /usr/bi…...