//create a preview Image protected void previewTemplate(string documentFile) { if (cmbDocument.SelectedItem.ToString() == string.Empty) { MessageBox.Show("No Template Selected"); } else { pbPreview.ImageLocation = ""; //generate new file using (Engine btEngine = new Engine(true)) { // Start the BarTender print engine. btEngine.Start(); // Open the specified format. LabelFormatDocument btFormat = btEngine.Documents.Open(Path.Combine(documentDirectoryPath, documentFile)); // Export the label format's thumbnail image to a file. btFormat.ExportImageToFile(Path.Combine(Properties.Settings.Default.previewPath, "PreviewImage.jpg"), ImageType.JPEG, Seagull.BarTender.Print.ColorDepth.ColorDepth256, new Resolution(96), Seagull.BarTender.Print.OverwriteOptions.Overwrite); // Stop the BarTender print engine. pbPreview.ImageLocation = Path.Combine(Properties.Settings.Default.previewPath, "PreviewImage.jpg"); btEngine.Stop(); } //Change Preview } }
public string Print(PrintData item) { try { Start(); if (_format.FileName != item.Filename) { _format?.Close(SaveOptions.DoNotSaveChanges); _format = _engine.Documents.Open(item.Filename); } _format.PrintSetup.IdenticalCopiesOfLabel = GetNumberOfLabels(item.NumberOfLables); _format.PrintSetup.PrinterName = DefaultPrinterName; _format.PageSetup.Orientation = GetOrientation(item.Orientation); var waitForCompletionTimeout = 10000; // 10 seconds var result = _format.Print("Label Print", waitForCompletionTimeout, out var messages); string messageString = "\n\nMessages:"; foreach (Seagull.BarTender.Print.Message message in messages) { messageString += "\n\n" + message.Text; } _log.Debug(messageString); return(messageString); } catch (Exception e) { _log.Error(e.Message, e); } return("An Error Occurred"); }
//printing time protected void printFinalLayout(string btLayoutPath, string prtName, string filepath) { using (Engine btEngine = new Engine(true)) { lbEvents.Items.Add("Print Job Started"); DateTime dateValue; btnPrint.Enabled = false; btEngine.Start(); LabelFormatDocument ldoc = btEngine.Documents.Open(btLayoutPath); ldoc.PrintSetup.PrinterName = trimPrinterName(prtName); using (StreamReader ioFile = new StreamReader(@filepath)) { ioFile.ReadLine(); int counter = 0; string line; while ((line = ioFile.ReadLine()) != null) { string[] filSpliced = line.Split(','); ldoc.SubStrings["lblBarcode"].Value = filSpliced[1]; ldoc.SubStrings["lblDescription"].Value = filSpliced[2].Replace(',', ' '); ldoc.SubStrings["lblDate"].Value = DateTime.TryParse(filSpliced[3], out dateValue) ? filSpliced[3] : "1/1/1990"; ldoc.Print(); counter++; } ioFile.Close(); lbEvents.Items.Add("Print Job Completed"); } ldoc.Close(SaveOptions.DoNotSaveChanges); btEngine.Stop(); } btnPrint.Enabled = true; }
public string GetPreviewImage(string filename, int width, int height) { _log.Debug($"GetPreviewImage for filename={filename}"); try { var previewPath = ConfigurationProvider.Settings.PreviewPath; var files = Directory.GetFiles(previewPath); foreach (string file in files) { File.Delete(file); } _format = _engine.Documents.Open(filename); _format.PrintSetup.PrinterName = DefaultPrinterName; Messages messages; _format.ExportPrintPreviewToFile(previewPath, "PrintPreview%PageNumber%.jpg", ImageType.JPEG, Seagull.BarTender.Print.ColorDepth.ColorDepth24bit, new Resolution(width, height), System.Drawing.Color.White, OverwriteOptions.Overwrite, true, true, out messages); files = Directory.GetFiles(previewPath, "*.*"); return(files.Length < 1 ? String.Empty : files[0]); } catch (Exception ex) { _log.Error($"BartenderService.GetPreviewImage error for filename={filename}", ex); } return(null); }
public void BartenderprintShow(string Units) { Engine btEngine = new Engine(); bool isAlive = btEngine.IsAlive; string path = ConfigurationManager.AppSettings["BartenderPath"]; btEngine.Start(); LabelFormatDocument btFormat = btEngine.Documents.Open(path);//这里是Bartender软件生成的模板文件,你需要先把模板文件做好。 //btFormat.PrintSetup.PrinterName = "Foxit Reader PDF Printer"; //btFormat.PrintSetup.IdenticalCopiesOfLabel = 1; //打印份数 //btFormat.SubStrings["s0"].Value = value; //Messages messages; //int waitout = 10000; // 10秒 超时 //Result nResult = btFormat.Print("标签打印软件", waitout, out messages); //string messageString = "\n\nMessages:"; //foreach (Seagull.BarTender.Print.Message message in messages) //{ // messageString += "\n\n" + message.Text; //} System.Drawing.Printing.PrintDocument doc = new System.Drawing.Printing.PrintDocument(); int rawKind = 1; for (int i = 0; i <= doc.PrinterSettings.PaperSizes.Count - 1; i++) { if (doc.PrinterSettings.PaperSizes[i].PaperName == "称重标签") { rawKind = doc.PrinterSettings.PaperSizes[i].RawKind; } } btFormat.PrintSetup.PrinterName = doc.PrinterSettings.PrinterName; if (Units == "斤") { btFormat.SubStrings["UnitsName"].Value = "重量:"; } if (Units == "个") { btFormat.SubStrings["UnitsName"].Value = "数量:"; } btFormat.SubStrings["GoodsName"].Value = info.DrugName;//为Bartender里的数据源(文本框、条码等等)传值 btFormat.SubStrings["GoodsWeight"].Value = info.DrugWeight.ToString("0.00") + Units; btFormat.SubStrings["FJ_id"].Value = info.FJ_id; btFormat.SubStrings["TotalPrice"].Value = "¥" + info.TotalPrice.ToString("0.00"); //btFormat.SubStrings["k3"].Value = batch; //btFormat.SubStrings["s0"].Value = value; //Result nResult1 = btFormat.Print("标签打印软件", waitout, out messages); //btFormat.PrintSetup.Cache.FlushInterval = CacheFlushInterval.PerSession; btFormat.Print(); btFormat.Close(SaveOptions.DoNotSaveChanges);//不保存对打开模板的修改 btEngine.Stop(); }
private void toolStripMenuItem_打印整张表_Click(object sender, EventArgs e) { if (MessageBox.Show("将打印整张表的所有行,是吗?", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Asterisk, MessageBoxDefaultButton.Button2) != DialogResult.Yes) { return; } if (this.Text.Contains("入库汇总") || this.Text.Contains("入库明细")) { foreach (DataGridViewRow row in this.dataGridView.Rows) { string tm = row.Cells["条码"].Value.ToString(); string pm = row.Cells["品名"].Value.ToString(); float sj = float.Parse(row.Cells["售价"].Value.ToString()); string fs = row.Cells["数量"].Value.ToString(); string dj = "¥" + sj.ToString("N2"); LabelFormatDocument doc = Form_main.labeldoc; doc.SubStrings["tm"].Value = tm; doc.SubStrings["pm"].Value = pm; doc.SubStrings["sj"].Value = dj; doc.SubStrings["fs"].Value = fs; doc.Print(); } } }
public LabelFormatDocument OpenLabel(string file) { if (isObjectExistingFile(file)) { LabelFormatDocument label = null; if (this.fileLableDict.ContainsKey(file)) { label = this.fileLableDict[file]; } else { try { label = this.engine.Documents.Open(file); this.fileLableDict.Add(file, label); } catch (Exception ex) { Log.Instance.Logger.Error($"打开btw标签出错{ex.Message}"); } } return(label); } else { return(null); } }
// //载入模板信息 // private void btn_ChangeBT_Template_Click(object sender, RoutedEventArgs e) { try { _WTT_LabInfo.Clear(); //清空列表 // string Patch = "D:\\模板\\PrintTemplates\\HP_Templates\\" + cmb_LabTemplate.Text.Trim(); string Patch = "\\\\QQQQQQ-MS2\\Templates\\PrintTemplates\\HP_Templates\\" + cmb_LabTemplate.Text.Trim(); btEngine.Start(); LabelFormatDocument btFormat = btEngine.Documents.Open(Patch); DataSet ds = Maticsoft.BLL.XmlDatasetConvert.ConvertXMLToDataSet(btFormat.SubStrings.XML); // if (ds.Tables[0].Rows.Count > 0) { foreach (DataRow dr in ds.Tables[0].Rows)//遍历ds { _WTT_LabInfo.Add(new Maticsoft.Model.LabInfo() { Name = dr["Name"].ToString(), Value = dr["Value"].ToString() }); } //排序 // _WTT_LabInfo = new ObservableCollection<Maticsoft.Model.LabInfo>(_WTT_LabInfo.OrderBy(P=>P.Name)); } else { My_MessageBox.My_MessageBox_Message("未找到要设置的模板信息,请确认模板设置是否正确!"); } // btFormat.Close(SaveOptions.DoNotSaveChanges); btEngine.Stop(); } //获取异常信息 catch (Exception ex) { My_MessageBox.My_MessageBox_Message("加载模板信息过程中发生错误!\r\n" + ex.Message); } }
/// <summary> /// Loads a format in a separate thread so it doesn't hang the UI. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> void formatLoader_DoWork(object sender, DoWorkEventArgs e) { int index = (int)e.Argument; string errorMessage = ""; // We lock the engine here because the engine might still be printing a format. lock (engine) { // Make sure this is still the label the user has selected in case they are clicking around fast. if (selectedIndex == index) { try { if (format != null) { format.Close(SaveOptions.DoNotSaveChanges); } format = engine.Documents.Open(browsingFormats[index]); } catch (System.Runtime.InteropServices.COMException comException) { errorMessage = String.Format("Unable to open format: {0}\nReason: {1}", browsingFormats[index], comException.Message); format = null; } } } // We are in a non-UI thread so we need to use Invoke to show our message properly. if (errorMessage.Length != 0) { Invoke(new DelegateShowMessageBox(ShowMessageBox), errorMessage); } }
/// <summary> /// 标签打印 /// </summary> protected virtual void onPrint() { try { string ExcelName = _WTT_LabSetInfo.Tables[0].Rows[0]["LabName"].ToString(); string ExcelPath = "D:\\模板\\PrintTemplates\\Data_Source\\" + ExcelName.Substring(0, ExcelName.Length - 4) + ".xlsx"; //1.获取默认打印机 填充数据 2.开始打印 3.计数清零 4.Exfo待打印数据列表清零 //获取默认打印机 PrintDocument fPrintDocument = new PrintDocument(); Delete_ExcelData(ExcelPath); //填充打印数据源 foreach (DataSet _Temds in _WTT_NotPrintList) { Install_data_ToExcel(_Temds); } Messages messages = null; //设置打印模板 LabelFormatDocument btFormat = btEngine.Documents.Open(LabPatch + LabName); //设置打印机 btFormat.PrintSetup.PrinterName = fPrintDocument.PrinterSettings.PrinterName; btFormat.Activate(); Result result = btFormat.Print("PrintJob1", out messages); btFormat.Close(SaveOptions.SaveChanges); _LabCount = 0; _WTT_NotPrintList.Clear(); Delete_ExcelData(ExcelPath); } catch (System.Exception ex) { My_MessageBox.My_MessageBox_Message(ex.Message); } }
public void print条码() { Engine btEngine = new Engine(); btEngine.Start(); //string lj = AppDomain.CurrentDomain.BaseDirectory + "顺丰订单模板.btw"; //test.btw是BT的模板 //string lj = AppDomain.CurrentDomain.BaseDirectory + "001.btw"; //test.btw是BT的模板 String lj2 = "C:\\003.btw"; LabelFormatDocument btFormat = btEngine.Documents.Open(lj2); //指定打印机名 //btFormat.PrintSetup.PrinterName = "HPRT HLP106S-UE"; //btFormat.PrintSetup.PrinterName = "TEC"; btFormat.PrintSetup.PrinterName = "POSTEK G-3106"; //打印份数 btFormat.PrintSetup.IdenticalCopiesOfLabel = 1; //改变标签打印数份连载 btFormat.PrintSetup.NumberOfSerializedLabels = 2; //对BTW模版相应字段进行赋值 btFormat.SubStrings["styleid"].Value = this.dto.materialid; btFormat.SubStrings["cd"].Value = this.dto.materialcd + " " + this.dto.materialname; Messages messages1; int waitout1 = 10000; // 10秒 超时 Result nResult2 = btFormat.Print("条码" + this.dto.materialid, waitout1, out messages1); btFormat.PrintSetup.Cache.FlushInterval = CacheFlushInterval.PerSession; //不保存对打开模板的修改 btFormat.Close(SaveOptions.DoNotSaveChanges); //结束打印引擎 btEngine.Stop(); }
private void SetUpServiceTagFormat() { serviceTagFormatLinkLabel.Enabled = false; serviceTagFormatLinkLabel.Text = "ładowanie..."; if (serviceTagFormat != null) { serviceTagFormat.Close(Seagull.BarTender.Print.SaveOptions.DoNotSaveChanges); serviceTagFormat = null; } if (!string.IsNullOrEmpty(settings.ServiceTagFormatFile)) { try { serviceTagFormat = engine.Documents.Open(settings.ServiceTagFormatFile); } catch (Exception x) { settings.ServiceTagFormatFile = ""; ShowError("Błąd otwierania etykiety Service Tag", x.Message); } } serviceTagFormatLinkLabel.Text = serviceTagFormat == null ? "wybierz..." : Path.GetFileNameWithoutExtension(settings.ServiceTagFormatFile); serviceTagFormatLinkLabel.Enabled = true; }
protected virtual void onMyZebraPint() { try { if (MyZeberPrint != null) { Messages messages = null; //设置打印模板 LabelFormatDocument btFormat = btEngine.Documents.Open(_LabellMode); //设置打印机 btFormat.PrintSetup.PrinterName = _PrintName; MyZeberPrint(btFormat); // Set this format as the Active format for this // BarTender engine instance. btFormat.Activate(); // Print the format. // btEngine.ActiveDocument.Print(); Result result = btFormat.Print("PrintJob1", out messages); // Close the current format, saving any changes. btFormat.Close(SaveOptions.SaveChanges); } } catch (Exception ex) { MessageBox.Show(ex.Message); } }
public bool Print(string filename) { try { _format?.Close(SaveOptions.DoNotSaveChanges); _format = _engine.Documents.Open(filename); _format.PrintSetup.IdenticalCopiesOfLabel = 1; _format.PrintSetup.PrinterName = DefaultPrinterName; var waitForCompletionTimeout = 10000; // 10 seconds var result = _format.Print("Label Print", waitForCompletionTimeout, out var messages); string messageString = "\n\nMessages:"; foreach (Seagull.BarTender.Print.Message message in messages) { messageString += "\n\n" + message.Text; } _log.Info(messageString); return(result == Result.Success); } catch (Exception e) { _log.Error(e.Message, e); } return(false); }
//调试打印 private void Debug_Print_Click(object sender, EventArgs e) { //判断导入Excel没 if (this.ImportPath.Text == "") { player.Play(); this.remined.AppendText("请先导入Excel\r\n"); return; } //判断模板是否为空 if (this.Select_Template.Text == "") { player.Play(); this.remined.AppendText("请先选择模板\r\n"); return; } string strExtension = this.ImportPath.Text.Substring(this.ImportPath.Text.LastIndexOf('.')); DataTable dt = IEB.GetExcelDatatable(this.ImportPath.Text, strExtension); DataRow dr3 = dt.Rows[1]; LabelFormatDocument btFormat = btEngine.Documents.Open(lj); //指定打印机名称 btFormat.PrintSetup.PrinterName = this.Printer.Text; //对模板相应字段进行赋值 btFormat.SubStrings["IMEI1"].Value = dr3[0].ToString(); btFormat.SubStrings["IMEI2"].Value = dr3[1].ToString(); btFormat.SubStrings["IMEI3"].Value = dr3[2].ToString(); btFormat.SubStrings["IMEI4"].Value = dr3[3].ToString(); btFormat.SubStrings["IMEI5"].Value = dr3[4].ToString(); btFormat.SubStrings["ProductDate"].Value = DateTime.Now.ToString("yyyy.MM.dd"); //打印份数,同序列打印的份数 btFormat.PrintSetup.IdenticalCopiesOfLabel = TN; btFormat.Print(); Form1.Log("Excel调试打印了机身贴IMEI号为" + dr3[1].ToString() + "的制单", null); }
public PrintWorkerArguments(IPrintJob printJob, Engine engine, LabelFormatDocument orderFormat, LabelFormatDocument programFormat, LabelFormatDocument serviceTagFormat) { this.orderFormat = orderFormat; this.programFormat = programFormat; this.serviceTagFormat = serviceTagFormat; PrintJob = printJob; Engine = engine; }
public int InsertBarTenderPrintingLable(int productid, string formatname, int chk) { try { string btFileName = ""; LogFile lf = new LogFile(); using (Engine btEngine = new Engine()) { lf.LogMessge("S1 :" + "Inside Service"); btEngine.Start(); lf.LogMessge("S2 :" + "Service Started"); btEngine.Window.Visible = true; // btFileName = @"\\glpdc01\corp\IT Files\GPLS\BarTenderFiles\" + filename + ".btw"; //btFileName = @"\\psapp01\IT Files\PLS\BarTenderFiles\" + filename + ".btw"; btFileName = @"\\psapp01\IT Files\PLS\BarTenderFilesTest01\" + formatname + ".btw"; lf.LogMessge("S3 :" + "File Path"); lf.LogMessge("S4 :" + "File :" + btFileName); LabelFormatDocument btFormat = btEngine.Documents.Open(btFileName); lf.LogMessge("S5 :" + "Go the File"); Seagull.BarTender.Print.Database.QueryPrompts queryprompts = btFormat.DatabaseConnections.QueryPrompts; queryprompts["productid"].Value = productid.ToString(); queryprompts["chk"].Value = chk.ToString(); lf.LogMessge("S6 :" + "Query Promted"); //btFormat.PrintSetup.IdenticalCopiesOfLabel = labelcount; //btFormat.PrintSetup.NumberOfSerializedLabels = 4 Result result = btFormat.Print(btFileName); lf.LogMessge("S7 :" + "Result: " + result); //Result result = btFormat.Print(); if (result == Result.Failure) { lf.LogMessge("S8 :" + "Failure "); btFormat.Close(Seagull.BarTender.Print.SaveOptions.DoNotSaveChanges); btEngine.Stop(); btEngine.Dispose(); return(0); } else { lf.LogMessge("S9 :" + "Sucess "); btFormat.Close(Seagull.BarTender.Print.SaveOptions.DoNotSaveChanges); btEngine.Stop(); btEngine.Dispose(); return(1); } } } catch (Exception ex) { LogFile lf1 = new LogFile(); lf1.LogMessge("S10 :" + "Exception Date :" + DateTime.Now.ToLongTimeString() + "\nException Message:" + ex.Message); // Page.ClientScript.RegisterStartupScript(this.GetType(), "log", "log('" + ex.Message + "');", true); return(0); } }
public int BarTenderPrintingLable(int controlId, int labelcount, int categorycode, string filename, int batchid, int testprint) { try { string btFileName = ""; LogFile lf = new LogFile(); using (Engine btEngine = new Engine()) { lf.LogMessge("S1 :" + "Inside Service"); btEngine.Start(); lf.LogMessge("S2 :" + "Service Started"); btEngine.Window.Visible = true; // btFileName = @"\\psapp01\IT Files\PLS\BarTenderFilesTes1\" + filename + ".btw"; btFileName = @"\\psapp01\IT Files\PLS\BarTenderFiles\" + filename + ".btw"; lf.LogMessge("S4 :" + "File :" + btFileName); LabelFormatDocument btFormat = btEngine.Documents.Open(btFileName); lf.LogMessge("S3 :" + "File Path"); lf.LogMessge("S4 :" + "File :" + btFileName); Seagull.BarTender.Print.Database.QueryPrompts queryprompts = btFormat.DatabaseConnections.QueryPrompts; lf.LogMessge("S5 :" + "Go the File"); queryprompts["controlid"].Value = controlId.ToString(); queryprompts["categorycode"].Value = categorycode.ToString(); queryprompts["toprint"].Value = labelcount.ToString(); queryprompts["batchid"].Value = batchid.ToString(); queryprompts["testprint"].Value = testprint.ToString(); lf.LogMessge("S6 :" + "Query Promted"); //btFormat.PrintSetup.IdenticalCopiesOfLabel = labelcount; //btFormat.PrintSetup.NumberOfSerializedLabels = 4 Result result = btFormat.Print(btFileName); lf.LogMessge("S7 :" + "Result: " + result); //Result result = btFormat.Print(); if (result == Result.Failure) { lf.LogMessge("S8 :" + "Failure "); btFormat.Close(Seagull.BarTender.Print.SaveOptions.DoNotSaveChanges); btEngine.Stop(); btEngine.Dispose(); return(0); } else { lf.LogMessge("S9 :" + "Sucess "); btFormat.Close(Seagull.BarTender.Print.SaveOptions.DoNotSaveChanges); btEngine.Stop(); btEngine.Dispose(); return(1); } } } catch (Exception ex) { LogFile lf1 = new LogFile(); lf1.LogMessge("S10 :" + "Exception Date :" + DateTime.Now.ToLongTimeString() + "\nException Message:" + ex.Message); return(0); } }
private void button1_Click(object sender, EventArgs e) { Engine btEngine = new Engine(); //starting BarTender print engine, Should move this probably to more optimal position btEngine.Start(); //add all files from the chosen directory | looking for a way to oass agrument on files grabbed to only get .btw string[] labelFiles = Directory.GetFiles(labelsPath); //Will be list of .btw files full path that match the speech var selectedLabels = new List <string>(); //create the speech recognition engine using (SpeechRecognitionEngine recognizer = new SpeechRecognitionEngine( new System.Globalization.CultureInfo("en-US"))) { recognizer.LoadGrammar(new DictationGrammar()); recognizer.SetInputToDefaultAudioDevice(); recognizer.InitialSilenceTimeout = TimeSpan.FromSeconds(5); RecognitionResult recorded = recognizer.Recognize(); if (recorded != null) { MessageBox.Show(recorded.Text); //This is to count how many documents contain the speech recorded int count = 0; string oneDocument = ""; foreach (string x in labelFiles) { if (x.Remove(0, labelsPath.Length + 1).ToLower().Contains(recorded.Text.ToLower()) && x.Contains(".btw")) { MessageBox.Show(x.Remove(0, labelsPath.Length + 1)); count++; string printFile = x; //add found .btw to the dropdown comboBox1.Items.Add(printFile.Remove(0, labelsPath.Length + 1)); //add full path to list selectedLabels.Add(x); oneDocument += x; } } if (count == 1) { LabelFormatDocument Label = btEngine.Documents.Open(@oneDocument); Label.PrintSetup.PrinterName = printerName; Label.PrintSetup.RecordRange = "1"; Label.Print(); } } } }
void PrintBar(bool isPreView = false) { if (_btw_path.Length < 5) { fileNametBox.BackColor = Color.Red; return; } using (Engine btEngine = new Engine(true)) { LabelFormatDocument labelFormat = btEngine.Documents.Open(_btw_path); try { labelFormat.SubStrings.SetSubString("name", name_textBox.Text); labelFormat.SubStrings.SetSubString("age", age_textBox.Text); labelFormat.SubStrings.SetSubString("ID", id_textBox.Text); labelFormat.SubStrings.SetSubString("code", num_textBox.Text); } catch (Exception ex) { MessageBox.Show("修改内容出错 " + ex.Message, "操作提示"); } if (labelFormat != null) { //Generate a thumbnail for it. labelFormat.ExportImageToFile(_bmp_path, ImageType.BMP, Seagull.BarTender.Print.ColorDepth.ColorDepth24bit, new Resolution(407, 407 ), OverwriteOptions.Overwrite); System.Drawing.Image image = System.Drawing.Image.FromFile(_bmp_path); Bitmap NmpImage = new Bitmap(image); pictureBox.Image = NmpImage; image.Dispose(); } else { MessageBox.Show("生成图片错误", "操作提示"); } if (isPreView) { return; } if (_PrinterName != "") { labelFormat.PrintSetup.PrinterName = _PrinterName; labelFormat.Print("BarPrint" + DateTime.Now, 3 * 1000); } else { MessageBox.Show("请先选择打印机", "操作提示"); } } }
static void Main(string[] args) { //Print(@"C:\Program Files (x86)\Seagull\BarTender UltraLite", "得力模板"); try { string PrintName = "TSC TTP-243E Pro"; //"TSC TTP-243E Pro" Console.WriteLine("引擎new之前"); //"记录日志方便查找问题原因" Engine btEngine = new Engine(); Console.WriteLine("引擎new完后,start前"); btEngine.Start(); Console.WriteLine("引擎开启"); LabelFormatDocument btFormat = btEngine.Documents.Open(Path.Combine("C://Program Files (x86)//Seagull//BarTender Suite", "得力模板" + ".btw")); Console.WriteLine("模版打开"); btFormat.SubStrings["dept"].Value = "研发部"; //对模版相应字段进行赋值 //btFormat.SubStrings["ProjectName"].Value = DataImportOld.Material_Name; //btFormat.SubStrings["GroupName"].Value = DataImportOld.WorkingGroup_Name; //btFormat.SubStrings["Type"].Value = DataImportOld.Material_Type; //btFormat.SubStrings["Color"].Value = DataImportOld.Color; //btFormat.SubStrings["Num"].Value = Convert.ToString(True_Number); //btFormat.SubStrings["BarCodeName"].Value = builder.ToString(); //btFormat.SubStrings["Batch"].Value = DataImportOld.Batch; Console.WriteLine("模版赋值"); //btFormat.PrintSetup.Cache.FlushInterval = CacheFlushInterval.PerSession; //btFormat.Close(SaveOptions.DoNotSaveChanges);//不保存对打开模板的修改 btFormat.PrintSetup.PrinterName = PrintName; //寻找打印机 //PrinterSettings.StringCollection snames = PrinterSettings.InstalledPrinters; //bool PrintIsExist = false; //string logPringter = ""; //foreach (string Name in snames) //{ // logPringter += Name + ";"; // if (Name.ToLower().Trim() == PrintName.ToLower().Trim()) // { // PrintIsExist = true; // } //} //Console.WriteLine("搜索的打印机有" + logPringter); //if (!PrintIsExist) //{ // Console.WriteLine("打印机不存在"); //} Console.WriteLine("开始打印"); btFormat.Print(); Console.WriteLine("打印成功"); Console.WriteLine("开始关闭引擎"); btEngine.Stop(); Console.WriteLine("关闭引擎成功"); } catch (Exception ex) { Console.WriteLine(string.Format("Exception: " + ex.Message)); } }
private LabelFormatDocument SetLabelValues(string file, out string obarcodeHistroySuffix) { Log.Instance.Logger.Info($"开始设置标签字段值,文件{file}"); string barcodeHistroySuffix = ""; LabelFormatDocument label = this.labelOperator.OpenLabel(file); string[] fieldsIn = this.labelOperator.GetLabelFields(file); Log.Instance.Logger.Info($"标签包含的字段:{string.Join(",", fieldsIn)}"); this.Message = $"标签包含的字段:{string.Join(",", fieldsIn)}"; if (this.LabelHasShift) { string shiftValue = this.SelectedShift; foreach (string field in fieldsIn.Intersect( Constants.FieldsAliasDict[Constants.FieldShift] .Union(new string[] { Constants.FieldShift })).Distinct()) { label.SubStrings[field].Value = shiftValue; Log.Instance.Logger.Info($"设置{field}={shiftValue}"); } barcodeHistroySuffix += shiftValue; } Log.Instance.Logger.Info($"转换规则名称{fieldsValueConverter.GetType()}"); if (this.LabelHasDate) { string dateValue = this.fieldsValueConverter.ConvertDate(this.SelectedDate); foreach (string field in fieldsIn.Intersect( Constants.FieldsAliasDict[Constants.FieldDate] .Union(new string[] { Constants.FieldDate })).Distinct()) { label.SubStrings[field].Value = dateValue; Log.Instance.Logger.Info($"设置{field}={dateValue}"); } barcodeHistroySuffix += dateValue; } if (this.LabelHasSN) { this.StartingNumber++; string snValue = this.fieldsValueConverter.ConvertSn(this.StartingNumber); foreach (string field in fieldsIn.Intersect( Constants.FieldsAliasDict[Constants.FieldSN] .Union(new string[] { Constants.FieldSN })).Distinct()) { label.SubStrings[field].Value = snValue; Log.Instance.Logger.Info($"设置{field}={snValue}"); } barcodeHistroySuffix += snValue; } Log.Instance.Logger.Info($"结束设置标签字段值,文件{file}"); obarcodeHistroySuffix = barcodeHistroySuffix; return(label); }
/// <summary> /// 定时执行事件 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void Print_Elapse(object sender, ElapsedEventArgs e) { DorllyOrderService.Service service = new DorllyOrderService.Service(); service.Url = _serviceUrl; try { logger.Info("开始检索打印数据..."); DataTable dt = service.PopulateDataSet("Select * From OP_MeterPrint Where Status='0'").Tables[0]; if (dt.Rows.Count > 0) { service.ExecuteNonQuery("Update OP_MeterPrint Set Status='1' Where Status='0'"); List <Op_MeterPrint> printList = JsonConvert.DeserializeObject <List <Op_MeterPrint> >(JsonConvert.SerializeObject(dt)); try { logger.Info(string.Format("数据获取成功,数量为{0},准备打印中...", printList.Count)); foreach (var item in printList) { Engine printEngine = new Engine(); printEngine.Start(); LabelFormatDocument labelFormat = printEngine.Documents.Open(AppDomain.CurrentDomain.BaseDirectory + item.PrintFormat); labelFormat.PrintSetup.PrinterName = _machineName; labelFormat.PrintSetup.IdenticalCopiesOfLabel = 1; //编号 labelFormat.SubStrings["meterNo"].Value = item.MeterNo; //费率 labelFormat.SubStrings["meterRate"].Value = item.MeterRate.ToString("0.####"); //位数 labelFormat.SubStrings["meterDigit"].Value = item.MeterDigit.ToString(); //二维码 labelFormat.SubStrings["meterCode"].Value = item.MeterNo; labelFormat.Print(); labelFormat.Close(SaveOptions.DoNotSaveChanges);//不保存对打开模板的修改 printEngine.Stop(); } } catch (Exception ex) { logger.Error("打印发生错误!详情见错误信息!"); logger.Error(ex.ToString()); } }//end count if else { logger.Info("暂无打印数据。。。"); } } catch (Exception ex) { logger.Error("数据获取错误!详情见错误信息!"); logger.Error(ex.ToString()); } }
private void bw_DoWork(object sender, DoWorkEventArgs e) { LabelFormatDocument format = null; // The currently open Format Messages messages; //int waitForCompletionTimeout = 10000; // 10 seconds Result result; string strData, strLabelPathAndName; using (Engine engine = new Engine()) { engine.Start(); //strLabelFile = Settings.GetLabelPath() + mobjSelectedLabel.LabelFile; strData = e.Argument.GetValueFromAnonymousType <string>("Data"); strLabelPathAndName = e.Argument.GetValueFromAnonymousType <string>("LabelPathAndName"); format = engine.Documents.Open(strLabelPathAndName); if (format.PrintSetup.SupportsIdenticalCopies) { format.PrintSetup.IdenticalCopiesOfLabel = int.Parse(nudQuantity.Value.ToString()); } foreach (var objSubString in format.SubStrings) { switch (objSubString.Name) { case "Text": format.SubStrings[objSubString.Name].Value = strData; break; case "Address": format.SubStrings[objSubString.Name].Value = strData; break; } } format.PrintSetup.PrinterName = e.Argument.GetValueFromAnonymousType <string>("PrinterName"); //result = format.Print("WTF Shipping Application", waitForCompletionTimeout, out messages); result = format.Print("WTF Shipping Application", out messages); string messageString = "\n\nMessages:"; foreach (Seagull.BarTender.Print.Message message in messages) { messageString += "\n\n" + message.Text; } if (result == Result.Failure) { throw new Exception(messageString); } else { e.Result = messageString; } } }
public void BarTenderPrintingLable(int id) { try { DataTable dt = new DataTable(); //SqlCommand cmd = new SqlCommand("dbo.spLabelingReportPreview", conn); //cmd.CommandType = CommandType.StoredProcedure; //cmd.Parameters.AddWithValue("@ControlID", id); //SqlDataAdapter da = new SqlDataAdapter(cmd); //da.Fill(dt); dt = st_dll.ReportData("dbo.spLabelingReportPreview", id, 4); DataRow row = dt.Rows[0]; using (Engine btEngine = new Engine()) { btEngine.Start(); //btEngine.Window.Visible = true; string btFileName = ""; btFileName = @"\\GLWS18\Users\samancha\Documents\BarTender\BarTenderDocuments\Product_Label.btw"; //btFileName = @"C:\Users\samancha\Desktop\Product_Label.btw"; LabelFormatDocument btFormat = btEngine.Documents.Open(btFileName); Seagull.BarTender.Print.Database.QueryPrompts queryprompts = btFormat.DatabaseConnections.QueryPrompts; queryprompts["controlid"].Value = id.ToString(); btFormat.PrintSetup.IdenticalCopiesOfLabel = Convert.ToInt32(dt.Rows[0]["LabelCount"]); Result result = btFormat.Print(btFileName); //Result result = btFormat.Print(); if (result == Result.Failure) { //string Message = "Label is printed Failure"; //string wsScript = "<script type=\"text/javascript\">document.getElementById('#divfailure').style.display='block';document.getElementById('#divfailure').InnerHtml ='" + Message + "'</script>"; //Page.ClientScript.RegisterStartupScript(this.GetType(), "validation", wsScript, true); SucessMessage("Label is printed successfully !"); } else { //string Message = "Label is printed Successfully"; //string wsScript = "<script type=\"text/javascript\">document.getElementById('#divAdded').style.display='block';document.getElementById('#divAdded').InnerHtml ='" + Message + "'</script>"; //Page.ClientScript.RegisterStartupScript(this.GetType(), "validation", wsScript, true); ErrorMessage("Failed to print the label !"); } btFormat.Close(Seagull.BarTender.Print.SaveOptions.DoNotSaveChanges); btEngine.Stop(); } } catch (Exception ex) { ErrorMessage(ex.Message); } }
public void BartenderprintShow() { Engine btEngine = new Engine(); bool isAlive = btEngine.IsAlive; string path = ConfigurationManager.AppSettings["CountPath"]; btEngine.Start(); LabelFormatDocument btFormat = btEngine.Documents.Open(path);//这里是Bartender软件生成的模板文件,你需要先把模板文件做好。 //btFormat.PrintSetup.PrinterName = "Foxit Reader PDF Printer"; //btFormat.PrintSetup.IdenticalCopiesOfLabel = 1; //打印份数 //btFormat.SubStrings["s0"].Value = value; //Messages messages; //int waitout = 10000; // 10秒 超时 //Result nResult = btFormat.Print("标签打印软件", waitout, out messages); //string messageString = "\n\nMessages:"; //foreach (Seagull.BarTender.Print.Message message in messages) //{ // messageString += "\n\n" + message.Text; //} System.Drawing.Printing.PrintDocument doc = new System.Drawing.Printing.PrintDocument(); //int rawKind = 1; //for (int i = 0; i <= doc.PrinterSettings.PaperSizes.Count - 1; i++) //{ // if (doc.PrinterSettings.PaperSizes[i].PaperName == "订单打印") // { // rawKind = doc.PrinterSettings.PaperSizes[i].RawKind; // } //} btFormat.PrintSetup.PrinterName = doc.PrinterSettings.PrinterName; btFormat.SubStrings["Info"].Value = this.textBox1.Text.ToString();//为Bartender里的数据源(文本框、条码等等)传值 //btFormat.SubStrings["k3"].Value = batch; //btFormat.SubStrings["s0"].Value = value; //Result nResult1 = btFormat.Print("标签打印软件", waitout, out messages); //btFormat.PrintSetup.Cache.FlushInterval = CacheFlushInterval.PerSession; btFormat.Print(); btFormat.Close(SaveOptions.DoNotSaveChanges);//不保存对打开模板的修改 btEngine.Stop(); return; }
public static string PrintBtwFile(LabelFormatDocument updatedFormat, Engine btEngine) { Messages messages; int waitForCompletionTimeout = 10000; Result result = updatedFormat.Print("在线打印系统打印", waitForCompletionTimeout, out messages); string messageString = ""; foreach (Seagull.BarTender.Print.Message message in messages) { messageString += "\r\n" + message.Text; } return(messageString); }
public string[] GetLabelFields(string file) { LabelFormatDocument label = this.OpenLabel(file); if (label != null) { return(label.SubStrings.OfType <SubString>().Select(x => x.Name.Trim()).ToArray()); } else { return new string[] { } }; }
public PrintForm(IList <IPrintJob> printJobs, Engine engine, LabelFormatDocument orderFormat, LabelFormatDocument programFormat, LabelFormatDocument serviceTagFormat) { InitializeComponent(); this.printJobs = printJobs; this.engine = engine; this.orderFormat = orderFormat; this.programFormat = programFormat; this.serviceTagFormat = serviceTagFormat; CreateSeriesGroups(); CreatePrintJobItems(); }
public PrintForm(IList<IPrintJob> printJobs, Engine engine, LabelFormatDocument orderFormat, LabelFormatDocument programFormat, LabelFormatDocument serviceTagFormat) { InitializeComponent(); this.printJobs = printJobs; this.engine = engine; this.orderFormat = orderFormat; this.programFormat = programFormat; this.serviceTagFormat = serviceTagFormat; CreateSeriesGroups(); CreatePrintJobItems(); }
// //生产预览 // private void btn_YL_Click(object sender, RoutedEventArgs e) { try { string Patch = "\\\\QQQQQQ-MS2\\Templates\\PrintTemplates\\HP_Templates\\" + cmb_LabTemplate.Text.Trim(); btEngine.Start(); LabelFormatDocument btFormat2 = btEngine.Documents.Open(Patch); //填充打印数据源 foreach (Maticsoft.Model.LabInfo _lin in _WTT_LabInfo) { string drName = _lin.Name; btFormat2.SubStrings[drName].Value = _lin.Value; } string path = @"D:\Thumbnail.jpeg"; File.Delete(path); Resolution t = new Resolution(ImageResolution.Screen); btFormat2.ExportImageToFile(path, ImageType.JPEG, Seagull.BarTender.Print.ColorDepth.ColorDepth256, new Resolution(3840, 2160), OverwriteOptions.Overwrite); btFormat2.Close(SaveOptions.DoNotSaveChanges); btEngine.Stop(); lab_State.Content = "显示图片"; try { //读成二进制 imBytes = File.ReadAllBytes(path); //直接把这个存储到数据就行了cmd.Parameters.Add("@image", SqlDbType.Image).Value = bytes; //在控件中显示图片 BitmapImage BI = new BitmapImage(); BI.BeginInit(); BI.StreamSource = new MemoryStream(imBytes); //bufPic是图片二进制,byte类型 BI.EndInit(); // image1.Width = BI.Width; // image1.Height = BI.Height; image1.UseLayoutRounding = true; image1.Source = BI;//image是XAML页面上定义的Image控件 } catch { } lab_State.Content = "生成完成!"; // System.Diagnostics.Process.Start("explorer.exe", FilePath); //打开指定文件夹 } catch (Exception ex) { My_MessageBox.My_MessageBox_Erry("错误\r\n" + ex.Message); } }
public void Print(LabelFormatDocument labelFormat) { SetPrintSetup(labelFormat); SetSubStrings(labelFormat); Messages messages; var result = labelFormat.Print(PrintJobName, out messages); if (result == Result.Success) { return; } if (result == Result.Timeout) { throw new PrintException("Upłynął czas oczekiwania na odpowiedź."); } HandleFailure(messages); }
private static void print2BitmapFile(LabelFormatDocument btFormat, PoolItem item) { string methodName = "print2BitmapFile"; logger.DebugFormat("BEGIN: {0}()", methodName); try { lock (synPrinter) { setupBitmapPrinter(item); btFormat.PrintSetup.EnablePrompting = false; Thread.Sleep(20); Result result = btFormat.Print(); if (result == Result.Success) { waitingBitmapFile(item.BmpFolder); logger.DebugFormat("Thread Id: {0} generate label {1} bitmap files count ok! ", item.ThreadId.ToString(), item.ThreadId.ToString("D5")); } else { item.HasError = true; item.ErrorText = string.Format("Thread Id: {0} generate label {1} bitmap file {2} ErrorText: {3}", item.ThreadId.ToString(), item.BtwFile, item.ThreadId.ToString("D5"), result.ToString()); throw new Exception(item.ErrorText); } } } catch (Exception e) { logger.Error(e.Message, e); throw; } finally { logger.DebugFormat("END: {0}()", methodName); } }
private LabelFormatDocument GetBarcodeLabel(LabelFormatDocument btFormat, BarcodeEntity barcode, int itemID, string wsNumber) { if (btFormat.SubStrings[BarCodeConstants.CustomerName] != null) { btFormat.SubStrings[BarCodeConstants.CustomerName].Value = barcode.LastName + " " + barcode.FirstName; } if (btFormat.SubStrings[BarCodeConstants.CurrentQuantity] != null) { btFormat.SubStrings[BarCodeConstants.CurrentQuantity].Value = (itemID + 1).ToString(); } if (btFormat.SubStrings[BarCodeConstants.TotalQuantity] != null) { btFormat.SubStrings[BarCodeConstants.TotalQuantity].Value = barcode.Quantity; } if (btFormat.SubStrings[BarCodeConstants.SalesOrder] != null) { btFormat.SubStrings[BarCodeConstants.SalesOrder].Value = barcode.SalesOrder; } if (btFormat.SubStrings[BarCodeConstants.OrderDate] != null) { btFormat.SubStrings[BarCodeConstants.OrderDate].Value = barcode.OrderDate; } if (btFormat.SubStrings[BarCodeConstants.CustomerPO] != null) { btFormat.SubStrings[BarCodeConstants.CustomerPO].Value = barcode.CustomerPO; } if (btFormat.SubStrings[BarCodeConstants.Worksheet] != null) { btFormat.SubStrings[BarCodeConstants.Worksheet].Value = barcode.Worksheet; } if (btFormat.SubStrings[BarCodeConstants.Size] != null) { btFormat.SubStrings[BarCodeConstants.Size].Value = barcode.Size; } if (btFormat.SubStrings[BarCodeConstants.SQFT] != null) { btFormat.SubStrings[BarCodeConstants.SQFT].Value = barcode.SqFt; } if (btFormat.SubStrings[BarCodeConstants.Logo] != null) { btFormat.SubStrings[BarCodeConstants.Logo].Value = barcode.Logo; } if (btFormat.SubStrings[BarCodeConstants.Description] != null) { btFormat.SubStrings[BarCodeConstants.Description].Value = barcode.Description; } if (btFormat.SubStrings[BarCodeConstants.BarcodeItem] != null) { btFormat.SubStrings[BarCodeConstants.BarcodeItem].Value = wsNumber + "-" + barcode.Line + "-" + (itemID + 1).ToString(); } if (btFormat.SubStrings[BarCodeConstants.DueDate] != null) { btFormat.SubStrings[BarCodeConstants.DueDate].Value = barcode.DueDate; } if (btFormat.SubStrings[BarCodeConstants.GlassShape] != null) { btFormat.SubStrings[BarCodeConstants.GlassShape].Value = barcode.Shape; } return btFormat; }
protected virtual void SetPrintSetup(LabelFormatDocument labelFormat) { labelFormat.PrintSetup.PrinterName = PrinterName; labelFormat.PrintSetup.IdenticalCopiesOfLabel = LabelQuantity; }
private Result PrintLabel(LabelFormatDocument label) { Result result = Result.Failure; try { result = label.Print(); } catch (Exception ex) { Logger.LogException(ex); } return result; }
private static void preview2BitmapFile(LabelFormatDocument btFormat, PoolItem item) { string methodName = "preview2BitmapFile"; logger.DebugFormat("BEGIN: {0}()", methodName); try { Seagull.BarTender.Print.Messages message = null; string bmpFileName = "%PageNumber%.bmp"; Resolution res = new Resolution(item.DPI); System.Drawing.Color bkcolor = System.Drawing.ColorTranslator.FromHtml("#FFFFFF"); Result result = btFormat.ExportPrintPreviewToFile(item.BmpFolder, bmpFileName, ImageType.BMP, ColorDepth.Mono , res, bkcolor, OverwriteOptions.Overwrite, false, false, out message); if (result != Result.Success) { item.HasError = true; string str = ""; foreach (Seagull.BarTender.Print.Message m in message) { str += string.Format("{0} Message: {1}\r\n", m.Severity, m.Text); } item.ErrorText = string.Format("Thread Id: {0} generate label {1} bitmap file {2} ErrorText: {3}", item.ThreadId.ToString(), item.BtwFile, result.ToString(), str); throw new Exception(item.ErrorText); } else { logger.DebugFormat("Thread Id: {0} generate label {1} bitmap file ok! ", item.ThreadId.ToString(), item.BtwFile); } } catch (Exception e) { logger.Error(e.Message, e); throw; } finally { logger.DebugFormat("END: {0}()", methodName); } }
protected override void SetPrintSetup(LabelFormatDocument labelFormat) { labelFormat.PrintSetup.PrinterName = PrinterName; labelFormat.PrintSetup.IdenticalCopiesOfLabel = 1; labelFormat.PrintSetup.NumberOfSerializedLabels = LabelQuantity; }