Ejemplo n.º 1
0
        private void PrintOrderCore <ReportType>(decimal widthByInch, decimal heightByInch) where ReportType : UserControl, new()
        {
            var        ps = new LocalPrintServer();
            PrintQueue pq = null;

            try
            {
                pq = ps.GetPrintQueue("VP-D800N");                                                                                //指定したプリンタ
                pq.UserPrintTicket.PageMediaSize  = new PageMediaSize((double)(widthByInch * 96m), (double)(heightByInch * 96m)); //pixcel指定。1pixel=1/96inchだそうで
                pq.UserPrintTicket.PageResolution = new PageResolution(96, 96);
                pq.UserPrintTicket.InputBin       = InputBin.Tractor;
            }
            catch (PrintQueueException)
            {
                try
                {   //PrimoPDF
                    //pq = ps.GetPrintQueue("PrimoPDF");
                }
                catch (PrintQueueException)
                {
                    pq = ps.DefaultPrintQueue; //どれもダメなら既定のプリンタ
                }
            }

            var printer = new PrintCutSheetReport <OrderSource, ReportType>(pq);

            var orderSources = getOrderSources();

            printer.Print(orderSources);
            UpdateOrderHistory();
        }
Ejemplo n.º 2
0
 private static PrintQueue GetNamedLocalPrintQueue(string localPrintQueueName)
 {
     using (var printServer = new LocalPrintServer())
     {
         return(printServer.GetPrintQueue(localPrintQueueName));
     }
 }
Ejemplo n.º 3
0
        private IEnumerable <CloudPrinter> DoGetPrintQueues()
        {
            LocalPrintServer PrintServer = new LocalPrintServer();
            Dictionary <string, PrintQueue> queuesToDispose = new Dictionary <string, PrintQueue>(PrintQueues);

            foreach (string printername in EnumerateLocalPrinterNames())
            {
                if (PrintQueues.ContainsKey(printername))
                {
                    queuesToDispose.Remove(printername);
                }
                else
                {
                    PrintQueues.Add(printername, PrintServer.GetPrintQueue(printername));
                }
            }

            foreach (KeyValuePair <string, PrintQueue> pq_kvp in queuesToDispose)
            {
                PrintQueues.Remove(pq_kvp.Key);
                pq_kvp.Value.Dispose();
            }

            return(PrintQueues.Values.Where(q => q.IsShared).Select(q => new CloudPrinterImpl(q)).ToArray());
        }
Ejemplo n.º 4
0
        } // 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()
Ejemplo n.º 5
0
        //public void Print()
        //{
        //    PrintDialog printDialog = new PrintDialog();
        //    LocalPrintServer printServer = new LocalPrintServer();
        //    PrintQueue pq = printServer.GetPrintQueue(PrinterVariables.PRINTERNAME);
        //    printDialog.PrintQueue = pq;
        //    FlowDocument flowDoc = new FlowDocument(new Paragraph(new Run(receipt)));
        //    flowDoc.Name = "Receipt";
        //    flowDoc.FontFamily =  new System.Windows.Media.FontFamily(PrinterVariables.FONTNAME);
        //    flowDoc.FontSize = PrinterVariables.FONTSIZE;

        //    IDocumentPaginatorSource idpSource = flowDoc;
        //    printDialog.PrintDocument(idpSource.DocumentPaginator, "Printing Receipt");

        //}

        public void PrintSilently()
        {
            PrintDialog printDialog = new PrintDialog();
            PrintQueue  pq;
            IDocumentPaginatorSource idpSource = flowDoc;

            try
            {
                if (Settings.Default.useNetworkPrinter)
                {
                    string printServerName = @"\\Coregaming";
                    string printQueueName  = "POS";

                    PrintServer ps = new PrintServer(printServerName);
                    pq = ps.GetPrintQueue(printQueueName);
                    flowDoc.PageWidth = printDialog.PrintableAreaWidth;
                }
                else
                {
                    LocalPrintServer printServer = new LocalPrintServer();
                    pq = printServer.GetPrintQueue(PrinterVariables.PRINTERNAME);
                }
                idpSource = flowDoc;
                printDialog.PrintQueue = pq;
                printDialog.PrintDocument(idpSource.DocumentPaginator, "Printing Receipt");
            }
            catch (Exception e)
            {
                MessageBox.Show("Error in PrintSilently():\n" + e.Message + "\n" + e.Data.ToString());
            }
        }
