public static Dictionary<string, string> GetInputBins(string printerName)
        {
            Dictionary<string, string> inputBins = new Dictionary<string, string>();

            // get PrintQueue of Printer from the PrintServer
            LocalPrintServer printServer = new LocalPrintServer();
            PrintQueue printQueue = printServer.GetPrintQueue(printerName);

            // get PrintCapabilities of the printer
            MemoryStream printerCapXmlStream = printQueue.GetPrintCapabilitiesAsXml();

            // read the JobInputBins out of the PrintCapabilities
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(printerCapXmlStream);

            // create NamespaceManager and add PrintSchemaFrameWork-Namespace (should be on DocumentElement of the PrintTicket)
            // Prefix: psf NameSpace: xmlDoc.DocumentElement.NamespaceURI = "http://schemas.microsoft.com/windows/2003/08/printing/printschemaframework"
            XmlNamespaceManager manager = new XmlNamespaceManager(xmlDoc.NameTable);
            manager.AddNamespace(xmlDoc.DocumentElement.Prefix, xmlDoc.DocumentElement.NamespaceURI);

            // and select all nodes of the bins
            XmlNodeList nodeList = xmlDoc.SelectNodes("//psf:Feature[@name='psk:JobInputBin']/psfSurpriseption", manager);

            // fill Dictionary with the bin-names and values
            foreach (XmlNode node in nodeList)
            {
                inputBins.Add(node.LastChild.InnerText, node.Attributes["name"].Value);
            }

            return inputBins;
        }
Beispiel #2
0
        public YellowstonePathology.YpiConnect.Contract.MethodResult Print()
        {
            YellowstonePathology.YpiConnect.Contract.MethodResult methodResult = new Contract.MethodResult();
            YellowstonePathology.YpiConnect.Contract.MethodResult downloadResult = null;

            if (this.m_IsDownloaded == true)
            {
                downloadResult = new Contract.MethodResult();
                downloadResult.Success = true;
            }
            else
            {
                downloadResult = this.Download();
            }

            if (downloadResult.Success == true)
            {
                LocalPrintServer ps = new LocalPrintServer();
                PrintQueue pq = ps.DefaultPrintQueue;
                XpsDocumentWriter xpsdw = PrintQueue.CreateXpsDocumentWriter(pq);
                xpsdw.Write(this.m_XpsDocument.GetFixedDocumentSequence().DocumentPaginator);
                methodResult.Success = true;
            }
            else
            {
                methodResult.Success = false;
                methodResult.Message = downloadResult.Message;
            }

            return methodResult;
        }
 private void Window_Loaded(object sender, RoutedEventArgs e)
 {
     // select the default printer ...
     var defaultPrinter = new LocalPrintServer().DefaultPrintQueue;
     if (defaultPrinter != null)
     {
         CmbPrinters.SelectedValue = defaultPrinter.FullName;
     }
 }
Beispiel #4
0
 public Printer()
 {
     LocalPrintServer server = new LocalPrintServer();
     var queues = server.GetPrintQueues();            
     var queList = queues.
         Select(x => x.FullName).
         ToList();
     printers = new ObservableCollection<string>(queList);
     PrinterName = "FugaPrinter";                                
 }
        public PrintSettingsViewModel()
        {
            var lps = new LocalPrintServer();
            var queue = lps.GetPrintQueue("Microsoft XPS Document Writer");
            var pc = Capabilities.Load(queue.GetPrintCapabilitiesAsXml());
            printTicket = Ticket.Load(queue.DefaultPrintTicket.GetXmlStream());

            var mediaSizeFeature = pc.Get(Psk.PageMediaSize);
            MediaSizeDisplayName = mediaSizeFeature.Get(Psk.DisplayName)?.AsString();
            MediaSizeCapabilities = new ReactiveList<MediaSizeViewModel>(
                from option in mediaSizeFeature.Options()
                select new MediaSizeViewModel(option));

            MediaSize = MediaSizeCapabilities.First(ms =>
            {
                return ms.Option.Name == printTicket.Get(Psk.PageMediaSize)?.First()?.Name;
            });

            this.WhenAnyValue(x => x.MediaSize)
                .Skip(1)
                .Subscribe(ms =>
                {
                    printTicket = printTicket.Set(Psk.PageMediaSize, ms.Option);
                });

            var copies = pc.Get(Psk.JobCopiesAllDocuments);
            CopiesDisplayName = copies.Get(Psk.DisplayName)?.AsString();
            CopiesMax = (copies.Get(Psf.MaxValue)?.AsInt()).GetValueOrDefault(1);
            CopiesMin = (copies.Get(Psf.MinValue)?.AsInt()).GetValueOrDefault(1);
            CopiesMultiple = (copies.Get(Psf.Multiple)?.AsInt()).GetValueOrDefault(1);
            Copies = (copies.Get(Psf.DefaultValue)?.AsInt()).GetValueOrDefault(1);

            this.WhenAnyValue(x => x.Copies)
                .Skip(1)
                .Subscribe(cp =>
                {
                    printTicket = printTicket.Set(Psk.JobCopiesAllDocuments, cp);
                });

            IncreaseCopies = ReactiveCommand.Create(
                this.WhenAny(_ => _.Copies, x => x.Value < CopiesMax));
            IncreaseCopies.Subscribe(_ =>
            {
                Copies += CopiesMultiple;
            });

            DecreaseCopies = ReactiveCommand.Create(
                this.WhenAny(_ => _.Copies, x => x.Value > CopiesMin));
            DecreaseCopies.Subscribe(_AppDomain =>
            {
                Copies -= CopiesMultiple;
            });
        }
        private void MainWindow_OnLoaded(object sender, RoutedEventArgs e)
        {
            // the page to print -- this page uses a media print stylesheet
            Browser.Navigate(_homeUrl);
            ApplyScriptXLicense();

            // select the default printer ...
            var defaultPrinter = new LocalPrintServer().DefaultPrintQueue;
            if (defaultPrinter != null)
            {
                CmbPrinters.SelectedValue = defaultPrinter.FullName;
            }

        }
        /// <summary>
        /// Constructor de la ventana.
        /// </summary>
        /// <param name="sqlConn">Datos de la conexión a la base de datos</param>
        public SelectPrinter_Window(SqlConnection sqlConn)
        {
            this.InitializeComponent();

            //Centramos la ventana.
            WindowFormat.CenterWindowOnScreen(this);

            //Asignamos el valor de la conexión a nuestra variable de instancia.
            _sqlConn = sqlConn;

            //Creamos el servidor de impresión con privilegios de administrador.
            _printServer = new LocalPrintServer(PrintSystemDesiredAccess.AdministrateServer);

            //Rellenamos el ComboBox con las impresoras actuales.
            FillWithPrinters();
        }
 public static PrintQueue GetPrintQueue(string PrinterName)
 {
     LocalPrintServer pr = new LocalPrintServer();
     pr.Refresh();
     EnumeratedPrintQueueTypes[] enumerationFlags = {EnumeratedPrintQueueTypes.Local,
                                                     EnumeratedPrintQueueTypes.Connections,
                                                    };
     foreach (PrintQueue pq in pr.GetPrintQueues(enumerationFlags))
     {
         if (pq.Name == PrinterName)
         {
             return pq;
         }
     }
     return null;
 }
Beispiel #9
0
        public static void PrintXPS()
        {
            // Create print server and print queue.
            LocalPrintServer localPrintServer = new LocalPrintServer();
            PrintQueue defaultPrintQueue = LocalPrintServer.GetDefaultPrintQueue();

            try
            {
                // Print the Xps file while providing XPS validation and progress notifications.
                PrintSystemJobInfo xpsPrintJob = defaultPrintQueue.AddJob("Pawn Ticket", @"C:\Users\raymetz\Desktop\WPF Printing notes.xps", false);
            }
            catch (Exception e) // PrintJobException not found?
            {
                MessageBox.Show(e.InnerException.Message);
            }
        }
Beispiel #10
0
        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            //look for local and network printers
            EnumeratedPrintQueueTypes[] enumerationFlags = {

                    EnumeratedPrintQueueTypes.Local,

                    EnumeratedPrintQueueTypes.Connections
            };

            List<Printer> printers = vm.getPrinters();
            Printer target = printers.Where(p => p.Store == vm.store).SingleOrDefault();
            TargetPrinter.Text = target.PrinterName;
            
            bool bFound = false;
            LocalPrintServer localPrintServer = new LocalPrintServer();
            // Retrieving collection of local printer and remote printers
            PrintQueueCollection PrinterCollection =
                localPrintServer.GetPrintQueues(enumerationFlags);

          //  PrintQueueCollection PrinterCollection = new PrintServer(@"\\adac").GetPrintQueues(new[] {
          //EnumeratedPrintQueueTypes.Local, EnumeratedPrintQueueTypes.Connections});
            PrintQueue printq = null;
            foreach (PrintQueue printq1 in PrinterCollection)
            {
  //              MessageBox.Show(printq1.FullName);

                if ( string.Compare( printq1.FullName, target.PrinterName,true) == 0)
                {
                    printq = printq1;
                    bFound = true;
                }
            }
            if (!bFound)
            {
                MessageBox.Show(string.Format("Printer not found  {0}", target.PrinterName));
                this.Close();
                return;
            }
            PrintButton.Visibility = Visibility.Collapsed;
            TargetPrinter.Visibility = Visibility.Collapsed;
            PrintDialog pd = new PrintDialog();
            pd.PrintQueue = printq;
            pd.PrintVisual(UI, "On The Spot");
            this.Close();

        }
