/// UpdateJobData #region UpdateJobData /// <summary> /// /// </summary> /// <param name="data"></param> /// <param name="printerName"></param> /// <param name="host"></param> /// <returns></returns> private static bool UpdateJobData(ref PrintJobData data, string printerName, string host) { bool updated = false; try { LogHelper.LogDebug("INNER START " + printerName); PrintQueue queue = GetPrintQueue(printerName, host); if (queue == null) { return(false); } queue.Refresh(); if (queue.NumberOfJobs > 0) { bool quit = false; while (!quit) { try { LogHelper.LogDebug("jobs " + queue.GetPrintJobInfoCollection().Count() + " | " + queue.NumberOfJobs); foreach (PrintSystemJobInfo info in queue.GetPrintJobInfoCollection()) { info.Refresh(); string docName = info.Name; int NumberOfPages = info.NumberOfPages; int xxx = info.NumberOfPagesPrinted; LogHelper.LogDebug("Printing " + info.IsPrinting + " | Paused " + info.IsPaused + " | Spooling " + info.IsSpooling + " | IsDeleting " + info.IsDeleting); LogHelper.LogDebug("pages " + NumberOfPages + " printed " + xxx); if (data.PrintJobTitle.Document == docName && data.PrintJobTitle.TotalPages < xxx) { data.PrintJobTitle.TotalPages = xxx; updated = true; } } quit = true; } catch (Exception ex) { queue.Refresh(); LogHelper.LogDebug("refresh"); WPFNotifier.Error(ex); } } } } catch (Exception ex) { WPFNotifier.Error(ex); } LogHelper.LogDebug("INNER END " + printerName); return(updated); }
private static Status CancelJob(PrintQueue printQueue, string uniqueFileName) { // If you do not "refresh" the print queue, then getting information about the jobs will fail. printQueue.Refresh(); PrintJobInfoCollection jobs = printQueue.GetPrintJobInfoCollection(); // Extension is pulled out because some applications omit the file extension when it creates the job name. string fileName = Path.GetFileNameWithoutExtension(uniqueFileName); PrintSystemJobInfo jobInfo = jobs.FirstOrDefault(j => j.Name.Contains(fileName)); jobInfo?.Cancel(); //wait for 20 seconds to check if the job got deleted DateTime expireTime = DateTime.Now + TimeSpan.FromSeconds(20); while (jobInfo.IsDeleting && DateTime.Now < expireTime) { Thread.Sleep(100); } if (jobInfo.IsDeleted) { return(Status.Passed); } return(Status.Failed); }
public static async Task JobStatus2(PrintQueue queue, int timeout, int interval, Action <int, int> action, CancellationToken token = default) { using (queue) { int previousTotal = 0, total = 0, previousPrinted = 0, printed = 0, i = 0, count = timeout * 1000 / interval; PrintJobInfoCollection jobs; var exists = new HashSet <int>(); while (!token.IsCancellationRequested) { queue.Refresh(); jobs = queue.GetPrintJobInfoCollection(); foreach (var item in jobs) { if (exists.Contains(item.JobIdentifier)) { continue; } exists.Add(item.JobIdentifier); } if (i++ > count) { return; } printed = (total = exists.Count) - jobs.Count(); if (previousPrinted != printed || previousTotal != total) { action(previousPrinted = printed, previousTotal = total); } await Task.Delay(interval); } } }
public static async Task JobStatus(PrintQueue queue, int timeout, int interval, Action <int> action) { using (queue) { int previousTotal = 0, total = 0, printed = 0, i = 0, count = timeout * 1000 / interval; while (true) { queue.Refresh(); total = queue.GetPrintJobInfoCollection().Count(); if (i++ > count) { return; } if (previousTotal != total) { i = 0; if (total < previousTotal) { printed += previousTotal - total; action(printed); } previousTotal = total; } await Task.Delay(interval); } } }
} // Fin DetailsPrint() /** * \brief Devuelve el nombre del puerto de la impresora. * \param Printer Nombre de la impresora de la que queremos obtener su puerto de impresión. * \return Nombre del puerto de la impresosa */ public static string PrinterPortName(string Printer) { PrintQueue PrintQueue; string PortName = ""; try { // Conectamos al servidor de Impresión local LocalPrintServer localPrintServer = new LocalPrintServer(); localPrintServer.Refresh(); // Abrimos la impresora PrintQueue = localPrintServer.GetPrintQueue(Printer); PrintQueue.Refresh(); // Obtenemos el nombre del puerto de la impresora Log.Debug(">>> Impresora(PrintQueue.Name): '" + PrintQueue.Name + "'"); PortName = PrintQueue.QueuePort.Name; Log.Info(">Puerto(printQueue.QueuePort.Name): '" + PrintQueue.QueuePort.Name + "'"); } catch (Exception e) { Log.Error("LocalPrinting.PrinterPortName. No hemos podido obtener el Nombre del puerto de Impresora.", e); } return(PortName); } //Fin PrinterProperties()
} //Fin PrinterProperties() /** * \brief Se establecen las propiedades de las impresoras gestionadas por el Servidor de impresión * \details La única propiedad que nos interesa establecer y mantener para poder monitorizar los trabajos de impresión es que * "Conserven los documentos después de su impresión" (Se conserven los ficheros de Spool) */ public static void ConfigurePrinters() { PrintQueue printQueue = null; LocalPrintServer localPrintServer; try { /// Accedemos al Servidor de Impresión Local localPrintServer = new LocalPrintServer(); Log.Debug(">>> Servidor de impresion: '" + localPrintServer.Name + "'"); /// Accedemos a las impresoras gestionadas por el Servidor de Impresión Local PrintQueueCollection localPrinterCollection = localPrintServer.GetPrintQueues(); System.Collections.IEnumerator localPrinterEnumerator = localPrinterCollection.GetEnumerator(); /// Recorremos todas las impresoras y revisamos su configuración para que se conserven los ficheros de Spool while (localPrinterEnumerator.MoveNext()) { printQueue = (PrintQueue)localPrinterEnumerator.Current; ApiImpresion PrintServer = new ApiImpresion(); PrintServer.KeepSpoolFiles(printQueue.Name); printQueue.Refresh(); } //while } catch (Exception e) { Log.Error(e); } //try } //ConfigurePrinters()
/// <summary> /// Gets the most recently submitted job /// </summary> /// <returns>The most recent job, or null if there are no jobs</returns> private PrintSystemJobInfo getLastJob() { DateTime latestJobTime = DateTime.Now; PrintSystemJobInfo latestJob = null; PrintQueue queue; foreach (string queueName in queueNamesToBlock) { queue = new PrintQueue(printServer, queueName); queue.Refresh(); foreach (var job in queue.GetPrintJobInfoCollection()) { job.Refresh(); var time = job.TimeJobSubmitted; if (time > latestJobTime) { latestJobTime = time; latestJob = job; } } } return(latestJob); }
private void cmdRefreshQueue_Click(object sender, RoutedEventArgs e) { if (lstQueues.SelectedValue != null) { PrintQueue queue = printServer.GetPrintQueue(lstQueues.SelectedValue.ToString()); queue.Refresh(); } }
public override void Start() { PrintServer PrintS = new PrintServer(); PrintQueue queue = new PrintQueue(PrintS, _window.PrintInformation.PrinterSettings.PrinterName); bool trouve; List <Document> tempDocToRemove; List <Document> tempDocInQueue; do { tempDocToRemove = new List <Document>(); tempDocInQueue = _window.DocumentsInQueue.ToList(); queue.Refresh(); foreach (Document theDoc in tempDocInQueue) { trouve = false; try { using (PrintJobInfoCollection jobinfo = queue.GetPrintJobInfoCollection()) { foreach (PrintSystemJobInfo job in jobinfo) { using (job) { if (job.Name.Contains(theDoc.Name)) { trouve = true; } } } } } catch (NullReferenceException) { } catch (RuntimeWrappedException) { } catch (InvalidOperationException) { } if (trouve == false) { tempDocToRemove.Add(theDoc); SetStatus(theDoc, State.Printed); } } foreach (Document theDoc in tempDocToRemove) { _window.DocumentsInQueue.Remove(theDoc); } } while (!_token.IsCancellationRequested || _stopWindow.Stopped); PrintS.Dispose(); queue.Dispose(); }
private void resumeAllJobs(PrintQueue queue) { queue.Refresh(); foreach (var job in queue.GetPrintJobInfoCollection()) { job.Refresh(); job.Resume(); } queue.Commit(); }
/// <summary> /// Cancel Print Job /// </summary> /// <param name="printName"></param> public static void ClearJob(string printName) { PrintServer localPrintServer = new LocalPrintServer(); PrintQueue pq = localPrintServer.GetPrintQueue(printName); pq.Refresh(); PrintJobInfoCollection allPrintJobs = pq.GetPrintJobInfoCollection(); foreach (PrintSystemJobInfo printJob in allPrintJobs) { printJob.Cancel(); } }
/// <summary> /// Pauses all of the current user's jobs in the queue, provided printing is disabled /// </summary> /// <param name="queue"></param> private void pauseAllJobs(PrintQueue queue) { queue.Refresh(); foreach (PrintSystemJobInfo job in queue.GetPrintJobInfoCollection()) { job.Refresh(); logJob(job.JobIdentifier, job.NumberOfPages, job.TimeJobSubmitted, job.Submitter); pauseJob(job); } queue.Commit(); }
//Not Use public List <string> PrintCheckAll() { List <string> list_print = new List <string>(); PrintServer myPS = new PrintServer(); PrintQueueCollection myPrintQueues = myPS.GetPrintQueues(); Console.WriteLine("\n\nKiem tra trang thai may in:\n\n"); int check_print = 0; foreach (PrintQueue pq2 in myPrintQueues) { if (!this.checkedList_mayin.CheckedItems.Contains(pq2.FullName)) { Console.WriteLine("Skip resume printer because not in the list."); continue; } Console.WriteLine(pq2.FullName); PrintQueue pq = new PrintQueue(myPS, pq2.FullName, PrintSystemDesiredAccess.AdministratePrinter); pq.Refresh(); string statusReport = pq.FullName + ": "; check_print = this.SpotTroubleUsingProperties(ref statusReport, pq); if (check_print == 0) { list_print.Add(pq.FullName); } else { if (!pq.IsOffline && !pq.IsBusy && !pq.IsPrinting && pq.NumberOfJobs > 0) { try { pq.Resume(); SetText("Đã cố gắng resume " + pq.NumberOfJobs + " bản in: " + pq2.FullName); } catch (Exception) { } } Console.WriteLine(statusReport); } }// end for each print queue return(list_print); }
/// <summary> /// 清理打印机队列中的JOb /// </summary> public void ClearJobs() { //清空打印机里残留的队列 PrintServer ps = new PrintServer(); PrintQueue queue = ps.GetPrintQueue(ConfigurationManager.AppSettings["printer"]); queue.Refresh(); PrintJobInfoCollection allPrintJobs = queue.GetPrintJobInfoCollection(); foreach (PrintSystemJobInfo printJob in allPrintJobs) { printJob.Cancel(); } //释放资源 ps.Dispose(); queue.Dispose(); allPrintJobs.Dispose(); }
public static bool CleanPrintQueue(string PrinterName) { try { LocalPrintServer _printServer = new LocalPrintServer(PrintSystemDesiredAccess.AdministratePrinter); PrintQueue printqueue = new PrintQueue(_printServer, PrinterName); printqueue.Refresh(); if (printqueue.NumberOfJobs != 0) { printqueue.Purge(); } return(true); } catch (Exception) { return(false); } }
/// <summary> /// Check for possible trouble states of a printer using its properties /// </summary> /// <param name="statusReport"></param> /// <param name="printQueue"></param> public static PrinterTrouble SpotPrinterTroubles(ref String statusReport, PrintQueue printQueue) { if (printQueue == null) { return(PrinterTrouble.None); } PrinterTrouble printerTrouble = PrinterTrouble.None; printQueue.Refresh(); if (!(printQueue.HasToner)) { printerTrouble |= PrinterTrouble.OutOfToner; statusReport = statusReport + "Is out of toner. "; } if (printQueue.IsOutOfPaper) { printerTrouble |= PrinterTrouble.OutOfPaper; statusReport = statusReport + "Is out of paper. "; } if (printQueue.IsOffline) { printerTrouble |= PrinterTrouble.Offline; statusReport = statusReport + "Offline. "; } if (printQueue.IsInError) { printerTrouble |= PrinterTrouble.Error; statusReport = statusReport + "Error. "; } if (printQueue.IsPaperJammed) { printerTrouble |= PrinterTrouble.PaperJammed; statusReport = statusReport + "Paper jammed. "; } return(printerTrouble); }
/// <summary> /// Kiểm tra tình trạng máy in. /// Nếu không có tài liệu chờ in trả về tình trạng sẵn sàng /// </summary> /// <param name="printer"></param> /// <returns></returns> private bool CheckPrinterStatus(PrintQueue printer) { try { if (printer == null) { return(false); } printer.Refresh(); //Nếu không có tài liệu chờ in trả về tình trạng sẵn sàng if (printer.NumberOfJobs <= 0) { return(true); } return(false); } catch (Exception) { return(false); } }
/// PrintTicket #region PrintTickets /// <summary> /// /// </summary> /// <param name="path"></param> /// <returns></returns> public static PrintTicket GetPrintTicketFromPrinter(string path, out PrintJobSettings printJobSettings) { printJobSettings = null; if (String.IsNullOrWhiteSpace(path)) { return(null); } PrintQueue printQueue = null; PrintServer printServer = new PrintServer(); // Retrieving collection of local printer on user machine PrintQueueCollection localPrinterCollection = printServer.GetPrintQueues(); foreach (var printer in localPrinterCollection) { if (printer.Name == path) { printQueue = (PrintQueue)printer; } } if (printQueue == null) { return(null); } printQueue.Refresh(); // Get default PrintTicket from printer //PrintTicket printTicket = printQueue.DefaultPrintTicket; PrintTicket printTicket = printQueue.UserPrintTicket; PrintJobSettings settings = printQueue.CurrentJobSettings; //System.Printing.PrintJobSettings printJobSettings = settings; return(printTicket); }
public string GetQueue() { string jobList = ""; LocalPrintServer ps = new LocalPrintServer(); // Get the default print queue PrintQueue pq = ps.DefaultPrintQueue; // foreach (PrintQueue pq in myPrintQueues) // { pq.Refresh(); PrintJobInfoCollection jobs = pq.GetPrintJobInfoCollection(); foreach (PrintSystemJobInfo job in jobs) { jobList = jobList + "\n\tQueue:" + pq.Name; jobList = jobList + "\n\tLocation:" + pq.Location; jobList = jobList + "\n\t\tJob: " + job.JobName + " ID: " + job.JobIdentifier; }// end for each print job // }// end for e return(jobList); }
private bool Print_Reset(string _ptr_device) { if (string.IsNullOrEmpty(_ptr_device)) { return(false); } if (!Exist_Printer(_ptr_device)) { return(false); } LocalPrintServer localPrintServer = new LocalPrintServer(); PrintQueue printQueue = localPrintServer.GetPrintQueue(_ptr_device); printQueue.Refresh(); if (printQueue.NumberOfJobs > 0) { PrintJobInfoCollection printJobInfoCollection = printQueue.GetPrintJobInfoCollection(); foreach (PrintSystemJobInfo item in printJobInfoCollection) { item.Cancel(); } } return(true); }
public override void Start() { _wait.Reset(); _inQueue = false; PrintServer PrintS = new PrintServer(); PrintQueue queue = new PrintQueue(PrintS, _window.PrintInformation.PrinterSettings.PrinterName); int trial = 0; do { trial++; queue.Refresh(); if (trial >= 3000 && trial < 6000) { RefreshList(_document); _window.Dispatcher.Invoke(new Action(() => { _stopWindow.skipVisibility(System.Windows.Visibility.Visible); })); SetStatus(_document, State.Searching); } else if (trial >= 6000) { SetStatus(_document, State.StillSearching); } try { if (queue.NumberOfJobs > 0) { using (PrintSystemJobInfo job = queue.GetPrintJobInfoCollection().Last()) { if (job.Name.Contains(_document.Name)) { _inQueue = true; SetStatus(_document, State.InQueue); log.Info(_document.Name + " has been queued"); } } } } catch (NullReferenceException) { } catch (RuntimeWrappedException) { } catch (InvalidOperationException) { } } while (!_inQueue && trial < 10000 && !_token.IsCancellationRequested && !_stopWindow.Skip); PrintS.Dispose(); queue.Dispose(); if (trial >= 10000) { SetStatus(_document, State.Error); log.Error(_document.Name + " has made an error"); if (!_window.Configuration.AutoRetry) { System.Media.SystemSounds.Beep.Play(); _window.Dispatcher.Invoke(new Action(() => { _stopWindow.retryVisibility(System.Windows.Visibility.Visible); _window.Activate(); _stopWindow.Activate(); })); _stopWindow.Retry.Reset(); _stopWindow.Retry.WaitOne(); } } if (_stopWindow.Skip) { SetStatus(_document, State.Skipped); log.Info(_document.Name + " has been skipped"); } }
string PrinterName = ConfigurationManager.AppSettings["QRPrinterName"];//"CUSTOM KPM150";//"Microsoft Print to PDF"; public Enums.PRINTER_STATE getStatusWithUsb() { try { string query = string.Format("SELECT * from Win32_Printer WHERE Name LIKE '%{0}'", PrinterName); using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(query)) using (ManagementObjectCollection coll = searcher.Get()) { try { foreach (ManagementObject printer in coll) { foreach (PropertyData property in printer.Properties) { if (property.Name == "WorkOffline") { if ((bool)property.Value) { return(Enums.PRINTER_STATE.ERROR); } else { var server = new LocalPrintServer(); PrintQueue queue = server.GetPrintQueue(PrinterName, new string[0] { }); queue.Refresh(); if (queue.IsOffline) { return(Enums.PRINTER_STATE.ERROR); } if (queue.IsPaused) { return(Enums.PRINTER_STATE.ERROR); } if (queue.IsOutOfPaper) { return(Enums.PRINTER_STATE.NO_PAPER); } if (queue.HasPaperProblem) { return(Enums.PRINTER_STATE.LOW_PAPER); } if (!queue.IsOffline) { return(Enums.PRINTER_STATE.OK); } if (!queue.IsOutOfPaper) { return(Enums.PRINTER_STATE.OK); } return(Enums.PRINTER_STATE.OTHER); } } } } return(Enums.PRINTER_STATE.ERROR); } catch (ManagementException ex) { return(Enums.PRINTER_STATE.ERROR); } } } catch (Exception ex) { return(Enums.PRINTER_STATE.ERROR); } }
private void Hodoo_SIP30C(DataTable dt, string BizCode, bool IsNewData) { DataTable mdt = dt.Copy(); for (int i = 0; i < mdt.Rows.Count; i++) { #region 카드발급프린터 대기열 작업완료시까지 기다림 using (LocalPrintServer localPrinterServer = new LocalPrintServer()) { PrintQueue printQueue = localPrinterServer.GetPrintQueue(PrintName); if (printQueue.NumberOfJobs > 0) { MessageBox.Show("인쇄 대기인 문서가 있습니다."); return; } localPrinterServer.Dispose(); } #endregion rPrintData = null; rPrintData = mdt.Rows[i]; //일반(사진) info.xpos = Convert.ToInt32(rPrintData["X_POS"].ToString().Trim()); info.ypos = Convert.ToInt32(rPrintData["Y_POS"].ToString().Trim()); info.xsize = Convert.ToInt32(rPrintData["X_SIZE"].ToString().Trim()); info.ysize = Convert.ToInt32(rPrintData["Y_SIZE"].ToString().Trim()); //일반(승산)-카드프린터 클래스 생성 info.bizcode = BizCode; info.membername = rPrintData["MEMBER_NAME_KOR"].ToString().Trim(); info.memberno = rPrintData["MEMBER_NO"].ToString().Trim(); info.memberphoto = rPrintData["PHOTO"] == DBNull.Value ? null : (Byte[])rPrintData["PHOTO"]; info.cardissueno = rPrintData["CARD_ISSUE_NO"].ToString().Trim(); //예외(승산)-카드프린터 클래스 생성 if (info.bizcode == "23") { info.commodity_accountcode = rPrintData["COMMODITY_ACCOUNT_CODE"].ToString().Trim(); info.gccode = rPrintData["GC_CODE"].ToString().Trim(); info.memberno = string.Format("{0}-{1}{2}", info.memberno.Trim().Substring(2, 6) , info.memberno.Trim().Substring(8, 2) , info.commodity_accountcode.Trim()); if (info.membername.Length == 3) { info.membername = String.Format("{0} {1} {2}", info.membername.Substring(0, 1), info.membername.Substring(1, 1), info.membername.Substring(2, 1)); } } //예외(대천)-카드프린터 클래스 생성 if (info.bizcode == "22") { info.registercode = rPrintData["REGISTER_CODE"].ToString().Trim(); info.printdate = DateTime.Today.ToString("yyyy.MM.dd"); if (info.memberno.Length == 10) { info.memberno = String.Format("{0}-{1}-{2}-{3}", info.memberno.Substring(0, 2), info.memberno.Substring(2, 2), info.memberno.Substring(4, 4), info.memberno.Substring(8, 2)); } //기명=N if (info.membername.Length == 3 && info.registercode == "N") { info.membername = String.Format("{0} {1} {2}", info.membername.Substring(0, 1), info.membername.Substring(1, 1), info.membername.Substring(2, 1)); } //무기명=U else { string strmemberName = info.membername; if (info.membername.Length > 11) { strmemberName = info.membername.Substring(0, 11); } info.printdate = info.printdate + (info.membername.Equals("") ? "" : " " + strmemberName); } } //예외(엘도라도)-카드프린터 클래스 생성 if (info.bizcode == "51") { info.membername = rPrintData["MEMBER_NAME_ENG"].ToString().Trim(); } //일반(대천) - 마그네틱엔코딩 info.mstrack1 = ""; info.mstrack2 = String.Format("{0}={1}", rPrintData["CARD_ISSUE_NO"].ToString().Trim(), rPrintData["MEMBER_NO"].ToString().Trim()); info.mstrack3 = ""; //예외(승산) - 마그네틱엔코딩 /*설명 : 1.승산 임시회원카드 = track1=골프혜택, track2=회원번호(8), track3="" * 2.승산 임시회원카드 = track1=회원번호(8)골프혜택, track2="", track3="" * 승산 임시회원카드는 정식카드 사용전까지 사용하며, * 정식 마그네틱 저장형식은 추후 협의후 결정(기본 = track2사용, 카드번호(10자리)=회원번호(10자리)) */ if (info.bizcode == "23") { info.mstrack1 = String.Format("{0}{1}", rPrintData["MEMBER_NO"].ToString().Trim().Substring(2, 8), rPrintData["GC_CODE"].ToString().Trim()); //rPrintData["GC_CODE"].ToString().Trim(); info.mstrack2 = ""; //rPrintData["CARD_ISSUE_NO"].ToString().Trim();//"";//String.Format("{0}", rPrintData["MEMBER_NO"].ToString().Trim().Substring(2, 8)); info.mstrack3 = ""; } if (!WriteMagnetic(IsNewData, info.mstrack1, info.mstrack2, info.mstrack3)) { return; } if (IsNewData) { Drawprint(PrintName); } suSender sender = new suSender { BizCode = BizCode, sucMode = IsNewData ? SucessMode.NewData : SucessMode.Magstripe }; bool IsSucess = true; using (LocalPrintServer localPrinterServer1 = new LocalPrintServer()) { PrintQueue printQueue = localPrinterServer1.GetPrintQueue(PrintName); int startTick = Environment.TickCount; bool isTimeOut = false; while (printQueue.NumberOfJobs > 0 & !(isTimeOut)) { printQueue.Refresh(); int currentTick = Environment.TickCount; if (currentTick - startTick > 60000) { isTimeOut = true; } System.Threading.Thread.Sleep(10); Application.DoEvents(); } if (isTimeOut) { PrintJobInfoCollection jobs = printQueue.GetPrintJobInfoCollection(); foreach (PrintSystemJobInfo job in jobs) { job.Cancel(); } int deleteStateTime = System.Environment.TickCount; string strmsg = "제한시간초과 - 인쇄가 완료되지 못했습니다. "; while ((System.Environment.TickCount - deleteStateTime) < 1000) { printQueue.Refresh(); } if (printQueue.NumberOfJobs > 0) { strmsg += "\n\r인쇄문서가 대기 중 입니다 . \n\r\n\r취소 후 다시 시도 하세요!"; } IsSucess = false; RaiseErrorEvent(new Exception(strmsg)); return; } if (IsSucess) { RaiseDataSucessEvent(sender, rPrintData); } } } }
/// <summary> /// Kiểm tra tình trạng máy in. /// Nếu không có tài liệu chờ in trả về tình trạng sẵn sàng /// </summary> /// <param name="printer"></param> /// <returns></returns> private bool CheckPrinterStatus(PrintQueue printer) { try { if (printer == null) return false; printer.Refresh(); //Nếu không có tài liệu chờ in trả về tình trạng sẵn sàng if (printer.NumberOfJobs <= 0) return true; return false; } catch (Exception) { return false; } }
/** \brief Detalles del Trabajo de Impresion * \param Printer Nombre de impresora * \param JobId Número de trabajo de impresión * \param PrintJob Estructura para almacenar las propiedades del trabajo de impresión, pasado por referencia * \details * Con este método recuperamos los detalles del trabajo de impresión: Cola, Número de Páginas, Tamaño página, Usuario, etc. * \remarks Hay que revisar si la propiedad PrintQueue.IsRawOnlyEnabled = False indica que el spool del trabajo * se almacena en formato EMF. */ public static void DetailsPrint(string Printer, string JobId, ref STRUCT_PRINT_JOB PrintJob) { PrintQueue ColaImpresion = null; PrintSystemJobInfo JobInfo = null; Log.Debug("========================================================================="); Log.Debug(" NAMESPACE System.Printing"); Log.Debug("========================================================================="); Log.Debug(""); /// Conectamos con el Servidor de impresión local LocalPrintServer ServidorImpresionLocal = null; try { ServidorImpresionLocal = new LocalPrintServer(); Log.Debug("==> Servidor de Impresión: " + ServidorImpresionLocal.Name); } catch (Exception e) { Log.Error("No se puede abrir el Servidor de Impresión Local: " + e); throw e; } /// Abrimos la impresora y su trabajo de Impresión pasados como argumentos al método Log.Debug("==> Trabajo de impresión: " + JobId + " a través de la Cola de Impresión: " + Printer); try { Log.Debug("Abrimos conexión con impresora: " + Printer); ColaImpresion = (PrintQueue)ServidorImpresionLocal.GetPrintQueue(Printer); Log.Debug("Recuperamos trabajo de Impresión: " + JobId); ColaImpresion.GetJob(Convert.ToInt32(JobId)); ColaImpresion.Refresh(); /// - Generamos log con las propiedades del Trabajo de Impresión if (ColaImpresion.IsRawOnlyEnabled) { Log.Debug("==> La cola de impresión sólo utiliza RAW."); } else { Log.Debug("==> La cola de impresión admite EMF."); } /// Se guarda en el log los detalles del trabajo de impresión Log.Debug("PageMediaSizeName: " + ColaImpresion.CurrentJobSettings.CurrentPrintTicket.PageMediaSize.PageMediaSizeName); Log.Debug("PageMediaSize: " + ColaImpresion.CurrentJobSettings.CurrentPrintTicket.PageMediaSize); Log.Debug("Width: " + ColaImpresion.CurrentJobSettings.CurrentPrintTicket.PageMediaSize.Width); Log.Debug("Height: " + ColaImpresion.CurrentJobSettings.CurrentPrintTicket.PageMediaSize.Height); Log.Debug("Número copias: " + ColaImpresion.CurrentJobSettings.CurrentPrintTicket.CopyCount); Log.Debug("OutputColor: " + ColaImpresion.CurrentJobSettings.CurrentPrintTicket.OutputColor); Log.Debug("PageOrientation: " + ColaImpresion.CurrentJobSettings.CurrentPrintTicket.PageOrientation); Log.Debug("Duplexing: " + ColaImpresion.CurrentJobSettings.CurrentPrintTicket.Duplexing); Log.Debug("OutputColor: " + ColaImpresion.CurrentJobSettings.CurrentPrintTicket.OutputColor); Log.Debug("=====> Propiedades JOB a través PrintSystemJobInfoFO ===="); JobInfo = PrintSystemJobInfo.Get(ColaImpresion, Convert.ToInt32(JobId)); Log.Debug("JobStatus: " + JobInfo.JobStatus); Log.Debug("Name: " + JobInfo.Name); Log.Debug("NumberOfPages: " + JobInfo.NumberOfPages); Log.Debug("NumberOfPagesPrinted: " + JobInfo.NumberOfPagesPrinted); Log.Debug("Submitter: " + JobInfo.Submitter); Log.Debug("TimeJobSubmitted: " + JobInfo.TimeJobSubmitted.ToString()); Log.Debug("JobSize: " + JobInfo.JobSize); /// - Almacenamos las propiedades del Trabajo de Impresión en el struct de entrada al método pasado por referencia PrintJob.F_PRINTJOB = JobInfo.TimeJobSubmitted.ToLocalTime().Day.ToString().PadLeft(2, '0') + "/" + JobInfo.TimeJobSubmitted.ToLocalTime().Month.ToString().PadLeft(2, '0') + "/" + JobInfo.TimeJobSubmitted.ToLocalTime().Year.ToString().PadLeft(4, '0') + " " + JobInfo.TimeJobSubmitted.ToLocalTime().Hour.ToString().PadLeft(2, '0') + ":" + JobInfo.TimeJobSubmitted.ToLocalTime().Minute.ToString().PadLeft(2, '0') + ":" + JobInfo.TimeJobSubmitted.ToLocalTime().Second.ToString().PadLeft(2, '0'); PrintJob.ID_JOBNAME = PrintJob.N_JOB.ToString().PadLeft(5, '0') + "_" + PrintJob.F_PRINTJOB; PrintJob.ID_FUENTE = "System.Printing"; PrintJob.ID_LOGIN = JobInfo.Submitter; PrintJob.ID_PRINTSERVER = ServidorImpresionLocal.Name; PrintJob.ID_DOCUMENT = JobInfo.Name; PrintJob.N_PAGES = JobInfo.NumberOfPages; PrintJob.N_PAGES_PRINTED = JobInfo.NumberOfPagesPrinted; PrintJob.N_LENGTH = (int)ColaImpresion.CurrentJobSettings.CurrentPrintTicket.PageMediaSize.Height; PrintJob.N_WIDTH = (int)ColaImpresion.CurrentJobSettings.CurrentPrintTicket.PageMediaSize.Width; PrintJob.ID_MEDIASIZE = ColaImpresion.CurrentJobSettings.CurrentPrintTicket.PageMediaSize.ToString(); // PageMediaSizeName; PrintJob.N_MEDIASIZE = (int)ColaImpresion.CurrentJobSettings.CurrentPrintTicket.PageMediaSize.PageMediaSizeName; PrintJob.N_ORIENTATION = (int)ColaImpresion.CurrentJobSettings.CurrentPrintTicket.PageOrientation; PrintJob.ID_ORIENTATION = ColaImpresion.CurrentJobSettings.CurrentPrintTicket.PageOrientation.ToString(); PrintJob.N_COPIES = (int)ColaImpresion.CurrentJobSettings.CurrentPrintTicket.CopyCount; PrintJob.ID_COLOR = ColaImpresion.CurrentJobSettings.CurrentPrintTicket.OutputColor.ToString(); PrintJob.N_COLOR = (int)ColaImpresion.CurrentJobSettings.CurrentPrintTicket.OutputColor; PrintJob.ID_DUPLEX = ColaImpresion.CurrentJobSettings.CurrentPrintTicket.Duplexing.ToString(); if (ColaImpresion.CurrentJobSettings.CurrentPrintTicket.Duplexing != null) { PrintJob.N_DUPLEX = (int)ColaImpresion.CurrentJobSettings.CurrentPrintTicket.Duplexing; } PrintJob.ID_STATUS = JobInfo.JobStatus.ToString(); // ?: Operador condicional ==> (condicion) ? valor_caso_verdadero : valor_caso_falso PrintJob.N_COLORPAGES = (PrintJob.ID_COLOR.ToUpper() == "COLOR") ? PrintJob.N_PAGES_PRINTED: 0; PrintJob.N_JOBSIZE = JobInfo.JobSize; } catch (Exception e) { Log.Error("No se puede abrir el trabajo de impresión: " + JobId + " a través de la Cola de Impresión: " + Printer); Log.Fatal("Comprobar que en la impresora: " + Printer + " se guardan los trabajos de impresión", e); throw e; } } // Fin DetailsPrint()