Ejemplo n.º 6
0
        /* The thread that is actually doing the print work */
        public static void PrintWork(object data)
        {
            List <object> genericlist  = data as List <object>;
            String        file         = (String)genericlist[0];
            bool          print_all    = (bool)genericlist[1];
            int           from         = (int)genericlist[2];
            int           to           = (int)genericlist[3];
            String        printer_name = (String)genericlist[4];
            Print         printcontrol = (Print)genericlist[5];
            bool          istempfile   = (bool)genericlist[6];
            xpsprint      xps_print    = (xpsprint)genericlist[7];
            String        filename     = "";

            if (istempfile == true)
            {
                filename = file;
            }

            /* We have to get our own copy of the print queue for the thread */
            LocalPrintServer m_printServer     = new LocalPrintServer();
            PrintQueue       m_selectedPrinter = m_printServer.GetPrintQueue(printer_name);

            XpsDocument xpsDocument = new XpsDocument(file, FileAccess.Read);

            xps_print.Print(m_selectedPrinter, xpsDocument, printcontrol, print_all,
                            from, to, filename, istempfile);

            /* Once we are done, go ahead and delete the file */
            if (istempfile == true)
            {
                xpsDocument.Close();
            }
            xps_print.Done();
        }
        public PreferenceWindow(MainWindow mw = null)
        {
            InitializeComponent();

            if (mw != null)
            {
                Main = mw;
            }


            pwContext.pwSaveFolderPath = Settings.SaveFilePath;
            pwContext.pwBackFolderPath = Settings.BackupFilePath;
            pwContext.pwPrintLandscape = Settings.PrintLandscape;
            PrinterName          = Settings.PrinterName;
            pwContext.iBackUpGen = Settings.BackupSaveGeneration - 1;



            if (PrinterName != "" && Settings.PrintTicketSetting != null)
            {
                dPrt = new PrintDialog();

                LocalPrintServer ps = new LocalPrintServer();
                dPrt.PrintQueue  = ps.GetPrintQueue(PrinterName);
                dPrt.PrintTicket = Settings.PrintTicketSetting;
            }

            DataContext = pwContext;
        }
        private void InitPrinterParameter(string printerName = "")
        {
            PrintQueue pq = null;

            if (string.IsNullOrEmpty(printerName))
            {
                try
                {
                    pq = LocalPrintServer.GetDefaultPrintQueue();
                }
                catch { pq = null; }
            }
            else
            {
                try
                {
                    LocalPrintServer pser = new LocalPrintServer();
                    pq = pser.GetPrintQueue(printerName);
                }
                catch { pq = null; }
            }
            if (null != pq)
            {
                _printerName = pq.FullName;
                // load default page setting.
                _pageSetting = new LocalReportPageSettings();
            }
            else
            {
                _printerName = string.Empty;
                // default
                _pageSetting = new LocalReportPageSettings();
            }
        }
Ejemplo n.º 9
0
        public void Printing()
        {
            var server = new LocalPrintServer();

            PrintQueue queue = server.GetPrintQueue(@"\\QWTORPRINT1\Goreway-Glazing1", new string[0] {
            });
        }
Ejemplo n.º 10
0
        public static void Print(ref Grid fwe, string PrinterName)
        {
            if (fwe == null)
            {
                return;
            }
            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, "");
        }