Beispiel #11
0
        static void Main(string[] args)
        {
            try
            {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
            }
            catch (Exception e)
            {
                Console.WriteLine("{0} Exception caught during startup", e);
                MessageBox.Show(String.Format("Exception caught during startup: {0}", e));
            }

            if (args.Length != 2)
            {
              Console.WriteLine("Usage: <printername> <xps file>");
              MessageBox.Show("Usage: <printername> <xps file>");
            }
            else
            {
                try
                {
                    string sPrinter = args[0];
                    string xpsDocPath = args[1]; // "c:\\test\\test.xps";

                    LocalPrintServer localPrintServer = new LocalPrintServer();
                    PrintQueue defaultPrintQueue = localPrintServer.GetPrintQueue(sPrinter);
                    if (defaultPrintQueue == null)
                    {
                        Console.WriteLine("Printer not found: " + sPrinter);
                        MessageBox.Show("Printer not found: " + sPrinter);
                    }
                    else
                    {
                        PrintSystemJobInfo xpsPrintJob = defaultPrintQueue.AddJob("Print", xpsDocPath, false);
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine("{0} Exception caught.", e);
                    MessageBox.Show(String.Format("Exception caught during printing: {0}", e));
                }
            }
            
            //Application.Run(new Form1());
        }
Beispiel #12
0
        public int GetNumberOfPrintTasks()
        {
            LocalPrintServer localServer = new LocalPrintServer();
            PrintQueueCollection queueCollection = localServer.GetPrintQueues();
            PrintQueue printQueue = null;

            foreach (PrintQueue pq in queueCollection)
            {
                printQueue = LocalPrintServer.GetDefaultPrintQueue();
            }

            int numTasks = 0;
            if (printQueue != null)
                numTasks = printQueue.NumberOfJobs;

            return numTasks;
        }
Beispiel #13
0
        public bool LoadPrintDialog(out PrintDialog dialog)
        {
            if (Dialog == null)
            {
                dialog = new PrintDialog();
                var printServer = new LocalPrintServer();
                PrintQueueCollection printQueuesOnLocalServer = printServer.GetPrintQueues();
                dialog.PrintQueue = printQueuesOnLocalServer.FirstOrDefault(printer => printer.Name == Name);
                Dialog = dialog;

            }
            else
            {
                dialog = Dialog;
            }

            return Dialog.PrintQueue != null;
        }
Beispiel #14
0
        /// <summary>
        /// PrintQueue
        /// </summary>
        /// <returns></returns>
        private PrintQueue DefaultPrintQueue()
        {
            Helpers.SecurityAssert();
            PrintQueue queue = null;

            try
            {
                queue = new LocalPrintServer().DefaultPrintQueue;
            }
            catch (PrintSystemException)
            {
                queue = null;
            }
            finally
            {
                Helpers.SecurityRevert();
            }

            return(queue);
        }
        /*-
         * private void printerTrays ()
         * {
         *  foreach (string p in PrinterSettings.InstalledPrinters)
         *  {
         *      PrinterSettings settings = new PrinterSettings { PrinterName = p };
         *
         *      //  Console.WriteLine ();
         *      //  Console.WriteLine (settings.PrinterName);
         *
         *      foreach (PaperSource paperSource in settings.PaperSources)
         *      {
         *      //  Console.WriteLine ("    PaperSource: Name = {0}, Kind = {1}, RawKind = {2}",
         *      //                    paperSource.SourceName, paperSource.Kind, paperSource.RawKind);
         *
         *          txtPaperSource.Text = paperSource.SourceName;
         *          txtKind.Text = paperSource.Kind.ToString ();
         *          txtRawKind.Text = paperSource.RawKind.ToString ();
         *
         *      }
         *  }
         * }
         */

        private void prtdata_01()
        {
            // Specify that the list will contain only the print queues that are installed as local and are shared
            EnumeratedPrintQueueTypes [] enumerationFlags = { EnumeratedPrintQueueTypes.Local,
                                                              EnumeratedPrintQueueTypes.Shared };

            LocalPrintServer printServer = new LocalPrintServer();

            //Use the enumerationFlags to filter out unwanted print queues
            PrintQueueCollection printQueuesOnLocalServer = printServer.GetPrintQueues(enumerationFlags);

            txtDiags.Text += "These are your shared, local print queues:\n\n";

            foreach (PrintQueue printer in printQueuesOnLocalServer)
            {
                txtDiags.Text += "\tThe shared printer " + printer.Name + " is located at " + printer.Location + "\n";
            }

            txtDiags.Text += "\n\n\n";
        }
Beispiel #16
0
 public PrintQueueCollection GetPrinterList(string printServer = "local")
 {
     if (printServer == "" || printServer == "local")
     {
         LocalPrintServer ps = new LocalPrintServer();
         printerList = ps.GetPrintQueues();
     }
     else
     {
         try
         {
             PrintServer ps = new PrintServer(printServer);
             printerList = ps.GetPrintQueues();
         }
         catch (Exception ex)
         {
         }
     }
     return(printerList);
 }
Beispiel #17
0
        public string GetQueue()
        {
            StringBuilder    jobList = new StringBuilder("Черга друку");
            LocalPrintServer ps      = new LocalPrintServer();

            // Get the default print queue
            //PrintQueue pq = ps.DefaultPrintQueue;
            foreach (PrintQueue pq in ps.GetPrintQueues())
            {
                jobList.Append("\n" + pq.FullName);
                pq.Refresh();
                PrintJobInfoCollection jobs = pq.GetPrintJobInfoCollection();
                jobList.Append($"\n\tQueue:{pq.Name} \tLocation:{ pq.Location}");
                foreach (PrintSystemJobInfo job in jobs)
                {
                    jobList.Append($"\nJob: {job.JobName} ID: {job.JobIdentifier} Document Name: {job.Name} Page:{job.NumberOfPages} Time:{job.TimeJobSubmitted}");
                }
            }
            return(jobList.ToString());
        }
Beispiel #18
0
        private PrintQueue AcquireDefaultPrintQueue()
        {
            PrintQueue result = null;

            SystemDrawingHelper.NewDefaultPrintingPermission().Assert();
            try
            {
                LocalPrintServer localPrintServer = new LocalPrintServer();
                result = localPrintServer.DefaultPrintQueue;
            }
            catch (PrintSystemException)
            {
                result = null;
            }
            finally
            {
                CodeAccessPermission.RevertAssert();
            }
            return(result);
        }
		/// <summary>
		/// PrintQueue
		/// </summary>
		/// <returns></returns>
		private PrintQueue DefaultPrintQueue()
		{
			new PrintingPermission(PrintingPermissionLevel.DefaultPrinting).Assert();
			PrintQueue queue = null;

			try
			{
				queue = new LocalPrintServer().DefaultPrintQueue;
			}
			catch (PrintSystemException)
			{
				queue = null;
			}
			finally
			{
				CodeAccessPermission.RevertAssert();
			}

			return queue;
		}
Beispiel #20
0
        public Print(ghostnet_wpf_example.MainWindow main_in, int num_pages)
        {
            InitializeComponent();

            m_ps = new PrinterSettings();
            main = main_in;

            this.Closing += new System.ComponentModel.CancelEventHandler(FakeWindowClosing);
            InitializeComponent();
            m_printServer     = new LocalPrintServer();
            m_selectedPrinter = LocalPrintServer.GetDefaultPrintQueue();
            m_ps.PrinterName  = m_selectedPrinter.FullName;
            m_pagedetails     = m_ps.DefaultPageSettings;


            xaml_rbAll.IsChecked = true;
            m_pages_setting      = PrintPages_t.ALL;

            xaml_autofit.IsChecked = false;

            m_numpages = num_pages;

            m_printcap = m_selectedPrinter.GetPrintCapabilities();

            m_trans_pap = new TranslateTransform(0, 0);
            m_trans_doc = new TranslateTransform(0, 0);
            m_isrotated = false;

            /* Data range case */
            m_range_pages = new PrintRanges(m_numpages);
            m_page_scale  = 1.0;

            m_numcopies = 1;

            m_invalidTo   = true;
            m_invalidFrom = true;
            m_from        = -1;
            m_to          = -1;

            InitPrinterList();
        }
Beispiel #21
0
        /// <summary>
        /// 設定を読み出して、印刷設定を取得する
        /// </summary>
        /// <param name="ps">ローカルプリントサーバー</param>
        /// <param name="pq">設定を入力するプリントキューへの参照</param>
        /// <param name="pt">設定を入力するプリントチケットへの参照</param>
        /// <returns>true:全て設定成功 false:システムデフォルト設定が混じった</returns>
        protected bool GetPrinterSetting(LocalPrintServer ps, ref PrintQueue pq, ref PrintTicket pt)
        {
            if (Settings.PrinterName != "")
            {
                try
                {
                    //PrinterName設定のキューを取得する
                    pq = ps.GetPrintQueue(Settings.PrinterName);

                    //PrintTicket設定に中身があれば取得する
                    if (Settings.PrintTicketSetting != null)
                    {
                        pt = Settings.PrintTicketSetting.Clone();

                        //両方取得できたらアプリ設定からの印刷設定取得に成功として返す
                        return(true);
                    }
                    else
                    {
                        //中身がなければキューのデフォルト設定を取得する
                        pt = ps.DefaultPrintQueue.UserPrintTicket.Clone();
                    }
                }
                catch
                {
                    //失敗したらシステムのデフォルト設定を取得する
                    MessageBox.Show("設定したプリンタが見つかりません");
                    pq = ps.DefaultPrintQueue;
                    pt = ps.DefaultPrintQueue.UserPrintTicket.Clone();
                }
            }
            else
            {
                //プリンタ設定がなければシステムのデフォルト設定を取得する
                pq = ps.DefaultPrintQueue;
                pt = ps.DefaultPrintQueue.UserPrintTicket.Clone();
            }

            //ここまで来たらアプリ設定からの印刷設定取得に失敗している
            return(false);
        }
Beispiel #22
0
        public void AddJob()
        {
            var options = new NotifyOptions
            {
                Types = new List <NotifyOptionsType>
                {
                    new NotifyOptionsType
                    {
                        Fields = new List <ushort> {
                            (ushort)JOB_NOTIFY_FIELD.JOB_NOTIFY_FIELD_PRINTER_NAME
                        },
                        Type = NOTIFY_TYPE.JOB_NOTIFY_TYPE,
                    }
                }
            };

            using var changeNotification = ChangeNotification.Create(0, NameConstants.PrinterName, PRINTER_NOTIFY_CATEGORY.PRINTER_NOTIFY_CATEGORY_ALL, options);

            using var localPrintServer = new LocalPrintServer();
            var defaultPrintQueue = localPrintServer.GetPrintQueue(NameConstants.PrinterName);

            var myPrintJob = defaultPrintQueue.AddJob();

            // Write a Byte buffer to the JobStream and close the stream
            var myByteBuffer = Encoding.Unicode.GetBytes("This is a test string for the print job stream.");

            using var myStream = myPrintJob.JobStream;
            myStream.Write(myByteBuffer, 0, myByteBuffer.Length);
            myStream.Close();

            using var myStream2 = myPrintJob.JobStream;
            myStream2.Write(myByteBuffer, 0, myByteBuffer.Length);
            myStream2.Close();

            changeNotification.WaitHandle.WaitOne();

            var changes = changeNotification.FindNextPrinterChangeNotification(false);

            Assert.That(changes.Data.Count, Is.EqualTo(1));
            Assert.That(changes.Data.First().Value, Is.EqualTo(NameConstants.PrinterName));
        }
Beispiel #23
0
        public Form1()
        {
            InitializeComponent();

            LocalPrintServer ps = new LocalPrintServer();

            foreach (string printer in System.Drawing.Printing.PrinterSettings.InstalledPrinters)
            {
                listBox1.Items.Add(printer);
            }
            // Get the default print queue
            // Create a new instance of the PrinterSettings class, which
            // we will only use to fetch the default printer name
            System.Drawing.Printing.PrinterSettings newSettings = new System.Drawing.Printing.PrinterSettings();

            //get printer default from config.ini
            String defaultPrinterINI = MyIni.Read("Default", "printer");
            int    index             = -1;

            if (defaultPrinterINI != "")
            {
                index = listBox1.FindString(defaultPrinterINI);
            }

            //MessageBox.Show("impresora: " + defaultPrinter +" index:" + index, "ERROR");

            //if no ini, get printer default system
            if (index < 0)
            {
                index = listBox1.FindString(newSettings.PrinterName);
            }

            if (index > -1)
            {
                listBox1.SetSelected(index, true);
            }

            //    var result = MessageBox.Show(pq.ToString(), pq.ToString(),
            //                            MessageBoxButtons.YesNo,
            //                            MessageBoxIcon.Question);
        }
Beispiel #24
0
        private void btnPrint_Click(object sender, RoutedEventArgs e)
        {
            PrintDialog print = new PrintDialog();
            //打印队列
            LocalPrintServer     localPrintServer = new LocalPrintServer();
            PrintQueueCollection printQueues      = localPrintServer.GetPrintQueues(new[] { EnumeratedPrintQueueTypes.Local, EnumeratedPrintQueueTypes.Connections });

            if (printQueues == null || !printQueues.Any())
            {
                MessageBox.Show("PrintQueues为空,打印出错!");
                return;
            }

            //设置打印机信息
            PrintQueue queue = printQueues.FirstOrDefault(p => p.Name.Equals(txtPrinterName.Text));

            if (queue == null)
            {
                MessageBox.Show("获取打印机驱动失败!");
            }
            print.PrintQueue = queue;

            double height = imgQrCode.Height;
            double width  = imgQrCode.Width;

            //打印纸张方向
            if ("0".Equals("0"))
            {
                print.PrintTicket.PageOrientation = System.Printing.PageOrientation.Landscape;  //竖印
                print.PrintTicket.PageMediaSize   = new PageMediaSize(width, height);
            }
            else
            {
                print.PrintTicket.PageMediaSize   = new PageMediaSize(height, width);
                print.PrintTicket.PageOrientation = System.Printing.PageOrientation.Portrait;  //横印
            }

            #region 直接打印
            print.PrintVisual(imgQrCode, "测试");
            #endregion
        }
 public CertificationPrintSetWin(List <CertificationBO> certs, IEnumerable <ProductShow> products, List <ProductUniqueCodeMapping> pumapping = null)
 {
     InitializeComponent();
     tbPrintQua.Visibility = gvDatas.Visibility = System.Windows.Visibility.Collapsed;
     btnPrint.Click       += (sender, e) =>
     {
         RadButton  btn = (RadButton)sender;
         PrintQueue defaultPrintQueue = LocalPrintServer.GetDefaultPrintQueue();
         var        printDialog       = new PrintDialog();
         printDialog.PrintQueue = defaultPrintQueue;
         int quaSuccessful = 0;
         foreach (ProductShow product in products)
         {
             var cert = certs.Find(o => o.StyleCode == product.StyleCode);
             if (cert != null)
             {
                 cert.Quantity          = product.Quantity;
                 cert.Color             = string.Format("[{0}]{1}", product.ColorCode, VMGlobal.Colors.Find(o => o.Code == product.ColorCode).Name);
                 cert.Size              = string.Format("[{0}]{1}", VMGlobal.Sizes.Find(o => o.Name == product.SizeName).Code, product.SizeName);
                 panelPrint.DataContext = cert;
                 try
                 {
                     this.Print(product.ProductID,
                                printDialog,
                                pumapping == null ? Enumerable.Range(1, product.Quantity).Select(o => product.ProductCode).ToList() : pumapping.Where(o => o.ProductID == product.ProductID).Select(o => o.UniqueCode).ToList(),
                                ref quaSuccessful);
                 }
                 catch (Exception ex)
                 {
                     MessageBox.Show("打印出现异常,错误信息:" + ex.Message);
                     break;
                 }
             }
             else
             {
                 MessageBox.Show("款式" + product.StyleCode + "的合格证信息不存在.");
             }
         }
         MessageBox.Show("合格证打印并保存成功" + quaSuccessful + "份");
     };
 }
        private void _pnlPrinting_OnIsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            ContentPresenter cp = (ContentPresenter)sender;
            var ef = ((MainWindow)Application.Current.MainWindow).Data.EditorFrame;

            if (ef == null || ef.XmlEditor == null || ef.XSDocument == null)
            {
                cp.Content = new Label {
                    Content = "No file loaded"
                };
                return;
            }

            PageSettings pageSettings = new PageSettings {
                Margins = new Margins(40, 40, 40, 40)
            };

            PrintQueue  printQueue  = LocalPrintServer.GetDefaultPrintQueue();
            PrintTicket printTicket = printQueue.DefaultPrintTicket;

            PrintPreviewControl printPreview = new PrintPreviewControl();

            printPreview.DocumentViewer.FitToMaxPagesAcross(1);

            printPreview.DocumentViewer.PrintQueue = printQueue;

            if (pageSettings.Landscape)
            {
                printTicket.PageOrientation = PageOrientation.Landscape;
            }

            printPreview.DocumentViewer.PrintTicket = printTicket;
            printPreview.DocumentViewer.PrintQueue.DefaultPrintTicket.PageOrientation = printTicket.PageOrientation;

            printPreview.LoadDocument(Printing.CreateDocumentPaginatorToPrint(ef.XmlEditor, pageSettings, printTicket, ef.XSDocument.Filename));

            // this is stupid, but must be done to view a whole page:
            DocumentViewer.FitToMaxPagesAcrossCommand.Execute("1", printPreview.DocumentViewer);

            cp.Content = printPreview;
        }
