在工业上位机开发环境中,经常会用到自定义批量打印标签的情况,比如合格证、生产单等,这是实现自动化的一个重要步骤,在这里我介绍一下我的具体实现方式。
一、设计模板
在设置模板前需要用的标签设计工具,在这里我推荐使用bartender,它可以绑定数据源、设计模板样式,完全能满足标签打印的需求,如果有好的方式也请大家在评论区讨论。
设计模板主要将模板的样式、数据源在模板里进行设置,这个使用拖拉拽的方式就能实现,我就不多赘述,下面是设计好的效果。
二、批量打印软件开发
批量打印软件需要根据具体的业务逻辑实现,比如通过接口获取后台的待打印列表,这些因项目而异,这里也没办法一次实现,现在主要说明一下bartender模板调用的问题。
针对打印部分我封装了一个通用的调用窗口,在这里可以选择打印机、设置每张的打印次数等;
选择打印机这里需要展示所有的打印列表
PrintDocument printDoc = new PrintDocument();
PrinterSettings printerSettings;
Console.WriteLine("安装的打印机列表:");
int i = 0;
int selectIndex = -1;String defaultPrint = IniUtils.Read("Information", "PrintName");foreach (string printerName in PrinterSettings.InstalledPrinters){ comboBox1.Items.Add(printerName); if(defaultPrint == printerName) { selectIndex = i; } i++; } if(selectIndex >= 0){ comboBox1.SelectedIndex = selectIndex; printName = (string)comboBox1.SelectedItem;}
标签打印类:
using DaYin.data;using MF.Manage.utils;using Newtonsoft.Json;using Newtonsoft.Json.Linq;using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms;
namespace DaYin.utils{ public class PrintUtils { private static BarTender.Application btApp = new BarTender.Application(); private static BarTender.Format btFormat;
public static void print(Dictionary<string, string> dic, string filename, string printName) { string path = System.IO.Directory.GetCurrentDirectory() + "//" + filename + ".btw"; printPath(dic, path,printName); } public static void printPath(Dictionary<string,string> dic, string filePath,string printName) { btFormat = btApp.Formats.Open(filePath, false, printName);
BarTender.NamedSubStrings nss = btFormat.NamedSubStrings;
Dictionary<string, string> js = new Dictionary<string, string>(); foreach (KeyValuePair<string, string> entry in dic) { string key = entry.Key.ToLower(); string value = entry.Value; js.Add(key, value); }
for (int i = 1; i <= nss.Count; i++) { string key = nss.GetSubString(i).Name; string value = js[key]; btFormat.SetNamedSubStringValue(key, value); } try { // 同样标签的份数 btFormat.PrintSetup.IdenticalCopiesOfLabel = 1; // 序列标签数 btFormat.PrintSetup.NumberSerializedLabels = 1; //打印开始 第2个参数是 是否显示打印机属性的。可以设置打印机路径 btFormat.PrintOut(false, false);
//关闭摸板文件,并且关闭文件流 btFormat.Close(BarTender.BtSaveOptions.btDoNotSaveChanges); }catch(Exception ex) {
} }
public static void complete(List<DataGridViewRow> list) { Task task = new Task(() => { string result = ""; try { string ids = ""; foreach (DataGridViewRow dg in list) { ids += dg.Cells["id"].Value + ","; } ids = ids.Substring(0, ids.Length - 1); string param = "ids=" + ids;
result = HttpRequest.getJson(ServerUri.updatePrintStatus, param); } catch (Exception ex) {
} }); task.Start(); } }}
以上就是调用模板和打印的全部流程