Ejemplo n.º 11
0
        /**
         * This funcion return an error message of the printer
         *
         * */
        public Error CheckPrinterStatus(string printerName)
        {
            Error _error = new Error();

            try
            {
                //Get local print server
                var server = new LocalPrintServer();

                //Load queue for correct printer
                PrintQueue queue = server.GetPrintQueue(printerName, new string[0] {
                });

                //Check some properties of printQueue
                bool isInError    = queue.IsInError;
                bool isOutOfPaper = queue.IsOutOfPaper;
                bool isOffline    = queue.IsOffline;
                bool isBusy       = queue.IsBusy;

                _error.HasError = (isInError || isOutOfPaper || isOffline || isBusy);
                _error.Message  = queue.QueueStatus.ToString();
            }
            catch (Exception e)
            {
                _error.HasError = true;
                _error.Message  = e.Message;
            }

            return(_error);
        }
Ejemplo n.º 12
0
        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;
        }
Ejemplo n.º 13
0
        public string ClearQueue()
        {
            LocalPrintServer ps = new LocalPrintServer();
            PrintQueue       pq = ps.GetPrintQueue("");/// ( DefaultPrintQueue;

            pq.Purge();
            return("Ok");
        }
        public static IEnumerable <Stapling> GetStaplings(string printerName)
        {
            var localPrintServer  = new LocalPrintServer();
            var printQueue        = localPrintServer.GetPrintQueue(printerName, new string[0] {
            });
            var printCapabilities = printQueue.GetPrintCapabilities();

            return(printCapabilities.StaplingCapability);
        }
Ejemplo n.º 15
0
        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;
            });
        }
Ejemplo n.º 16
0
        private bool CanDuplexing(string printerName, Duplexing duplexing)
        {
            if (!Printers.Contains(printerName))
            {
                return(false);
            }

            var queue        = _LocalPrintServer.GetPrintQueue(printerName);
            var capabilities = queue.GetPrintCapabilities();

            return(capabilities.DuplexingCapability.Contains(duplexing));
        }
Ejemplo n.º 17
0
        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;
            });
        }
Ejemplo n.º 18
0
        /// <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();
            }
        }
Ejemplo n.º 19
0
        public void TestPrinter()
        {
            var        server = new LocalPrintServer();
            PrintQueue queue  = server.GetPrintQueue(printerName, new string[0] {
            });
            bool error        = false;

            Console.Out.WriteLine("{");
            Console.Out.WriteLine($"\"name\": \"{printerName}\",");
            //Load queue for correct printer
            string[] status = new string[6];
            //Check some properties of printQueue
            if (queue.IsNotAvailable)
            {
                status[0] = "\"off\"";
            }
            if (queue.IsDoorOpened)
            {
                status[1] = "\"Door\"";
            }
            if (queue.IsManualFeedRequired)
            {
                status[2] = "\"User\"";
            }
            if (queue.IsOutOfPaper)
            {
                status[3] = "\"PaperOut\"";
            }
            if (queue.IsOffline)
            {
                status[4] = "\"Offline\"";
            }
            if (queue.IsInError)
            {
                status[5] = "\"Error\"";
            }
            Console.Out.Write("\"status\":[");
            for (int i = 0; i < status.Length; i++)
            {
                if (status[i] != null)
                {
                    if (error)
                    {
                        Console.Out.Write(",");
                    }
                    Console.Out.Write(status[i]);
                    error = true;
                }
            }
            Console.Out.WriteLine("]\n}");
        }
        public static string GetCurrentStapling(string printerName)
        {
            var localPrintServer = new LocalPrintServer();
            var printQueue       = localPrintServer.GetPrintQueue(printerName, new string[0] {
            });

            if (printQueue.UserPrintTicket.Stapling == null)
            {
                return(PrinterHelperMessages.StaplingNotSupportedMessage);
            }

            switch (printQueue.UserPrintTicket.Stapling)
            {
            case Stapling.None:;
                return(PrinterHelperMessages.StaplingNoneMessage);

            case Stapling.SaddleStitch:
                return(PrinterHelperMessages.StaplingSaddleStitchMessage);

            case Stapling.StapleBottomLeft:
                return(PrinterHelperMessages.StaplingStapleBottomLeftMessage);

            case Stapling.StapleBottomRight:
                return(PrinterHelperMessages.StaplingStapleBottomRightMessage);

            case Stapling.StapleDualBottom:
                return(PrinterHelperMessages.StaplingStapleDualBottomMessage);

            case Stapling.StapleDualLeft:
                return(PrinterHelperMessages.StaplingStapleDualLeftMessage);

            case Stapling.StapleDualRight:
                return(PrinterHelperMessages.StaplingStapleDualRightMessage);

            case Stapling.StapleDualTop:
                return(PrinterHelperMessages.StaplingStapleDualTopMessage);

            case Stapling.StapleTopLeft:
                return(PrinterHelperMessages.StaplingStapleTopLeftMessage);

            case Stapling.StapleTopRight:
                return(PrinterHelperMessages.StaplingStapleTopRightMessage);

            case Stapling.Unknown:
            default:
                return(PrinterHelperMessages.StaplingUnknownMessage);
            }
        }