Beispiel #27
0
        private static void ListPrinterQueuesToConsole()
        {
            Logger.AddMessage("LISTING_PRINTERS");

            try
            {
                using (PrintServer printServer = new LocalPrintServer())
                {
                    List <PrintQueue> printers = printServer.GetPrintQueues().ToList();
                    foreach (PrintQueue printer in printers)
                    {
                        Console.WriteLine($"{printer.Name} | {printer.NumberOfJobs} | {printer.QueueStatus}");
                        Logger.AddMessage($"{printer.Name} | {printer.NumberOfJobs} | {printer.QueueStatus}");
                    }
                }
            }
            catch (Exception ex1)
            {
                Logger.AddMessage($"EXCEPTION_USING_PRINTSERVER\n" + ex1.ToString());
            }
        }
Beispiel #28
0
        AcquireDefaultPrintQueue()
        {
            PrintQueue printQueue = null;

            try
            {
                LocalPrintServer server = new LocalPrintServer();
                printQueue = server.DefaultPrintQueue;
            }
            catch (PrintSystemException)
            {
                //
                // It is entirely possible for there to be no "default" printer.  In this case,
                // the printing system throws an exception.  We do not want this to propagate
                // up.  Instead, returning null is fine.
                //
                printQueue = null;
            }

            return(printQueue);
        }
