public string VariablesToString(LabelManager2.IDocument document) { var temp = ""; var cnt = document.Variables.FormVariables.Count; for (int i = 1; i <= cnt; i++) { temp += document.Variables.FormVariables.Item(i).Name + " ==> "; temp += document.Variables.FormVariables.Item(i).Value + "\r\n"; } return(temp); }
/// <summary> /// Codesoft模板打印。 /// </summary> /// <param name="name">打印机名称/IP地址。</param> /// <param name="port">打印机端口。</param> /// <param name="directAccess">直接访问打印机。</param> /// <param name="templatePath">codesoft模板绝对路径。</param> /// <param name="obj">替换模版文件中的变量。</param> /// <returns></returns> public bool Print(string name, string port, bool directAccess, string templatePath, ExpandoObject obj) { LabelManager2.IApplication lbl = null; LabelManager2.IDocument doc = null; try { lbl = new LabelManager2.ApplicationClass(); string path = templatePath.Replace("codesoft://", string.Empty); if (doc == null) { if (Path.IsPathRooted(path) == false) { string directoryName = System.AppDomain.CurrentDomain.BaseDirectory; path = Path.GetFullPath(Path.Combine(directoryName, path)); } lbl.Documents.Open(path); if (lbl == null) { throw new Exception(string.Format("打开模板文件({0})失败。", path)); } doc = lbl.ActiveDocument; } if (doc == null) { throw new Exception(string.Format("打开模板文件({0})失败。", path)); } var printQty = 1; if (obj != null) { for (int i = 1; i <= doc.Variables.FormVariables.Count; i++) { var variableItem = doc.Variables.FormVariables.Item(i); KeyValuePair <string, object> pair = obj.FirstOrDefault(item => item.Key.ToUpper() == variableItem.Name.ToUpper()); if (pair.Value != null) { variableItem.Value = Convert.ToString(pair.Value); } } KeyValuePair <string, object> printQtyPair = obj.FirstOrDefault(item => item.Key.ToUpper() == "PrintQty".ToUpper()); if (printQtyPair.Value != null) { int.TryParse(Convert.ToString(printQtyPair.Value), out printQty); } } string defaultPrinterName = doc.Printer.Name; if (defaultPrinterName != name && doc.Printer.SwitchTo(name, port, directAccess) == false) { LabelManager2.Strings vars = lbl.PrinterSystem().Printers(LabelManager2.enumKindOfPrinters.lppxAllPrinters); string printerNames = string.Empty; for (int i = 1; i <= vars.Count; i++) { printerNames += vars.Item(i) + ";"; } throw new Exception(string.Format("打印机({0})不存在。系统中存在的打印机列表 {1}。", name, printerNames)); } doc.PrintDocument(printQty); } finally { //释放非托管资源 if (doc != null) { doc.FormFeed(); doc.Close(); doc = null; } if (lbl != null) { lbl.Quit(); lbl = null; } } return(true); }