Ejemplo n.º 21
0
        private int Wait_Ticket_Poll(string _ptr_device)
        {
            LocalPrintServer       localPrintServer       = new LocalPrintServer();
            PrintQueue             printQueue             = localPrintServer.GetPrintQueue(_ptr_device);
            PrintJobInfoCollection printJobInfoCollection = printQueue.GetPrintJobInfoCollection();

            if (printQueue.NumberOfJobs > 0)
            {
                if (printQueue.IsPrinting)
                {
                    return(2);
                }
                return(1);
            }
            return(0);
        }
Ejemplo n.º 22
0
        /// <summary>
        /// Returns current printer queue info
        /// </summary>
        /// <returns>Current printer queue info</returns>
        public string GetQueueInfo()
        {
            try
            {
                var server = new LocalPrintServer();
                var queue  = server.GetPrintQueue(printer);

                IsOk = !queue.HasPaperProblem && queue.HasToner && !queue.IsBusy && !queue.IsInError && !queue.IsNotAvailable && !queue.IsOffline && !queue.IsOutOfMemory &&
                       !queue.IsOutOfPaper && !queue.IsOutputBinFull && !queue.IsPaperJammed;

                return
                    ("Full Name: " + queue.FullName + Environment.NewLine +
                     "Has Paper Problem: " + queue.HasPaperProblem + Environment.NewLine +
                     "Has Toner: " + queue.HasToner + Environment.NewLine +
                     "Is Busy: " + queue.IsBusy + Environment.NewLine +
                     "Is Hidden: " + queue.IsHidden + Environment.NewLine +
                     "Is In Error: " + queue.IsInError + Environment.NewLine +
                     "Is Initializing: " + queue.IsInitializing + Environment.NewLine +
                     "Is Not Available: " + queue.IsNotAvailable + Environment.NewLine +
                     "Is Offline: " + queue.IsOffline + Environment.NewLine +
                     "Is Out Of Memory: " + queue.IsOutOfMemory + Environment.NewLine +
                     "Is Out Of Paper: " + queue.IsOutOfPaper + Environment.NewLine +
                     "Is Output Bin Full: " + queue.IsOutputBinFull + Environment.NewLine +
                     "Is Paper Jammed: " + queue.IsPaperJammed + Environment.NewLine +
                     "Is Paused: " + queue.IsPaused + Environment.NewLine +
                     "Is Pending Deletion: " + queue.IsPendingDeletion + Environment.NewLine +
                     "Is Printing: " + queue.IsPrinting + Environment.NewLine +
                     "Is Processing: " + queue.IsProcessing + Environment.NewLine +
                     "Is Published: " + queue.IsPublished + Environment.NewLine +
                     "Is Queued: " + queue.IsQueued + Environment.NewLine +
                     "Is Server Unknown: " + queue.IsServerUnknown + Environment.NewLine +
                     "Is Shared: " + queue.IsShared + Environment.NewLine +
                     "Is Waiting: " + queue.IsWaiting + Environment.NewLine +
                     "Need User Intervention: " + queue.NeedUserIntervention + Environment.NewLine +
                     "Number Of Jobs: " + queue.NumberOfJobs + Environment.NewLine +
                     "Page Punt: " + queue.PagePunt + Environment.NewLine +
                     "Printing Is Cancelled: " + queue.PrintingIsCancelled + Environment.NewLine +
                     "Queue Status: " + queue.QueueStatus + Environment.NewLine +
                     "Share Name: " + queue.ShareName + Environment.NewLine);
            }
            catch (Exception ex)
            {
                IsOk = false;
                throw new Exception("This printer queue is unavailable.", ex);
            }
        }