Beispiel #29
0
        FromLocalServer <P>(Func <PrintQueue, P> printerFromPrintQueue)
            where P : class
        {
            var server = new LocalPrintServer();
            var printQueueCollection = server.GetPrintQueues();

            var disposable =
                new AnonymousDisposable(() =>
            {
                server.Dispose();
                printQueueCollection.Dispose();
            });

            var queues       = printQueueCollection.Cast <PrintQueue>().ToArray();
            var defaultIndex = DefaultIndex(queues, server.DefaultPrintQueue);

            var printers       = queues.Select(printerFromPrintQueue).ToArray();
            var defaultPrinter = defaultIndex >= 0 ? printers[defaultIndex] : null;

            return(new PrinterSelector <P>(printers, defaultPrinter, disposable));
        }
        public static void Print(ref Grid fwe, string PrinterName)
        {
            LocalPrintServer printServer = new LocalPrintServer();


            Size visualSize = new Size(fwe.ActualWidth, fwe.ActualHeight);


            DrawingVisual visual = PrintControlFactory.CreateDrawingVisual(fwe, fwe.ActualWidth, fwe.ActualHeight);


            SUT.PrintEngine.Paginators.VisualPaginator page = new SUT.PrintEngine.Paginators.VisualPaginator(visual, visualSize, new Thickness(0, 0, 0, 0), new Thickness(0, 0, 0, 0));
            page.Initialize(false);

            PrintDialog pd = new PrintDialog();

            pd.PrintQueue = printServer.GetPrintQueue(PrinterName);


            pd.PrintDocument(page, "");
        }
Beispiel #31
0
 public static PrintQueue GetPrinter(string printerName = null)
 {
     try
     {
         PrintQueue selectedPrinter = null;
         if (!string.IsNullOrEmpty(printerName))
         {
             var printers = new LocalPrintServer().GetPrintQueues();
             selectedPrinter = printers.FirstOrDefault(p => p.Name == printerName);
         }
         else
         {
             selectedPrinter = LocalPrintServer.GetDefaultPrintQueue();
         }
         return(selectedPrinter);
     }
     catch
     {
         return(null);
     }
 }
Beispiel #32
0
        /// <summary>МЕТОД Быстрая Печать</summary>
        public void MyPrintNow()
        {
            PrintDialog _PrintDialog = new PrintDialog();

            _PrintDialog.PrintQueue           = LocalPrintServer.GetDefaultPrintQueue();
            _PrintDialog.UserPageRangeEnabled = true;
            //_PrintDialog.PrintTicket.PageOrientation = PageOrientation.Landscape;
            try
            {
                DocumentPaginator _Paginator = this.Document.DocumentPaginator;
                if (_PrintDialog.PageRangeSelection == PageRangeSelection.UserPages)
                {
                    _Paginator = new UserPrint(this.Document.DocumentPaginator, _PrintDialog.PageRange);
                }
                _PrintDialog.PrintDocument(_Paginator, "BazisWPF");
            }
            catch
            {
                MessageBox.Show("Ошибка Печати");
            }
        }
Beispiel #33
0
        }// end:CreateFixedDocumentSequencePrintTicket()

        // ------------------ CreateFixedDocumentPrintTicket ------------------
        /// <summary>
        ///   Creates a FixedDocument compatible PrintTicket.</summary>
        /// <param name="isLandscaped">
        ///   true to output in landscape; false to output in portrait.</param>
        /// <returns>
        ///   A FixedDocument compatible PrintTicket.</returns>
        private PrintTicket CreateFixedDocumentPrintTicket(bool isLandscaped)
        {
            // Create a local print server
            LocalPrintServer ps = new LocalPrintServer();

            // Get the default print queue
            PrintQueue pq = ps.DefaultPrintQueue;

            // Get the default user print ticket
            PrintTicket pt = pq.UserPrintTicket;

            // Set Duplexing value for the document
            pt.Duplexing = Duplexing.TwoSidedLongEdge;

            if (isLandscaped)
            {
                pt.PageOrientation = PageOrientation.Landscape;
            }

            return(pt);
        }// end:CreateFixedDocumentPrintTicket()
Beispiel #34
0
        /// <summary>
        /// Чтение состояния принтера.
        /// </summary>
        /// <returns>список текущих задач</returns>
        public static List <PrintInfo> Request()
        {
            var jobs = new List <PrintInfo>();

            try
            {
                var server = new LocalPrintServer();
                var queue  = server.DefaultPrintQueue;
                if (queue != null)
                {
                    foreach (var job in queue.GetPrintJobInfoCollection())
                    {
                        jobs.Add(new PrintInfo(job));
                    }
                }
            }
            catch
            { }

            return(jobs);
        }
Beispiel #35
0
        //Funciona, pero dependiendo de la impresora sólo muestra que está imprimiendo aunque la impresora no tenga papel,
        //no tenga tinta, etc. porque ya lo muestra con los drivers propios en vez de mostrarlos en la cola de impresión.
        /// <summary>
        /// Método que accede a la cola de impresión de Windows y recoge un trabajo que envía a Trabajos()
        /// </summary>
        /// <returns></returns>
        public string impCheck()
        {
            estadoActualImpresora = "";
            LocalPrintServer     printServer = new LocalPrintServer();
            PrintQueueCollection printQueues = printServer.GetPrintQueues();

            foreach (PrintQueue pq in printQueues)
            {
                pq.Refresh();
                PrintJobInfoCollection pCollection = pq.GetPrintJobInfoCollection();
                foreach (PrintSystemJobInfo trabajo in pCollection)
                {
                    trabajo.Refresh();
                    if (Trabajos(trabajo))
                    {
                        timer.Change(Timeout.Infinite, Timeout.Infinite);
                    }
                }
            }
            return(estadoActualImpresora);
        }
        public static void Print(Grid grd)
        {
            PrintDialog printDialog = new PrintDialog();

            if (printDialog.ShowDialog() == true)
            {
                //grd.LayoutTransform = new ScaleTransform(5, 5);

                grd.Measure(new System.Windows.Size(printDialog.PrintableAreaWidth, double.PositiveInfinity));

                grd.Arrange(new Rect(grd.DesiredSize));

                grd.UpdateLayout();

                printDialog.PrintTicket.PageMediaSize = new PageMediaSize(printDialog.PrintableAreaWidth, grd.ActualHeight);

                printDialog.PrintQueue = LocalPrintServer.GetDefaultPrintQueue();

                printDialog.PrintVisual(grd, "Check");
            }
        }
Beispiel #37
0
        private PrintQueue GetPrinter(string printerName)
        {
            if (string.IsNullOrEmpty(printerName))
            {
                return(LocalPrintServer.GetDefaultPrintQueue());
            }

            using (var printServer = new PrintServer())
            {
                using (var printQueues = printServer.GetPrintQueues())
                {
                    var pq = printQueues.FirstOrDefault(p => p.FullName == printerName);
                    if (pq != null)
                    {
                        return(pq);
                    }
                }
            }

            return(LocalPrintServer.GetDefaultPrintQueue());
        }