Ejemplo n.º 23
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());
        }
Ejemplo n.º 24
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());
        }
Ejemplo n.º 25
0
        public static void PrintXPS()
        {
            LocalPrintServer localPrintServer = new LocalPrintServer();
            PrintQueue       psPrintQueue     = localPrintServer.GetPrintQueue("HP CLJ 8550");

            string xpsFile = @"C:\twopages.xps";

            try
            {
                psPrintQueue.UserPrintTicket.CopyCount = 5;
                psPrintQueue.UserPrintTicket.Collation = Collation.Collated;

                PrintSystemJobInfo xpsPrintJob = psPrintQueue.AddJob(xpsFile, xpsFile, false);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
Ejemplo n.º 26
0
        public bool Printer_Poll(string _ptr_device)
        {
            if (string.IsNullOrEmpty(_ptr_device))
            {
                return(false);
            }
            LocalPrintServer       localPrintServer       = new LocalPrintServer();
            PrintQueue             printQueue             = localPrintServer.GetPrintQueue(_ptr_device);
            PrintJobInfoCollection printJobInfoCollection = printQueue.GetPrintJobInfoCollection();

            if (printQueue.NumberOfJobs > 0)
            {
                if (printQueue.IsPrinting)
                {
                    return(true);
                }
                return(false);
            }
            return(false);
        }
Ejemplo n.º 27
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));
        }
Ejemplo n.º 28
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);
        }
Ejemplo n.º 29
0
        }         // proc SetPrintTicket

        /// <summary>Copy printer settings from System.Drawing to System.Printing</summary>
        /// <param name="printerSettings"></param>
        /// <param name="printQueue"></param>
        /// <param name="printTicket"></param>
        public static unsafe void SetPrinterSettings(this PrinterSettings printerSettings, out PrintQueue printQueue, out PrintTicket printTicket)
        {
            using (var printTicketConverter = new PrintTicketConverter(printerSettings.PrinterName, PrintTicketConverter.MaxPrintSchemaVersion))
                using (var printServer = new LocalPrintServer())
                {
                    printQueue = printServer.GetPrintQueue(printerSettings.PrinterName);

                    var hDevMode = printerSettings.GetHdevmode();
                    try
                    {
                        var pDevMode = NativeMethods.GlobalLock(hDevMode);
                        var bDevMode = new byte[NativeMethods.GlobalSize(hDevMode).ToInt32()];
                        Marshal.Copy(pDevMode, bDevMode, 0, bDevMode.Length);
                        NativeMethods.GlobalUnlock(hDevMode);

                        printTicket = printTicketConverter.ConvertDevModeToPrintTicket(bDevMode, PrintTicketScope.JobScope);
                    }
                    finally
                    {
                        Marshal.FreeHGlobal(hDevMode);
                    }
                }
        }         // proc SetPrinterSettings
Ejemplo n.º 30
0
        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);
        }
        private IEnumerable<CloudPrinter> DoGetPrintQueues()
        {
            LocalPrintServer PrintServer = new LocalPrintServer();
            Dictionary<string, PrintQueue> queuesToDispose = new Dictionary<string, PrintQueue>(PrintQueues);

            foreach (string printername in EnumerateLocalPrinterNames())
            {
                if (PrintQueues.ContainsKey(printername))
                {
                    queuesToDispose.Remove(printername);
                }
                else
                {
                    PrintQueues.Add(printername, PrintServer.GetPrintQueue(printername));
                }
            }

            foreach (KeyValuePair<string, PrintQueue> pq_kvp in queuesToDispose)
            {
                PrintQueues.Remove(pq_kvp.Key);
                pq_kvp.Value.Dispose();
            }

            return PrintQueues.Values.Where(q => q.IsShared).Select(q => new CloudPrinterImpl(q)).ToArray();
        }
Ejemplo n.º 32
0
        private void Print_Click(object sender, RoutedEventArgs e)
        {
            //If you reduce the size of the view area of the window, so the text does not all fit into one page, it will print separate pages
            string        str         = " If you reduce the size of the view area of the window, so \nthe text does not all fit into one page, it will print separate pages ";
            List <string> PrinterList = new List <string>();
            /*******************************/
            //printicket
            PrintTicket ticket = new PrintTicket();

            ticket.PageMediaSize   = new PageMediaSize(100, 100);
            ticket.PageOrientation = PageOrientation.Portrait;
            ticket.PageOrder       = PageOrder.Standard;


            LocalPrintServer     prntserver      = new LocalPrintServer();
            PrintQueueCollection queueCollection = prntserver.GetPrintQueues();
            PrintDialog          printDialog     = new PrintDialog();

            foreach (string printer in System.Drawing.Printing.PrinterSettings.InstalledPrinters)
            {
                PrinterList.Add(printer);
                //MessageBox.Show(printer);
            }
            PageRange pr = new PageRange(1, 3);

            string[] tempPrint     = PrinterList.ToArray();
            string   printFullName = printDialog.PrintQueue.FullName;

            printDialog.PrintQueue  = prntserver.GetPrintQueue(PrinterList[0]);
            printDialog.PrintTicket = ticket;
            printDialog.PageRange   = pr;
            //DocumentPaginator paginatro = new DocumentPaginator();



            /***************************************************************/
            // add exptra pages
            FixedPage     page = new FixedPage();
            FixedDocument Doc  = new FixedDocument();


            //if(printDialog.ShowDialog() == true)
            //printDialog.PrintDocument(((IDocumentPaginatorSource)flowDocument).DocumentPaginator, str + "This is a Flow Document");

            string NewSelectedPrinter = printDialog.PrintQueue.FullName;


            /*****************new code*********************/

            // select printer and get printer settings
            PrintDialog pd = new PrintDialog();
            //if (pd.ShowDialog() != true) return;
            //Create a document
            double width  = 400;
            double height = 600;

            FixedDocument fxDoc = new FixedDocument();

            fxDoc.DocumentPaginator.PageSize = new Size(width, height);

            // Create fixed page1
            //FixedPage page1 = new FixedPage();
            //page1.Width = width;
            //page1.Height = height;

            //// Create fixed page2
            //FixedPage page2 = new FixedPage();
            //page2.Width = width;
            //page2.Height = height;

            ////Add some text1
            TextBlock tx1 = new TextBlock();
            //tx1.Width = width;
            //tx1.FontSize = 12;
            //tx1.Text = " Page1 And add the page to the document, this is a little tricky because we need to use a PageContent object as an intermediary and it looks like there is no way to add the page to the page content, the trick is to use the IAddChild interface – according to the documentation you’re not supposed to use IAddChild directly but it’s the only way to build a fixed document.";
            //tx1.TextAlignment = TextAlignment.Justify;
            //tx1.TextWrapping = TextWrapping.Wrap;
            //page1.Children.Add(tx1);

            ////Add some text2
            //tx1 = new TextBlock();
            //tx1.Width = width;
            //tx1.FontSize = 20;
            //tx1.Text = "  Page 2 And add the page to the document, this is a little tricky because we need to use a PageContent object as an intermediary and it looks like there is no way to add the page to the page content, the trick is to use the IAddChild interface – according to the documentation you’re not supposed to use IAddChild directly but it’s the only way to build a fixed document.";
            //tx1.TextAlignment = TextAlignment.Justify;
            //tx1.TextWrapping = TextWrapping.Wrap;
            //page2.Children.Add(tx1);



            // add page to document bye PageContent object
            //PageContent pgCont = new PageContent();
            //pgCont.Child = page1;
            //fxDoc.Pages.Add(pgCont);
            //pgCont = new PageContent();
            //pgCont.Child = page2;
            //fxDoc.Pages.Add(pgCont);

            FixedPage page1;
            Grid      grd1;
            TextBlock tx2;

            fxDoc = new FixedDocument();
            FixedDocument fixDocument2 = new FixedDocument();
            PageContent   pgCont       = new PageContent();
            Grid          grd;

            FixedPage[] pageCollection = new FixedPage[10];
            //List<FixedPage> listPageCollection = new List<FixedPage>();
            for (int i = 0; i < 8; i++)
            {
                //CreatePage
                page        = new FixedPage();
                page.Name   = "Page" + i;
                page.Width  = width;
                page.Height = height;
                /***********(2)*************/
                page1        = new FixedPage();
                page1.Name   = "Page" + i;
                page1.Width  = width;
                page1.Height = height;

                //Add text to Page.
                grd       = new Grid();
                grd.Width = width;
                /*******(2)**********/
                grd1       = new Grid();
                grd1.Width = width;

                //Grid
                RowDefinition row = new RowDefinition();
                grd.RowDefinitions.Add(row);
                row = new RowDefinition();
                grd.RowDefinitions.Add(row);
                /************(2)******************/
                RowDefinition row1 = new RowDefinition();
                grd1.RowDefinitions.Add(row1);
                row1 = new RowDefinition();
                grd1.RowDefinitions.Add(row1);

                //Header TextBlock
                tx1               = new TextBlock();
                tx1.Width         = width;
                tx1.FontSize      = 20;
                tx1.Text          = "Page Index " + i;
                tx1.TextAlignment = TextAlignment.Center;
                //tx1.TextWrapping = TextWrapping.Wrap;
                Grid.SetRow(tx1, 0);
                grd.Children.Add(tx1);
                /***********(2)**************/
                //Header TextBlock
                tx2               = new TextBlock();
                tx2.Width         = width;
                tx2.FontSize      = 20;
                tx2.Text          = "Page Index " + i;
                tx2.TextAlignment = TextAlignment.Center;
                //tx1.TextWrapping = TextWrapping.Wrap;
                Grid.SetRow(tx2, 0);
                grd1.Children.Add(tx2);



                //Paragraph
                tx1               = new TextBlock();
                tx1.Width         = width;
                tx1.FontSize      = 14;
                tx1.Text          = "Page " + i + " And add the page to the document, this is a little tricky because we need to use a PageContent object as an intermediary and it looks like there is no way to add the page to the page content, the trick is to use the IAddChild interface – according to the documentation you’re not supposed to use IAddChild directly but it’s the only way to build a fixed document.";
                tx1.TextAlignment = TextAlignment.Justify;
                tx1.TextWrapping  = TextWrapping.Wrap;
                Grid.SetRow(tx1, 1);
                grd.Children.Add(tx1);

                /**************(2)*********************/
                //Paragraph
                tx2               = new TextBlock();
                tx2.Width         = width;
                tx2.FontSize      = 14;
                tx2.Text          = "Page " + i + " And add the page to the document, this is a little tricky because we need to use a PageContent object as an intermediary and it looks like there is no way to add the page to the page content, the trick is to use the IAddChild interface – according to the documentation you’re not supposed to use IAddChild directly but it’s the only way to build a fixed document.";
                tx2.TextAlignment = TextAlignment.Justify;
                tx2.TextWrapping  = TextWrapping.Wrap;
                Grid.SetRow(tx2, 1);
                grd1.Children.Add(tx2);



                page.Children.Add(grd);
                //Add text to pagecontent
                page1.Children.Add(grd1);

                CloneObject c1 = new CloneObject();
                pageCollection[i] = (FixedPage)c1.DeepCopy();

                pgCont       = new PageContent();
                pgCont.Child = page;
                fxDoc.Pages.Add(pgCont);
            }

            ticket = new PrintTicket();
            ticket.PageMediaSize   = new PageMediaSize(width, height);
            ticket.PageOrientation = PageOrientation.Portrait;
            //ticket.PagesPerSheet = 2;
            pd.PrintTicket = ticket;
            pd.PrintDocument(fxDoc.DocumentPaginator, "My First Document");


            /*****************Print According to Index************************************/

            pgCont = new PageContent();
            //pgCont= fxDoc.Pages[4];

            page         = new FixedPage();
            page         = pageCollection[3];
            pgCont.Child = page;

            fxDoc = new FixedDocument();
            fxDoc.Pages.Add(pgCont);

            ticket = new PrintTicket();
            ticket.PageMediaSize   = new PageMediaSize(width, height);
            ticket.PageOrientation = PageOrientation.Portrait;
            //ticket.PagesPerSheet = 2;
            pd.PrintTicket = ticket;
            pd.PrintDocument(fxDoc.DocumentPaginator, "My First Document");

            /*****************************Cloning of Object******************************************************/
        }