Beispiel #38
0
        public void Print(Object obj)
        {
            if (obj is UserControl userControl)
            {
                using (LocalPrintServer ps = new LocalPrintServer())
                {
                    PrintQueue    pq            = ps.DefaultPrintQueue;
                    PageMediaSize pageMediaSize = pq.UserPrintTicket.PageMediaSize;

                    FixedDocument document = new FixedDocument();

                    if (pageMediaSize.Width.HasValue && pageMediaSize.Height.HasValue)
                    {
                        document.DocumentPaginator.PageSize = new Size(pageMediaSize.Width.Value, pageMediaSize.Height.Value);
                    }

                    if (userControl.Content is Viewbox viewBox)
                    {
                        viewBox.Width = document.DocumentPaginator.PageSize.Width;
                    }

                    FixedPage page = new FixedPage
                    {
                        Width  = document.DocumentPaginator.PageSize.Width,
                        Height = document.DocumentPaginator.PageSize.Height,
                        HorizontalAlignment = HorizontalAlignment.Center
                    };

                    page.Children.Add(userControl);

                    document.Pages.Add(new PageContent
                    {
                        Child = page
                    });

                    XpsDocumentWriter xpsdw = PrintQueue.CreateXpsDocumentWriter(pq);
                    xpsdw.Write(document.DocumentPaginator);
                }
            }
        }
        private void SetDocumentSize()
        {
            PrintQueue printQueue = null;

            LocalPrintServer localPrintServer = new LocalPrintServer();

            // Retrieving collection of local printer on user machine
            PrintQueueCollection localPrinterCollection =
                localPrintServer.GetPrintQueues();

            System.Collections.IEnumerator localPrinterEnumerator =
                localPrinterCollection.GetEnumerator();

            if (localPrinterEnumerator.MoveNext())
            {
                // Get PrintQueue from first available printer
                printQueue = (PrintQueue)localPrinterEnumerator.Current;
                PrintTicket ticket = printQueue.DefaultPrintTicket;
                if (cmboOrientation.SelectedIndex == 0)
                {
                    ticket.PageOrientation = PageOrientation.Landscape;
                }
                else
                {
                    ticket.PageOrientation = PageOrientation.Portrait;
                }
                System.Printing.PrintCapabilities capabilities = printQueue.GetPrintCapabilities(ticket);
                double scale = Math.Min(capabilities.PageImageableArea.ExtentWidth / this.ActualWidth, capabilities.PageImageableArea.ExtentHeight /
                    this.ActualHeight);

                Size sz = new Size(capabilities.PageImageableArea.ExtentWidth, capabilities.PageImageableArea.ExtentHeight);

                mDoc.PageHeight = sz.Height;
                mDoc.PageWidth = sz.Width;
                mDoc.PagePadding = new Thickness(50);
                mDoc.ColumnGap = 0;
                mDoc.ColumnWidth = sz.Width;

            }
        }
 /// <summary>
 /// Show print dialog or try use default printer when useDefaultPrinter param set to true.
 /// <para/>
 /// Return false on error or when user pushed Cancel.
 /// </summary>
 public bool SelectPrinter(bool useDefaultPrinter = false)
 {
     if (_printDialog == null)
     {
         _printDialog = new PrintDialog();
     }
     try
     {
         if (useDefaultPrinter)
         {
             _printDialog.PrintQueue = LocalPrintServer.GetDefaultPrintQueue();
         }
         // pDialog.PrintQueue == null when default printer is not selected in system
         if (_printDialog.PrintQueue == null || !useDefaultPrinter)
         {
             // Show print dialog
             if (_printDialog.ShowDialog() != true)
             {
                 return(false);
             }
         }
         if (_printDialog.PrintQueue == null)
         {
             throw new Exception("Printer error");
         }
         // Get default printer settings
         //_printDialog.PrintTicket = _printDialog.PrintQueue.DefaultPrintTicket;
     }
     catch (Exception ex)
     {
         MessageBox.Show(ex.Message);
         return(false);
     }
     PrintTicket        = _printDialog.PrintTicket;
     TicketCapabilities = _printDialog.PrintQueue.GetPrintCapabilities(PrintTicket);
     PageSize           = new Size((double)TicketCapabilities.OrientedPageMediaWidth,
                                   (double)TicketCapabilities.OrientedPageMediaHeight);
     SetPageMargins(PageMargins);     // Update margins if too small
     return(true);
 }
Beispiel #41
0
        private void CalculateSize(FixedPage fixedPage)
        {
            PrintQueue        printQueue   = LocalPrintServer.GetDefaultPrintQueue();
            PrintCapabilities capabilities = printQueue.GetPrintCapabilities();

            //get scale of the print wrt to screen of WPF visual
            double scale = Math.Min(capabilities.PageImageableArea.ExtentWidth / fixedPage.ActualWidth, capabilities.PageImageableArea.ExtentHeight / fixedPage.ActualHeight);

            //Transform the Visual to scale
            fixedPage.LayoutTransform = new ScaleTransform(scale, scale);

            //get the size of the printer page
            var sz = new Size(capabilities.PageImageableArea.ExtentWidth, capabilities.PageImageableArea.ExtentHeight);

            //update the layout of the visual to the printer page size.
            fixedPage.Measure(sz);
            double x = capabilities.PageImageableArea.OriginWidth;
            double y = capabilities.PageImageableArea.OriginHeight;

            fixedPage.Arrange(new Rect(new Point(x, y), sz));
            fixedPage.UpdateLayout();
        }
Beispiel #42
0
        static void Main(string[] args)
        {
            //<SnippetListSubsetOfPrintQueues>
            // Specify that the list will contain only the print queues that are installed as local and are shared
            EnumeratedPrintQueueTypes[] enumerationFlags = { EnumeratedPrintQueueTypes.Local,
                                                             EnumeratedPrintQueueTypes.Shared };

            LocalPrintServer printServer = new LocalPrintServer();

            //Use the enumerationFlags to filter out unwanted print queues
            PrintQueueCollection printQueuesOnLocalServer = printServer.GetPrintQueues(enumerationFlags);

            Console.WriteLine("These are your shared, local print queues:\n\n");

            foreach (PrintQueue printer in printQueuesOnLocalServer)
            {
                Console.WriteLine("\tThe shared printer " + printer.Name + " is located at " + printer.Location + "\n");
            }
            Console.WriteLine("Press enter to continue.");
            Console.ReadLine();
            //</SnippetListSubsetOfPrintQueues>
        }
Beispiel #43
0
        private void GetPrinters()
        {
            LocalPrintServer localPrintServer = new LocalPrintServer();
            // Retrieving collection of local printers on user's machine
            PrintQueueCollection localPrinterCollection = localPrintServer.GetPrintQueues();

            System.Collections.IEnumerator localPrinterEnumerator = localPrinterCollection.GetEnumerator();
            int        index   = 0;
            int        defindx = -1;
            PrintQueue printer = LocalPrintServer.GetDefaultPrintQueue();

            while (localPrinterEnumerator.MoveNext())
            {
                printers.Items.Add(((PrintQueue)localPrinterEnumerator.Current).FullName);
                if (((PrintQueue)localPrinterEnumerator.Current).FullName == printer.FullName)
                {
                    defindx = index;
                }
                index++;
            }
            printers.SelectedIndex = defindx;
        }
Beispiel #44
0
        private PrintQueue GetPrintQueue(string printerName)
        {
            PrintServer server = null;

            if (printerName.StartsWith(@"\\", StringComparison.InvariantCulture))
            {
                int indexOfSecondSlash = printerName.IndexOf('\\', 2);
                if (indexOfSecondSlash > 2)
                {
                    string serverName = printerName.Substring(0, indexOfSecondSlash);
                    printerName = printerName.Substring(indexOfSecondSlash + 1);
                    server      = new PrintServer(serverName);
                }
            }

            if (server == null)
            {
                server = new LocalPrintServer();
            }

            return(server.GetPrintQueue(printerName));
        }
Beispiel #45
0
        private void GetPrintDialog()
        {
            var         localPrintServer            = new LocalPrintServer();
            var         localPrinterQueueCollection = localPrintServer.GetPrintQueues();
            var         printerQueue = localPrinterQueueCollection.FirstOrDefault();
            PrintTicket printTicket  = null;

            if (null != printerQueue)
            {
                printTicket = printerQueue.DefaultPrintTicket;
            }

            _printDialog = new PrintDialog
            {
                PrintTicket = printTicket ?? new PrintTicket
                {
                    PageOrientation = PageOrientation.Portrait,                  //TODO-Print-Configuration : PageOrientation
                    CopyCount       = 1,
                    PageMediaSize   = new PageMediaSize(PageMediaSizeName.ISOA4) //TODO-Print-Configuration : PageMediaSize
                }
            };
        }
Beispiel #46
0
        public static void Print(List<object> printCollection, 
            String FinalTargetFileName, String HeadLineText, String PrintPageOrientation = "Portrait")
            {

            PrintDialog PrtDialog = new PrintDialog();
            LocalPrintServer LPS = new LocalPrintServer();
            PrintQueue DefaultPrinterQueue = LocalPrintServer.GetDefaultPrintQueue();
            PrintTicket DefaultTicket = DefaultPrinterQueue.DefaultPrintTicket;
            PrintCapabilities DefaultCapabilities = DefaultPrinterQueue.GetPrintCapabilities(DefaultTicket);

            if (PrintPageOrientation == "Landscape")
                PrtDialog.PrintTicket.PageOrientation = PageOrientation.Landscape;
            else
                PrtDialog.PrintTicket.PageOrientation = PageOrientation.Portrait;

            PAPER_SIZE_WIDTH = PrtDialog.PrintableAreaWidth;
            PAPER_SIZE_HEIGHT = PrtDialog.PrintableAreaHeight;
            TOP_MARGIN = PrtDialog.PrintableAreaHeight * 0.08;
            SIDE_MARGIN = PrtDialog.PrintableAreaWidth * 0.08;

            double MaxOWidth = PAPER_SIZE_WIDTH - (2 * SIDE_MARGIN);
            double MaxOHeight = PAPER_SIZE_HEIGHT - (2 * TOP_MARGIN) - 20;

            FixedDocument PageDocumentToPrint = new FixedDocument();
            DefinitionsForPrintWithXAMLControls XAMLDefinitionsForOnePage = GenerateNewContent(PageDocumentToPrint);
            ObservableCollection<object> PageCollection = XAMLDefinitionsForOnePage.GlobalContainer.ItemsSource as ObservableCollection<object>;
            int NumberOfPages = CreatePages (XAMLDefinitionsForOnePage, PageDocumentToPrint, MaxOHeight, printCollection,
                PageCollection, HeadLineText);



            XpsDocument XpsDoc = new XpsDocument(FinalTargetFileName, FileAccess.Write);
            XpsDocumentWriter XpsWriter = XpsDocument.CreateXpsDocumentWriter(XpsDoc);
            XpsWriter.Write(PageDocumentToPrint.DocumentPaginator);
            XpsDoc.Close();
		
            }
        private void OnPrint(object sender, RoutedEventArgs e)
        {
            var dlg = new PrintDialog();
            if (dlg.ShowDialog() == true)
            {
                dlg.PrintVisual(canvas1, "Print Demo");

            }


            // PrintServer printServer = new PrintServer(@"\\treslunas\laserjet");
            var printServer = new LocalPrintServer();

            PrintQueue queue = printServer.DefaultPrintQueue;


            PrintTicket ticket = queue.DefaultPrintTicket;
            PrintCapabilities capabilities = queue.GetPrintCapabilities(ticket);
            if (capabilities.DuplexingCapability.Contains(Duplexing.TwoSidedLongEdge))
                ticket.Duplexing = Duplexing.TwoSidedLongEdge;
            if (capabilities.InputBinCapability.Contains(InputBin.AutoSelect))
                ticket.InputBin = InputBin.AutoSelect;
            if (capabilities.MaxCopyCount > 3)
                ticket.CopyCount = 3;
            if (capabilities.PageOrientationCapability.Contains(PageOrientation.Landscape))
                ticket.PageOrientation = PageOrientation.Landscape;
            if (capabilities.PagesPerSheetCapability.Contains(2))
                ticket.PagesPerSheet = 2;
            if (capabilities.StaplingCapability.Contains(Stapling.StapleBottomLeft))
                ticket.Stapling = Stapling.StapleBottomLeft;

            XpsDocumentWriter writer = PrintQueue.CreateXpsDocumentWriter(queue);
            writer.Write(canvas1, ticket);


        }
 private static void WorkerMethodShared(object state)
 {
     Logger.GetInstance().Debug("Started Printing for MyDLP printer: " + sharedPrinterName);
     PrintQueue pQueue = null;
     try
     {
         PrinterController controller = PrinterController.getInstance();
         LocalPrintServer pServer = new LocalPrintServer();
         PrintQueueCollection qCollection = pServer.GetPrintQueues();
         foreach (PrintQueue q in qCollection)
         {
             //Find mathing non secure printer
             if (q.Name == sharedPrinterName)
             {
                 pQueue = q;
             }
         }
         if (pQueue == null)
             throw new Exception("Unable to find a matching non secure printer for mydlp printer: " + sharedPrinterName);
         Logger.GetInstance().Debug("Adding print job on real printer: " + pQueue.Name +
             ", path:" + sharedXpsPath + ", sharedJobID:" + sharedJobId);
         if (WaitForFile(sharedXpsPath))
         {
             pQueue.AddJob(sharedJobId, sharedXpsPath, false);
             Thread.Sleep(1000);
             Logger.GetInstance().Debug("Removing:" + sharedXpsPath);
             File.Delete(sharedXpsPath);
             Logger.GetInstance().Debug("Finished Printing");
         }
         else
         {
             Logger.GetInstance().Debug("WorkerMethodShared WaitForFile failed for xps file");
         }
     }
     catch (Exception e)
     {
         Logger.GetInstance().Error("WorkerMethodShared Exception" + e);
         if (e.InnerException != null)
         {
             Logger.GetInstance().Error(e.InnerException.Message + e.InnerException.StackTrace);
         }
     }
 }
 private static void WorkerMethodLocal(object state)
 {
     Logger.GetInstance().Debug("Started Printing for MyDLP printer: " + localPrinterName);
     PrintQueue pQueue = null;
     try
     {
         PrinterController controller = PrinterController.getInstance();
         if (controller.IsPrinterConnection(localPrinterName))
         {
             //It will be printerd remotely
             //It is a network printer connection on local computer
             PrinterController.PrinterConnection connection = controller.GetPrinterConnection(localPrinterName);
             IPAddress[] addresslist = Dns.GetHostAddresses(connection.server);
             Logger.GetInstance().Debug("Initiating remote print remoteprinter: " +
                 connection.name + " on server:" + connection.server + "of File:" + localXpsPath);
             SeapClient.InitiateRemotePrint(localJobId, connection.name, addresslist[0].ToString(), localXpsPath);
         }
         else
         {
             //It is a local printer
             LocalPrintServer pServer = new LocalPrintServer();
             PrintQueueCollection qCollection = pServer.GetPrintQueues();
             foreach (PrintQueue q in qCollection)
             {
                 //Find mathing non secure printer
                 if (PrinterController.GetSecurePrinterName(q.Name) == localPrinterName)
                 {
                     pQueue = q;
                 }
             }
             if (pQueue == null)
                 throw new Exception("Unable to find a matching non secure printer for mydlp printer: " + localPrinterName);
             Logger.GetInstance().Debug("Adding print job on real printer: " + pQueue.Name +
                 ", path:" + localXpsPath + ", jobID:" + localJobId);
             if (WaitForFile(localXpsPath))
             {
                 pQueue.AddJob(localJobId, localXpsPath, false);
                 Thread.Sleep(1000);
                 Logger.GetInstance().Debug("Removing:" + localXpsPath);
                 File.Delete(localXpsPath);
                 File.Delete(metaPath);
                 Logger.GetInstance().Debug("Finished Printing");
             }
             else
             {
                 Logger.GetInstance().Debug("WorkerMethodLocal WaitForFile failed for xps file");
             }
         }
     }
     catch (Exception e)
     {
         Logger.GetInstance().Error("WorkerMethod Exception" + e);
         if (e.InnerException != null)
         {
             Logger.GetInstance().Error(e.InnerException.Message + e.InnerException.StackTrace);
         }
     }
 }
        private static void CheckForSharedPrinters()
        {
            if (checkingPrinters)
            {
                return;
            }
            else
            {
                try
                {
                    checkingPrinters = true;
                    Logger.GetInstance().Debug("CheckForSharedPrinters");
                    PrintServer pServer = new LocalPrintServer();
                    sharedLocalPrinters = new ArrayList();

                    foreach (PrintQueue queue in pServer.GetPrintQueues())
                    {
                        if (queue.IsShared)
                        {
                            sharedLocalPrinters.Add(queue.Name);
                        }
                    }
                    if (sharedLocalPrinters.Count > 0)
                    {
                        if (!hasSharedPrinter)
                        {
                            //has shared printer
                            hasSharedPrinter = true;
                            StartSharedPrinterServerListener();
                        }
                    }
                    else
                    {
                        if (hasSharedPrinter)
                        {
                            //has no shared printer
                            hasSharedPrinter = false;
                            StopSharedPrinterServerListener();
                        }
                    }
                    checkingPrinters = false;
                }
                catch (Exception ex)
                {
                    checkingPrinters = false;
                    Logger.GetInstance().Error("CheckForSharedPrinters exception:" + ex);
                }
            }
        }
        private void PrintAll_OnClick(object sender, RoutedEventArgs e)
        {
            if (!LabelImages.HasContent())
            {
                ModernDialog.ShowMessage(@"An error occurred. The labels could not be printed.", "Error", MessageBoxButton.OK, Window.GetWindow(this));
            }
            else
            {
                foreach (var label in LabelImages)
                {
                    var printer = new LocalPrintServer().GetPrintQueue(label.Template.Printer);

                    var dialog = new PrintDialog
                    {
                        PrintQueue = printer
                    };

                    var vis = new DrawingVisual();
                    var dc = vis.RenderOpen();
                    dc.DrawImage(label.Bitmap.ToBitmapImage(), new Rect { Width = label.Bitmap.Width, Height = label.Bitmap.Height });
                    dc.Close();


                    dialog.PrintVisual(vis, label.Template.FriendlyName);
                }
            }
        }
        private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
        {
            var printerString = ((Button) sender).Tag.ToString();

            if (string.IsNullOrEmpty(printerString))
            {
                ModernDialog.ShowMessage(@"No printer is associated with this label. Please add one in the Edit Labels tab.", "Error", MessageBoxButton.OK, Window.GetWindow(this));
            }
            else
            {
                var selectedDisplayLabel  = LabelImages.SingleOrDefault(n => n.Template.TemplateName == printerString);

                if (selectedDisplayLabel == null)
                {
                    ModernDialog.ShowMessage(@"An error occurred. The requested label could not be printer.", "Error", MessageBoxButton.OK, Window.GetWindow(this));
                    return;
                }

                var printer = new LocalPrintServer().GetPrintQueue(selectedDisplayLabel.Template.Printer);

                var dialog = new PrintDialog
                {
                    PrintQueue = printer
                };

                var vis = new DrawingVisual();
                var dc = vis.RenderOpen();
                dc.DrawImage(selectedDisplayLabel.Bitmap.ToBitmapImage(), new Rect { Width = selectedDisplayLabel.Bitmap.Width, Height = selectedDisplayLabel.Bitmap.Height });
                dc.Close();


                dialog.PrintVisual(vis, selectedDisplayLabel.Template.FriendlyName);

            }
        }
        private void BeginPrint(IProgress<PrintProgressValue> progress)
        {
            Services.NewStudentIdServicesClient service = new Services.NewStudentIdServicesClient();
            LocalPrintServer lps = new LocalPrintServer();
            PrintQueue pq = lps.DefaultPrintQueue;
            try
            {
                PrintProgressValue progressValue = new PrintProgressValue();
                progressValue.MaxValue = printDataTable.Rows.Count;
                foreach (DataRow dr in printDataTable.Rows)
                {
                    //标识开始打印状态
                    printState = PrintState.正在打印;
                    //如果点击了取消则退出打印循环
                    if (isCancel) break;

                    pq.Refresh();
                    //控制打印机任务最多只能有2个
                    while (pq.NumberOfJobs > 1 &!isCancel)
                    {
                        pq.Refresh();
                    }
                    DataTable dt = printDataTable.Clone();
                    dt.TableName = "Student";
                    dt.ImportRow(dr);
                    //dr["打印状态"] = "正在打印";
                    //获取学生照片
                    Byte[] bytes = service.GetStudentImage(dr["考生号"].ToString());
                    if (bytes != null)
                    {
                        MemoryStream ms = new MemoryStream();
                        ms.Write(bytes, 0, bytes.Length);
                        //打印照片
                        PrintHelper.Print(dt, templateFile, ms);
                    }
                    else PrintHelper.Print(dt, templateFile);
                    //更新数据库
                    NewStudentIdModel model = service.GetModelById(int.Parse(dr["ID"].ToString()));
                    if (model.DYXH == 0)
                    {
                        //设置打印序号
                        model.DYXH = service.GetMaxPrintNum(int.Parse(SystemConfig.CurrentYear)) + 1;
                    }
                    //3表示通知书和邮寄单都打印
                    switch (printType)
                    {
                        case PrintType.通知书打印:
                            {
                                if (model.DYBZ != 1 || model.DYBZ != 3)
                                    model.DYBZ = ((int)printType) + model.DYBZ;
                            }; break;
                        case PrintType.邮寄单打印:
                            {
                                if (model.DYBZ != 2 || model.DYBZ != 3)
                                    model.DYBZ = ((int)printType) + model.DYBZ;
                            }; break;
                    }
                    service.NewStudentIdUpdate(model);
                    if (progress != null)
                    {
                        progressValue.CurrentValue++;
                        progress.Report(progressValue);
                    }
                }
                //dr["打印状态"] = "打印完成";
            }
            finally
            {
                //标识开始打印状态
                printState = PrintState.完成打印;
                service.Close();
            }
        }
        public void LocalPrinterRemoveHandler()
        {
            Logger.GetInstance().Debug("LocalPrinterRemoveHandler started");
            LocalPrintServer pServer = new LocalPrintServer();
            PrintQueueCollection queueCollection = pServer.GetPrintQueues();

            String fallbackDefaultSecurePrinterName = "";

            foreach (PrintQueue mQueue in queueCollection)
            {
                if (mQueue.QueueDriver.Name == MyDLPDriver ||
                    mQueue.QueuePort.Name == "MyDLP")
                {
                    bool exists = false;

                    //Check if it is a shared printer
                    foreach (PrinterConnection connection in printerConnections)
                    {
                        if (connection.secureName == mQueue.Name)
                        {
                            //found a secure printer for non-local printer skipping;
                            exists = true;
                            fallbackDefaultSecurePrinterName = mQueue.Name;
                        }
                    }

                    //Check if there is a non-secure printer for for this printer
                    foreach (PrintQueue queue in queueCollection)
                    {
                        if (queue.QueueDriver.Name != MyDLPDriver ||
                            queue.QueuePort.Name != "MyDLP")
                        {
                            if (mQueue.Name == GetSecurePrinterName(queue.Name))
                            {
                                exists = true;
                                fallbackDefaultSecurePrinterName = mQueue.Name;
                            }
                        }
                    }
                    if (!exists)
                    {
                        MyDLPEP.PrinterUtils.RemovePrinter(mQueue.Name);

                        MyDLPEP.SessionUtils.ImpersonateActiveUser();
                        String defaultPrinterName = MyDLPEP.PrinterUtils.GetDefaultSystemPrinter();
                        MyDLPEP.SessionUtils.StopImpersonation();
                        if (mQueue.Name == defaultPrinterName)
                        {
                            //Real default printer removed do something
                            if (fallbackDefaultSecurePrinterName != "")
                            {
                                MyDLPEP.SessionUtils.ImpersonateActiveUser();
                                MyDLPEP.PrinterUtils.SetDefaultSystemPrinter(fallbackDefaultSecurePrinterName);
                                MyDLPEP.SessionUtils.StopImpersonation();
                            }
                            else
                            {
                                //there is no fall back printer
                                MyDLPEP.PrinterUtils.SetDefaultSystemPrinter("");
                            }
                        }
                    }
                }
            }
        }
        private void AddSecurePrinterForConnection(PrinterConnection connection)
        {
            try
            {
                LocalPrintServer pServer = new LocalPrintServer();

                bool exists = false;

                foreach (PrintQueue queue in pServer.GetPrintQueues())
                {
                    if (queue.Name == connection.secureName)
                    {
                        exists = true;
                    }
                }

                if (!exists)
                {
                    pServer.InstallPrintQueue(connection.secureName,
                    MyDLPDriver,
                    new String[] { "MyDLP" },
                   "winprint",
                    PrintQueueAttributes.Direct);
                }

                printerConnections.Add(connection);
            }
            catch (Exception ex)
            {
                Logger.GetInstance().Error("AddSecurePrinterForConnection: " + connection + " " + ex.Message + " " + ex.StackTrace);
            }
        }
 private void RemoveSecurePrinterForConnection(PrinterConnection connection)
 {
     try
     {
         LocalPrintServer pServer = new LocalPrintServer();
         MyDLPEP.PrinterUtils.RemovePrinter(connection.secureName);
     }
     catch (Exception ex)
     {
         Logger.GetInstance().Error("RemoveSecurePrinterForConnection: " + connection + " " + ex.Message + " " + ex.StackTrace);
     }
 }
        private void RemoveLocalSecurePrinters()
        {
            lock (this)
            {
                if (changingLocalPrinters)
                {
                    return;
                }
                else changingLocalPrinters = true;
            }
            bool defaultPrinterReverted = false;
            try
            {
                Logger.GetInstance().Debug("RemoveSecurePrinters started");

                MyDLPEP.SessionUtils.ImpersonateActiveUser();
                String defaultPrinterName = MyDLPEP.PrinterUtils.GetDefaultSystemPrinter();
                MyDLPEP.SessionUtils.StopImpersonation();

                Logger.GetInstance().Info("Default printer :" + defaultPrinterName);

                LocalPrintServer pServer = new LocalPrintServer();
                PrintQueueCollection queueCollection = pServer.GetPrintQueues();
                foreach (PrintQueue queue in queueCollection)
                {
                    //Logger.GetInstance().Debug("Process printer queue: " + queue.Name
                    //   + " driver: " + queue.QueueDriver.Name + " port: " + queue.QueuePort.Name);

                    if (queue.QueueDriver.Name == MyDLPDriver ||
                        queue.QueuePort.Name == "MyDLP")
                    {
                        Logger.GetInstance().Debug("A secure printer found removing " + queue.Name);

                        if (queue.Name.StartsWith(PrinterPrefix))
                        {
                            PrintQueueCollection qCollection = pServer.GetPrintQueues();
                            foreach (PrintQueue q in qCollection)
                            {
                                //Find mathing non secure printer
                                if (GetSecurePrinterName(q.Name) == queue.Name)
                                {
                                    if (printerPermissions.ContainsKey(queue.Name))
                                    {
                                        MyDLPEP.PrinterUtils.SetPrinterSecurityDescriptor(
                                           q.Name,
                                           printerPermissions[queue.Name]);
                                    }
                                    else
                                    {
                                        //fallback make printer usable
                                        MyDLPEP.PrinterUtils.SetPrinterSecurityDescriptor(
                                            q.Name,
                                            BuiltinAdminsPrinterSecurityDescriptor + authUserPrint);
                                    }

                                    if (queue.Name == defaultPrinterName)
                                    {
                                        //Revert default printer
                                        MyDLPEP.SessionUtils.ImpersonateActiveUser();
                                        if (MyDLPEP.PrinterUtils.SetDefaultSystemPrinter(q.Name))
                                        {
                                            defaultPrinterReverted = true;
                                            MyDLPEP.SessionUtils.StopImpersonation();
                                            Logger.GetInstance().Debug("Set default printer as:" + q.Name + "successfully");
                                        }
                                        else
                                        {
                                            MyDLPEP.SessionUtils.StopImpersonation();
                                            Logger.GetInstance().Error("Failed to set default printer as:" + q.Name);
                                        }
                                    }

                                }
                            }
                        }

                        MyDLPEP.PrinterUtils.TakePrinterOwnership(queue.Name);
                        if (Environment.UserInteractive)
                        {
                            MyDLPEP.PrinterUtils.SetPrinterSecurityDescriptor(queue.Name, BuiltinAdminsPrinterSecurityDescriptor);
                        }
                        else
                        {
                            MyDLPEP.PrinterUtils.SetPrinterSecurityDescriptor(queue.Name, SystemPrinterSecurityDescriptor);
                        }
                        MyDLPEP.PrinterUtils.RemovePrinter(queue.Name);

                    }
                    else
                    {
                        //Logger.GetInstance().Debug("A non-secure printer found " + queue.Name);

                        if (spooledNativePrinters.Contains(queue.Name))
                        {
                            Logger.GetInstance().Debug("Reenabling spooling " + queue.Name);
                            MyDLPEP.PrinterUtils.SetPrinterSpoolMode(queue.Name, true);
                            spooledNativePrinters.Remove(queue.Name);
                        }
                    }
                }

                if (!defaultPrinterReverted)
                {
                    //Error occured set a valid default printer from available printers
                    MyDLPEP.SessionUtils.ImpersonateActiveUser();

                    MyDLPEP.PrinterUtils.SetDefaultSystemPrinter("");
                    MyDLPEP.SessionUtils.StopImpersonation();
                }

            }
            catch (Exception e)
            {
                Logger.GetInstance().Error("Remove secure printers failed: " + e);
            }
            finally
            {
                Logger.GetInstance().Debug("RemoveSecurePrinters ended");
                lock (this)
                {
                    changingLocalPrinters = false;
                }
            }
        }
        private void InstallLocalSecurePrinters()
        {
            bool change = false;
            lock (this)
            {
                if (changingLocalPrinters)
                {
                    return;
                }
                else changingLocalPrinters = true;
            }
            try
            {
                Logger.GetInstance().Debug("InstallSecurePrinters started");

                LocalPrintServer pServer = new LocalPrintServer();
                PrintQueue mydlpQueue;
                PrintQueueCollection queueCollection = pServer.GetPrintQueues();
                String securityDesc;

                foreach (PrintQueue queue in queueCollection)
                {
                    //Logger.GetInstance().Debug("Process printer queue: " + queue.Name
                    //    + " driver: " + queue.QueueDriver.Name + " port: " + queue.QueuePort.Name);

                    if (queue.QueueDriver.Name != MyDLPDriver ||
                        queue.QueuePort.Name != "MyDLP")
                    {

                        //check if secure printer already exists
                        bool exists = false;
                        PrintQueueCollection collection = pServer.GetPrintQueues();
                        foreach (PrintQueue q in queueCollection)
                        {
                            if (q.Name == GetSecurePrinterName(queue.Name))
                            {
                                if (q.QueueDriver.Name == MyDLPDriver && q.QueuePort.Name == "MyDLP")
                                {
                                    exists = true;
                                }
                                else
                                {
                                    //fix any incorrect ports
                                    Logger.GetInstance().Debug(q.QueueDriver.Name + q.QueuePort.Name);
                                    MyDLPEP.PrinterUtils.RemovePrinter(q.Name);
                                }
                            }
                        }

                        if (!exists)
                        {
                            Logger.GetInstance().Debug(
                                "Not a secure printer installing installing secure version:" + queue.Name + PrinterPrefix);
                            try
                            {
                                String mydlpQueueName = GetSecurePrinterName(queue.Name);
                                mydlpQueue = pServer.InstallPrintQueue(mydlpQueueName,
                                    MyDLPDriver,
                                    new String[] { "MyDLP" },
                                    "winprint",
                                    PrintQueueAttributes.Direct);
                                change = true;
                                MyDLPEP.PrinterUtils.TakePrinterOwnership(queue.Name);
                                securityDesc = MyDLPEP.PrinterUtils.GetPrinterSecurityDescriptor(queue.Name);

                                //save original permissions
                                if (!printerPermissions.ContainsKey(mydlpQueue.Name))
                                {
                                    printerPermissions.Add(mydlpQueue.Name, securityDesc);
                                }

                                if (Environment.UserInteractive)
                                {
                                    MyDLPEP.PrinterUtils.SetPrinterSecurityDescriptor(queue.Name, BuiltinAdminsPrinterSecurityDescriptor);
                                    MyDLPEP.PrinterUtils.SetPrinterSecurityDescriptor(mydlpQueue.Name, BuiltinAdminsPrinterSecurityDescriptor + authUserPrint);
                                }
                                else
                                {
                                    MyDLPEP.PrinterUtils.SetPrinterSecurityDescriptor(queue.Name, SystemPrinterSecurityDescriptor);
                                    MyDLPEP.PrinterUtils.SetPrinterSecurityDescriptor(mydlpQueue.Name, SystemPrinterSecurityDescriptor + authUserPrint);
                                }

                                //This is netiher required nor working in windows 7
                                if (!queue.IsDirect && Configuration.GetOs() == Configuration.OsVersion.XP)
                                {
                                    Logger.GetInstance().Debug("Found spooling native printer " + queue.Name);
                                    MyDLPEP.PrinterUtils.SetPrinterSpoolMode(queue.Name, false);
                                    spooledNativePrinters.Add(queue.Name);
                                }
                            }
                            catch (Exception e)
                            {
                                Logger.GetInstance().Debug("Unable to process non-secure printer " + queue.Name
                                    + " error:" + e);
                            }
                        }
                    }
                }

                //On any change set default printer to MyDLP counterpart
                if (change)
                {
                    //Give windows time to update default printer
                    Thread.Sleep(2000);
                    UpdateDefaultPrinter();
                }
            }
            catch (Exception e)
            {
                Logger.GetInstance().Error("InstallSecurePrinters failed: " + e);
            }
            finally
            {
                Logger.GetInstance().Debug("InstallSecurePrinters ended");
                lock (this)
                {
                    changingLocalPrinters = false;
                }
            }
        }