Ejemplo n.º 33
0
        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>
        /// 打印范围
        /// </summary>
        /// <param name="startIndex"></param>
        /// <param name="endIndex"></param>
        private void PrintRange(int startIndex, int endIndex)
        {
            if (startIndex >= 0 && endIndex < PageCount && startIndex <= endIndex)
            {
                var queueName = CurrentPrintQueue.FullName;

                //BitmapImage暂时没有办法异步打印
                if (this._paginator is DataTableDocumentPaginator)
                {
                    Task.Factory.StartNew(() =>
                    {
                        try
                        {
                            ProgressValue = 0;

                            if (endIndex != 0)
                            {
                                ShowProgress = true;
                            }

                            ControlStatus   = false;
                            IsIndeterminate = false;

                            var p = PaginatorFactory.GetDocumentPaginator(_config);

                            p.PageSize = new Size(_paginator.PageSize.Width, _paginator.PageSize.Height);

                            var server = new LocalPrintServer();

                            var queue = server.GetPrintQueue(queueName);

                            queue.UserPrintTicket.PageMediaSize = PageSize;

                            queue.UserPrintTicket.PageOrientation = PageOrientation;

                            var doc = PrintQueue.CreateXpsDocumentWriter(queue);

                            if (endIndex != 0)
                            {
                                doc.WritingProgressChanged += doc_WritingProgressChanged;
                            }

                            doc.Write(new PageRangeDocumentPaginator(startIndex, endIndex, p));

                            if (endIndex != 0)
                            {
                                doc.WritingProgressChanged -= doc_WritingProgressChanged;
                            }
                        }
                        catch (Exception ex)
                        {
                        }
                        finally
                        {
                            ControlStatus = true;
                            ShowProgress  = false;

                            _dispatcher.BeginInvoke(new Action(() => Close()));
                        }
                    });
                }
                else
                {
                    ProgressValue = 0;

                    if (endIndex != 0)
                    {
                        ShowProgress = true;
                    }

                    ControlStatus   = false;
                    IsIndeterminate = false;

                    var p = PaginatorFactory.GetDocumentPaginator(_config);

                    p.PageSize = new Size(_paginator.PageSize.Width, _paginator.PageSize.Height);

                    var server = new LocalPrintServer();

                    var queue = server.GetPrintQueue(queueName);

                    queue.UserPrintTicket.PageMediaSize = PageSize;

                    queue.UserPrintTicket.PageOrientation = PageOrientation;

                    var doc = PrintQueue.CreateXpsDocumentWriter(queue);

                    if (endIndex != 0)
                    {
                        doc.WritingProgressChanged += doc_WritingProgressChanged;
                    }

                    doc.Write(new PageRangeDocumentPaginator(startIndex, endIndex, p));

                    if (endIndex != 0)
                    {
                        doc.WritingProgressChanged -= doc_WritingProgressChanged;
                    }

                    ControlStatus = true;
                    ShowProgress  = false;

                    _dispatcher.BeginInvoke(new Action(() => Close()));
                }
            }
        }