Beispiel #59
0
 public void Print(object fileName)
 {
     Document doc = null;
     try
     {
         doc = myWord.Documents.Open(FileName: fileName, Visible: false);
         doc.ActiveWindow.PrintOut();
     }
     catch (Exception e)
     {
         if (doc != null) doc.Close();
         ErrorLog.AddNewEntry(e.Message);
         DeleteAllFilesOnTempDirectory();
         throw new Exception("Ошибка при открытии документа");
     }
     doc.Close();
     LocalPrintServer ps = new LocalPrintServer();
     while (ps.DefaultPrintQueue.NumberOfJobs > 0)//TODO:Получить очередь печати принтера и найти норм вирт принтер
     {
         ps.Refresh();
     }
     DeleteAllFilesOnTempDirectory(fileName.ToString());
 }
            AcquirePrintQueue(
                string printerName 
                ) 
            {
                PrintQueue printQueue = null; 

                EnumeratedPrintQueueTypes[] types = new EnumeratedPrintQueueTypes[] {
                    EnumeratedPrintQueueTypes.Local,
                    EnumeratedPrintQueueTypes.Connections 
                };
 
                // 
                // This forces us to acquire the cached version of the print queues.
                // This theoretically should prevent crashing in the printing system 
                // since all it is doing is reading the registry.
                //
                PrintQueueIndexedProperty[] props = new PrintQueueIndexedProperty[] {
                    PrintQueueIndexedProperty.Name, 
                    PrintQueueIndexedProperty.QueueAttributes
                }; 
 
                (new PrintingPermission(PrintingPermissionLevel.DefaultPrinting)).Assert();  //BlessedAssert
                try 
                {
                    //
                    // Get the PrintQueue instance for the printer
                    // 
                    using (LocalPrintServer server = new LocalPrintServer())
                    { 
                        foreach (PrintQueue queue in server.GetPrintQueues(props, types)) 
                        {
                            if (printerName.Equals(queue.FullName, StringComparison.OrdinalIgnoreCase)) 
                            {
                                printQueue = queue;
                                break;
                            } 
                        }
                    } 
                    if (printQueue != null) 
                    {
                        printQueue.InPartialTrust = true; 
                    }
                }
                finally
                { 
                    PrintingPermission.RevertAssert();
                } 
 
                return printQueue;
            }