Ejemplo n.º 1
0
        public static void PrintXPS(object sender)
        {
            string           text              = sender.ToString();
            LocalPrintServer localPrintServer  = new LocalPrintServer();
            PrintQueue       defaultPrintQueue = LocalPrintServer.GetDefaultPrintQueue();
            bool             arg_19_0          = defaultPrintQueue.IsXpsDevice;
            FileInfo         fileInfo          = new FileInfo(text);

            try
            {
                defaultPrintQueue.AddJob(fileInfo.Name, text, false);
                MessageBox.Show("打印完成");
            }
            catch (PrintJobException ex)
            {
                MessageBox.Show(string.Format("\n\t{0} 无法加入打印队列,请查看打印机设置.", fileInfo.Name));
                if (ex.InnerException.Message == "File contains corrupted data.")
                {
                    MessageBox.Show("\t文档结构出错,请重试");
                }
            }

            //LocalPrintServer ps = new LocalPrintServer();

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

            //// Get an XpsDocumentWriter for the default print queue
            //XpsDocument xpsDocument = new XpsDocument(text, FileAccess.ReadWrite);
            //XpsDocumentWriter xpsdw = PrintQueue.CreateXpsDocumentWriter(pq);

            //return xpsdw;
        }
Ejemplo n.º 2
0
        private void _printBooking(XpsDocument xpsDoc)
        {
            Logger.Log("Démarrage de l'impression");
            Thread printThread = new Thread(() =>
            {
                try
                {
                    string outDir = ConfigurationManager.AppSettings["XpsOutDir"];
                    PrintQueue defaultPrintQueue = LocalPrintServer.GetDefaultPrintQueue();
                    string jobName = $"Facture - {_clientEntity.FirstName} {_clientEntity.LastName} - {_clientEntity.BirthDate:dd/MM/yyyy}";
                    PrintSystemJobInfo xpsPrintJob = defaultPrintQueue.AddJob(jobName, $"{outDir}flowDocument.xps", false);

                    Logger.Log("Impression terminée");
                    PromptViewModel successPromptVM = new PromptViewModel("Succés", "L'impression a été effectuée.", false);
                    ViewDriverProvider.ViewDriver.ShowView <PromptViewModel>(successPromptVM);
                }
                catch (PrintJobException pje)
                {
                    Logger.Log(pje);
                }
            });

            printThread.SetApartmentState(ApartmentState.STA);
            printThread.Start();
        }
Ejemplo n.º 3
0
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            FixedDocument doc = new FixedDocument();
            // A4 Standard: 8.27 x 11.69 inch; 96 dpi
            Size documentSize = new Size(96 * 8.27, 96 * 11.69);

            doc.DocumentPaginator.PageSize = documentSize;

            using (FileStream fs = new FileStream("Template.xaml", FileMode.Open, FileAccess.Read))
            {
                FixedPage fixedPage = XamlReader.Load(fs) as FixedPage;
                //TODO Add Data (injection)

                //set page size
                fixedPage.Width  = doc.DocumentPaginator.PageSize.Width;
                fixedPage.Height = doc.DocumentPaginator.PageSize.Height;

                PageContent pageContent = new PageContent();
                ((IAddChild)pageContent).AddChild(fixedPage);
                doc.Pages.Add(pageContent);

                //XpsDocument xpsDocument = new XpsDocument("output.xps", FileAccess.Write);
                //XpsDocumentWriter xpsDocumentWriter = XpsDocument.CreateXpsDocumentWriter(xpsDocument);
                //xpsDocumentWriter.Write(doc);
                //xpsDocument.Close();

                docViewer.Document = doc;

                var pq        = LocalPrintServer.GetDefaultPrintQueue();
                var writer    = PrintQueue.CreateXpsDocumentWriter(pq);
                var paginator = doc.DocumentPaginator;
                writer.Write(paginator);
            }
        }
Ejemplo n.º 4
0
        public static void DruckerKontrolle()
        {
            while (true)
            {
                //Application.Current.Dispatcher.Invoke(DispatcherPriority.Background,
                //           new Action(() =>
                //           {
                //           }));



                var printerQuery = new ManagementObjectSearcher("SELECT * from Win32_Printer");
                foreach (var printer in printerQuery.Get())
                {
                    var name = printer.GetPropertyValue("Name");

                    string DruckerName      = name.ToString();
                    var    status           = printer.GetPropertyValue("Status");
                    var    isDefault        = printer.GetPropertyValue("Default");
                    string DefaultDrucker   = isDefault.ToString();
                    var    isNetworkPrinter = printer.GetPropertyValue("Network");



                    if (DefaultDrucker == "True")
                    {
                        GlobalVar.PrinterName = DruckerName;
                    }
                }


                string wmiQuery = "SELECT * FROM Win32_PrintJob";
                ManagementObjectSearcher   jobsSearcher  = new ManagementObjectSearcher(wmiQuery);
                ManagementObjectCollection jobCollection = jobsSearcher.Get();
                foreach (ManagementObject mo in jobCollection)
                {
                    if ((Convert.ToUInt32(mo["TotalPages"]) > 0) && (GlobalVar.CheckDruckActive == false))
                    {
                        foreach (var job in LocalPrintServer.GetDefaultPrintQueue().GetPrintJobInfoCollection())
                        {
                            using (PrintServer ps = new PrintServer())
                            {
                                using (PrintQueue Warteschlange = new PrintQueue(ps, GlobalVar.PrinterName, PrintSystemDesiredAccess.AdministratePrinter))
                                {
                                    Warteschlange.Pause();
                                }
                            }
                        }

                        Application.Current.Dispatcher.Invoke(DispatcherPriority.Background, new Action(() =>
                        {
                            WarnFenster Warnung = new WarnFenster();
                            Warnung.Show();
                        }));

                        GlobalVar.CheckDruckActive = true;
                    }
                }
            }
        }
Ejemplo n.º 5
0
        private void btnRePrint_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            Image btn = (Image)sender;
            RetailSearchEntity entity = (RetailSearchEntity)btn.DataContext;
            string             path   = string.Format("{0}\\RetailTicket\\{1}\\{2}.xps", Environment.CurrentDirectory, entity.CreateTime.ToString("yyyyMMdd"), entity.Code);

            if (!File.Exists(path))
            {
                MessageBox.Show("没有找到可供打印的票据.");
                return;
            }
            else
            {
                try
                {
                    //Uri printTemplate = new Uri(path, UriKind.Absolute);
                    XpsDocument       printPage         = new XpsDocument(path, FileAccess.Read);//(XpsDocument)Application.LoadComponent(printTemplate);
                    PrintQueue        defaultPrintQueue = LocalPrintServer.GetDefaultPrintQueue();
                    XpsDocumentWriter xpsdw             = PrintQueue.CreateXpsDocumentWriter(defaultPrintQueue);
                    xpsdw.Write(printPage.GetFixedDocumentSequence());
                }
                catch (Exception ex)
                {
                    MessageBox.Show("打印失败,失败原因:" + ex.Message);
                }
            }
        }
Ejemplo n.º 6
0
        static void Main(string[] args)
        {
            //<SnippetShowPropertyTypesWithoutReflection>

            // Enumerate the properties, and their types, of a queue without using Reflection
            LocalPrintServer localPrintServer  = new LocalPrintServer();
            PrintQueue       defaultPrintQueue = LocalPrintServer.GetDefaultPrintQueue();

            PrintPropertyDictionary printQueueProperties = defaultPrintQueue.PropertiesCollection;

            Console.WriteLine("These are the properties, and their types, of {0}, a {1}", defaultPrintQueue.Name, defaultPrintQueue.GetType().ToString() + "\n");

            foreach (DictionaryEntry entry in printQueueProperties)
            {
                PrintProperty property = (PrintProperty)entry.Value;

                if (property.Value != null)
                {
                    Console.WriteLine(property.Name + "\t(Type: {0})", property.Value.GetType().ToString());
                }
            }
            Console.WriteLine("\n\nPress Return to continue...");
            Console.ReadLine();

            //</SnippetShowPropertyTypesWithoutReflection>
        }
Ejemplo n.º 7
0
        public void Print()
        {
            foreach (var report in _localReports)
            {
                string mimeType, encoding, extension;

                Warning[] warnings;
                string[]  streams;

                var renderBytes = report.Render
                                  (
                    "PDF",
                    null,
                    out mimeType,
                    out encoding,
                    out extension,
                    out streams,
                    out warnings
                                  );



                var printQueue = LocalPrintServer.GetDefaultPrintQueue();
                using (var job = printQueue.AddJob())
                    using (var stream = job.JobStream)
                    {
                        stream.Write(renderBytes, 0, renderBytes.Length);
                    }
            }
        }
Ejemplo n.º 8
0
        public static void PrintXpsToPrinter(XpsDocument xpsDocument, string printQueueName = null)
        {
            //PrintTicket ticket = new PrintTicket();
            PrintQueue queue = null;

            if (!string.IsNullOrEmpty(printQueueName))
            {
                try
                {
                    queue = new LocalPrintServer().GetPrintQueue(printQueueName);
                }
                catch (Exception ex)
                {
                    LogService.Error("Error while getting print queue " + printQueueName, ex);
                    queue = LocalPrintServer.GetDefaultPrintQueue();
                }
            }
            else
            {
                queue = LocalPrintServer.GetDefaultPrintQueue();
            }

            //ticket.PageMediaSize = new PageMediaSize(PageWidth, PageHeight);
            //queue.UserPrintTicket = ticket;

            XpsDocumentWriter pwriter = PrintQueue.CreateXpsDocumentWriter(queue);

            pwriter.WritingCompleted += (s, e) =>
            {
            };

            //pwriter.WriteAsync(xpsDocument.GetFixedDocumentSequence(), ticket);
            pwriter.WriteAsync(xpsDocument.GetFixedDocumentSequence());
        }
        void PrintButtonClick(object sender, RoutedEventArgs e)
        {
            PrintDialog dlg = new PrintDialog();

            dlg.UserPageRangeEnabled = true;

            dlg.PrintQueue         = LocalPrintServer.GetDefaultPrintQueue();
            dlg.PageRangeSelection = PageRangeSelection.UserPages;



            PageRange oRange = new PageRange(ReferenceHelp.xpsDocumentViewer.xpsViewer1.MasterPageNumber, ReferenceHelp.xpsDocumentViewer.xpsViewer1.MasterPageNumber);

            dlg.PageRange = oRange;


            if (dlg.ShowDialog().Value == true)
            {
                DocumentPaginator paginator = _ReferenceHelp.xpsDocumentViewer.xpsViewer1.Document.DocumentPaginator;


                if (dlg.PageRangeSelection == PageRangeSelection.UserPages)
                {
                    paginator = new PageRangeDocumentPaginator(
                        _ReferenceHelp.xpsDocumentViewer.xpsViewer1.Document.DocumentPaginator,
                        dlg.PageRange);
                }



                dlg.PrintDocument(paginator, "FIA BIOSUM Help");
            }
        }
        private void cmdPrint_Click(object sender, RoutedEventArgs e)
        {
            PrintDialog dialog = new PrintDialog();

            dialog.PrintQueue = LocalPrintServer.GetDefaultPrintQueue();
            dialog.PrintVisual((Visual)sender, "Automatic Printout");
        }
Ejemplo n.º 11
0
        private void PrintingPreviewWindow_Loaded(object sender, RoutedEventArgs e)
        {
            List <Printer> printers = new List <Printer>();

            PrintServer          printServer = new PrintServer();
            PrintQueueCollection printQueues = printServer.GetPrintQueues();
            string  defaultFullName          = LocalPrintServer.GetDefaultPrintQueue().FullName;
            Printer defaultPrinter           = null;

            foreach (PrintQueue printQueue in printQueues)
            {
                Printer printer = new Printer(printQueue);
                printers.Add(printer);
                if (printer.FullName == defaultFullName)
                {
                    defaultPrinter = printer;
                }
            }

            printers.Reverse();

            PrintersCombo.ItemsSource = printers;

            PrintersCombo.SelectionChanged -= PrintersCombo_SelectionChanged;
            PrintersCombo.SelectionChanged += PrintersCombo_SelectionChanged;

            if (defaultPrinter != null)
            {
                PrintersCombo.SelectedItem = defaultPrinter;
            }
            else
            {
                PrintersCombo.SelectedIndex = 0;
            }
        }
Ejemplo n.º 12
0
 public PrintSettings()
 {
     this.PrintQueue           = LocalPrintServer.GetDefaultPrintQueue();
     this.PrintTicket          = this.PrintQueue.DefaultPrintTicket;
     this.PageSettings         = new PageSettings();
     this.PageSettings.Margins = new Margins(40, 40, 40, 40);
 }
Ejemplo n.º 13
0
        public void StartPrinting()
        {
            PrintDocument printDoc = new PrintDocument();
            // printDoc.PrinterSettings.PrinterName = DefaultPrinter.GetDefaultPrinterName();

            //if (Validations())
            //{
            //    MessageBox.Show("Make Sure Both The Boxes Are Filled");
            //    return;
            //}
            Configuration configuration = ConfigurationManager.
                                          OpenExeConfiguration(Assembly.GetExecutingAssembly().Location);

            GenerateBacode(configuration.AppSettings.Settings["StartingNumber"].Value);
            PrintDateString  = PrintDateString + "  " + "OK TESTED";
            PrintDateString += "\n" + Convert.ToString(DateTime.Now);
            var printServer = new LocalPrintServer();

            //  MessageBox.Show(LocalPrintServer.GetDefaultPrintQueue().FullName);
            if (LocalPrintServer.GetDefaultPrintQueue().FullName == null || LocalPrintServer.GetDefaultPrintQueue().FullName == "")
            {
                MessageBox.Show("NO PRINTER");
                return;
            }

            printDoc.PrinterSettings.PrinterName = LocalPrintServer.GetDefaultPrintQueue().FullName;
            printDoc.PrintPage += new PrintPageEventHandler(printPage);
            printDoc.Print();
        }
Ejemplo n.º 14
0
        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.º 15
0
        private void cmdPrint_Click(object sender, RoutedEventArgs e)
        {
            if (trvMain.SelectedItem is MReportGroup)
            {
                return;
            }

            MReportFilter mr = (MReportFilter)trvMain.SelectedItem;

            if (mr == null)
            {
                return;
            }

            CBaseReport paginator = (CBaseReport)reportObjs[mr.ReportName];

            if (paginator == null)
            {
                return;
            }

            Boolean isPageRange = (Boolean)cbxPageRange.IsChecked;

            if (isPageRange)
            {
                populatePageRange(paginator);

                if (paginator.toPage < paginator.fromPage)
                {
                    CHelper.ShowErorMessage("", "ERROR_PAGE_RANGE", null);
                    return;
                }
            }

            dialog.PrintQueue  = LocalPrintServer.GetDefaultPrintQueue();
            dialog.PrintTicket = dialog.PrintQueue.DefaultPrintTicket;
            dialog.PrintTicket.PageOrientation = paginator.GetPageOrientation();
            dialog.PrintTicket.PageMediaSize   = new PageMediaSize(PageMediaSizeName.Unknown, paginator.PageSize.Width, paginator.PageSize.Height);
            bool?result = dialog.ShowDialog();

            if (result == true)
            {
                paginator.isPageRange = isPageRange;

                FixedDocument fd = null;
                if (!isPageRange)
                {
                    fd = paginator.GetFixedDocument();
                }
                else
                {
                    fd = paginator.CreateFixedDocument();
                }

                docViewer.Document = paginator.GetFixedDocument();
                dialog.PrintDocument(fd.DocumentPaginator, "");

                CUtil.LoadPageNavigateCombo(cboPageNo, paginator.PageCount);
            }
        }
Ejemplo n.º 16
0
        /// <summary>
        /// 打印控件
        /// </summary>
        /// <param name="element"></param>
        public void PrintVisual(FrameworkElement element)
        {
            try
            {
                var printDialog = new PrintDialog();
                //if ((bool)printDialog.ShowDialog())
                //{
                //    printDialog.PrintVisual(element, "");
                //    return;
                //}

                SetPrintProperty(printDialog, element.Width - 1, element.Height);


                var printQueue = LocalPrintServer.GetDefaultPrintQueue();

                if (printQueue != null)
                {
                    printDialog.PrintQueue = printQueue;
                    //new PrintDirect(LocalPrintServer.GetDefaultPrintQueue().Name).PrintESC(0);
                    printDialog.PrintVisual(element, "");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
Ejemplo n.º 17
0
 public PrintSettings()
 {
     this.PrintQueue           = LocalPrintServer.GetDefaultPrintQueue();
     this.PrintTicket          = this.PrintQueue.DefaultPrintTicket;
     this.PageSettings         = new PageSettings();
     this.PageSettings.Margins = new Margins(left: mmToinch(12), right: mmToinch(12), top: mmToinch(15), bottom: mmToinch(15));  // unit is hundredths of an inch
 }
Ejemplo n.º 18
0
        private void prtdata_02()
        {
            // Enumerate the properties, and their types, of a queue without using Reflection
            LocalPrintServer localPrintServer  = new LocalPrintServer();
            PrintQueue       defaultPrintQueue = LocalPrintServer.GetDefaultPrintQueue();

            PrintPropertyDictionary printQueueProperties = defaultPrintQueue.PropertiesCollection;

            txtDiags.Text += "These are the properties, and their types, of " +
                             defaultPrintQueue.Name +
                             " " +
                             defaultPrintQueue.GetType().ToString() + "\n\n";

            foreach (DictionaryEntry entry in printQueueProperties)
            {
                PrintProperty property = (PrintProperty)entry.Value;

                if (property.Value != null)
                {
                    txtDiags.Text += property.Name +
                                     "\t" + property.Value.GetType().ToString() +
                                     "\t" + property.Value.ToString() +
                                     "\n";
                }
            }
        }
Ejemplo n.º 19
0
        public void Print_Document()

        {
            //----------------< Print_Document() >-----------------------

            //----< Get_Print_Dialog_and_Printer >----

            PrintDialog printDialog = new PrintDialog();

            printDialog.PrintQueue = LocalPrintServer.GetDefaultPrintQueue();

            printDialog.PrintTicket = printDialog.PrintQueue.DefaultPrintTicket;

            //----</ Get_Print_Dialog_and_Printer >----



            //*set the default page orientation based on the desired output.

            printDialog.PrintTicket.PageOrientation = PageOrientation.Landscape;

            printDialog.PrintTicket.PageScalingFactor = 90;

            printDialog.PrintTicket.PageMediaSize = new PageMediaSize(PageMediaSizeName.ISOA4);

            //printDialog.PrintableAreaHeight ; //*get

            //printDialog.PrintableAreaWidth;   //get

            //printDialog.PrintDocument.

            printDialog.PrintTicket.PageBorderless = PageBorderless.None;



            if (printDialog.ShowDialog() == true)

            {
                //----< print >----

                // set the print ticket for the document sequence and write it to the printer.

                _document.PrintTicket = printDialog.PrintTicket;



                //-< send_document_to_printer >-

                XpsDocumentWriter writer = PrintQueue.CreateXpsDocumentWriter(printDialog.PrintQueue);

                writer.WriteAsync(_document, printDialog.PrintTicket);

                //-</ send_document_to_printer >-

                //----</ print >----
            }

            //----------------</ Print_Document() >-----------------------
        }
Ejemplo n.º 20
0
        private void OnPrint(object sender, RoutedEventArgs e)
        {
            var dialog = new PrintDialog {
                PrintQueue = LocalPrintServer.GetDefaultPrintQueue()
            };

            dialog.PrintVisual((Visual)sender, "Automatic Printout");
        }
Ejemplo n.º 21
0
        public BradyPrinter()
        {
            var defaultPrintQueue = LocalPrintServer.GetDefaultPrintQueue();

            DocumentWriter = PrintQueue.CreateXpsDocumentWriter(defaultPrintQueue);
            PrintTicket    = defaultPrintQueue.DefaultPrintTicket;
            DrawingVisual  = new DrawingVisual();
        }
        /// <summary>
        /// 加载打印机和默认选中打印机
        /// </summary>
        private void LoadPrintQueues()
        {
            var server = new LocalPrintServer();

            PrintQueues = server.GetPrintQueues();

            CurrentPrintQueue =
                PrintQueues.FirstOrDefault(x => x.FullName == LocalPrintServer.GetDefaultPrintQueue().FullName);
        }
Ejemplo n.º 23
0
        public static void PrintXPS()
        {
            // Create print server and print queue.
            LocalPrintServer localPrintServer  = new LocalPrintServer();
            PrintQueue       defaultPrintQueue = LocalPrintServer.GetDefaultPrintQueue();

            // Prompt user to identify the directory, and then create the directory object.
            Console.Write("Enter the directory containing the XPS files: ");
            String        directoryPath = Console.ReadLine();
            DirectoryInfo dir           = new DirectoryInfo(directoryPath);

            // If the user mistyped, end the thread and return to the Main thread.
            if (!dir.Exists)
            {
                Console.WriteLine("There is no such directory.");
            }
            else
            {
                // If there are no XPS files in the directory, end the thread
                // and return to the Main thread.
                if (dir.GetFiles("*.xps").Length == 0)
                {
                    Console.WriteLine("There are no XPS files in the directory.");
                }
                else
                {
                    Console.WriteLine("\nJobs will now be added to the print queue.");
                    Console.WriteLine("If the queue is not paused and the printer is working, jobs will begin printing.");

                    // Batch process all XPS files in the directory.
                    foreach (FileInfo f in dir.GetFiles("*.xps"))
                    {
                        String nextFile = directoryPath + "\\" + f.Name;
                        Console.WriteLine("Adding {0} to queue.", nextFile);

                        try
                        {
                            // Print the Xps file while providing XPS validation and progress notifications.
                            PrintSystemJobInfo xpsPrintJob = defaultPrintQueue.AddJob(f.Name, nextFile, false);
                        }
                        catch (PrintJobException e)
                        {
                            Console.WriteLine("\n\t{0} could not be added to the print queue.", f.Name);
                            if (e.InnerException.Message == "File contains corrupted data.")
                            {
                                Console.WriteLine("\tIt is not a valid XPS file. Use the isXPS Conformance Tool to debug it.");
                            }
                            Console.WriteLine("\tContinuing with next XPS file.\n");
                        }
                    }
                }
            }

            Console.WriteLine("Press Enter to end program.");
            Console.ReadLine();
        }
        public void Print()
        {
            if (isAutoPrint == false && isClickPrint == false)
            {
                return;
            }
            try
            {
                PrintQueue printQueue = LocalPrintServer.GetDefaultPrintQueue();
                if (printQueue == null || printQueue.IsOffline == true)
                {
                    throw new Exception("打印机不可用!");
                }
                string      description = "磅单打印";
                PrintDialog printDialog = new PrintDialog();
                printDialog.CurrentPageEnabled = true;
                printDialog.PageRange          = new PageRange(1);

                Panel PrintArea = null;
                if (mType == WeightingBillType.RK)
                {
                    PrintArea = this.InPanel;
                }
                else
                {
                    PrintArea = this.OutPanel;
                }

                mTime = new System.Threading.Timer(delegate
                {
                    this.Dispatcher.BeginInvoke(new Action(delegate
                    {
                        printDialog = null;
                        this.Close();
                    }), System.Windows.Threading.DispatcherPriority.Send);
                }, null, 3000, System.Threading.Timeout.Infinite);


                this.Dispatcher.BeginInvoke(new Action(delegate
                {
                    printDialog.PrintVisual(PrintArea, description);
                    mWeighingBill.printTimes    = mWeighingBill.printTimes + 1;
                    mWeighingBill.printDateTime = MyHelper.DateTimeHelper.getCurrentDateTime();
                    isOPtionSuccess             = true;
                    DatabaseOPtionHelper.GetInstance().update(mWeighingBill);
                }));
            }
            catch (Exception e)
            {
                ConsoleHelper.writeLine($"Pint {mWeighingBill.id} failed:{e.Message}");
                this.Close();
            }
        }
Ejemplo n.º 25
0
        private PrintQueue FindPrinter(string printerName)
        {
            var printers = new PrintServer().GetPrintQueues();

            foreach (var printer in printers)
            {
                if (printer.FullName == printerName)
                {
                    return(printer);
                }
            }
            return(LocalPrintServer.GetDefaultPrintQueue());
        }
Ejemplo n.º 26
0
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            var viewModel = new PrintableUserControlViewModel(int.Parse(((ComboBoxItem)NumberOfLabelsToPrint.SelectedValue).Content.ToString()), (bool)FitToPage.IsChecked, (bool)NeedToShowDialog.IsChecked);

            for (int labelIndex = 0; labelIndex < viewModel.NumberOfLabelsToPrint; ++labelIndex)
            {
                viewModel.LabelViewModels[labelIndex].Text1 = string.Format("test{0}.1", labelIndex + 1);
                viewModel.LabelViewModels[labelIndex].Text2 = string.Format("test{0}.2", labelIndex + 1);
                viewModel.LabelViewModels[labelIndex].Text3 = string.Format("test{0}.3", labelIndex + 1);
            }

            var view = new PrintableUserControl(viewModel);

            PrintDialog printDialog = new PrintDialog();

            bool printDialogResult = true;

            if (viewModel.NeedToShowDialog)
            {
                printDialogResult = printDialog.ShowDialog() ?? false;
            }
            else
            {
                printDialog.PrintQueue                  = LocalPrintServer.GetDefaultPrintQueue(); // can also select one of new PrintServer().GetPrintQueues();
                printDialog.PrintTicket.CopyCount       = 1;                                       // number of copies
                printDialog.PrintTicket.PageOrientation = PageOrientation.Portrait;
            }

            if (viewModel.FitToPage)
            {
                //get selected printer capabilities
                System.Printing.PrintCapabilities capabilities = printDialog.PrintQueue.GetPrintCapabilities(printDialog.PrintTicket);

                //get scale of the printer to that of WPF control
                double scale = Math.Min(capabilities.PageImageableArea.ExtentWidth / view.ActualWidth, capabilities.PageImageableArea.ExtentHeight /
                                        view.ActualHeight);

                //Scare the control for printing size
                view.LayoutTransform = new ScaleTransform(scale, scale);

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

                //Update the layout of the control to the size of the printer page
                view.Measure(sizeOfPrinterPage);
                view.Arrange(new Rect(new Point(capabilities.PageImageableArea.OriginWidth, capabilities.PageImageableArea.OriginHeight), sizeOfPrinterPage));
            }

            //print the control to printer
            printDialog.PrintVisual(view, "Print title");
        }
        private void SetPrintDialogOptions(PrintDialog dlg)
        {
            if (dlg == null)
            {
                throw new ArgumentNullException();
            }

            dlg.PrintQueue = LocalPrintServer.GetDefaultPrintQueue();

            dlg.PrintTicket = dlg.PrintQueue.DefaultPrintTicket;
            dlg.PrintTicket.PageOrientation  = PageOrientation.Landscape;
            dlg.PrintTicket.OutputQuality    = OutputQuality.High;
            dlg.PrintTicket.TrueTypeFontMode = TrueTypeFontMode.DownloadAsNativeTrueTypeFont;
        }
Ejemplo n.º 28
0
        public void Print_Document()
        {
            try
            {
                PrintDialog printDialog = new PrintDialog();
                printDialog.PrintQueue  = LocalPrintServer.GetDefaultPrintQueue();
                printDialog.PrintTicket = printDialog.PrintQueue.DefaultPrintTicket;
                printDialog.PrintTicket.PageOrientation   = _pageOrientation;
                printDialog.PrintTicket.PageScalingFactor = 100;
                printDialog.PrintTicket.PageMediaSize     = new PageMediaSize(PageMediaSizeName.ISOA4);
                printDialog.PrintTicket.PageBorderless    = PageBorderless.None;
                printDialog.PageRangeSelection            = PageRangeSelection.AllPages;
                printDialog.UserPageRangeEnabled          = true;
                printDialog.CurrentPageEnabled            = true;

                printDialog.PrintTicket.PageResolution = new PageResolution(PageQualitativeResolution.High);
                if (printDialog.ShowDialog() == true)
                {
                    if (printDialog.PrintQueue.FullName == "Microsoft XPS Document Writer")
                    {
                        MessageWindow.Show("\"Microsoft XPS Document Writer\" not supported!!");
                        return;
                    }

                    DocumentViewer    viewer    = PrintView;
                    DocumentPaginator paginator = _fixedDocument.DocumentPaginator;
                    if (printDialog.PageRangeSelection == PageRangeSelection.UserPages)
                    {
                        paginator = new PageRangeDocumentPaginator(
                            _fixedDocument.DocumentPaginator,
                            printDialog.PageRange);
                    }
                    else if (printDialog.PageRangeSelection == PageRangeSelection.CurrentPage)
                    {
                        paginator = new CurrentPageDocumentPaginator(
                            _fixedDocument.DocumentPaginator,
                            PrintView.MasterPageNumber);
                    }
                    _fixedDocument.PrintTicket = printDialog.PrintTicket;
                    _documentName = _documentName.Replace("/", "-");
                    printDialog.PrintDocument(paginator, _documentName);
                }
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
            }
        }
Ejemplo n.º 29
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);
            }
        } // end PrintXPS method
Ejemplo n.º 30
0
        public static void Print(FixedPage page)//, string pageName
        {
            //page.UpdateLayout();
            PrintQueue defaultPrintQueue = LocalPrintServer.GetDefaultPrintQueue();

            //FixedPage若直接打印,则打印出来的内容为空白,因为height为0
            //推测原因:没有render
            //但先保存为文件,或加载到FixedDocument中就能打印,奇怪
            #region
            System.Printing.PrintCapabilities capabilities = defaultPrintQueue.GetPrintCapabilities();
            FixedDocument document = new FixedDocument();
            document.DocumentPaginator.PageSize = new Size(capabilities.PageImageableArea.ExtentWidth, capabilities.PageImageableArea.ExtentHeight);
            PageContent content = new PageContent();
            ((IAddChild)content).AddChild(page);
            document.Pages.Add(content);
            #endregion

            #region 根据打印机打印区域缩放page大小
            //System.Printing.PrintCapabilities capabilities = defaultPrintQueue.GetPrintCapabilities();
            ////get scale of the print wrt to screen of WPF visual
            //double scale = Math.Min(capabilities.PageImageableArea.ExtentWidth / page.ActualWidth, capabilities.PageImageableArea.ExtentHeight / page.ActualHeight);
            ////Transform the Visual to scale
            //page.LayoutTransform = new ScaleTransform(scale, scale);

            ////get the size of the printer page
            //Size sz = new Size(capabilities.PageImageableArea.ExtentWidth, capabilities.PageImageableArea.ExtentHeight);
            ////update the layout of the visual to the printer page size.
            //page.Measure(sz);
            //page.Arrange(new Rect(new Point(capabilities.PageImageableArea.OriginWidth, capabilities.PageImageableArea.OriginHeight), sz));
            #endregion

            try
            {
                //string path = SaveXPS(page, pageName);
                //PrintSystemJobInfo xpsPringtJob = defaultPrintQueue.AddJob(pageName + ".xps", path, true);
                XpsDocumentWriter xpsdw = PrintQueue.CreateXpsDocumentWriter(defaultPrintQueue);//如此会自动帮我们判定上面AddJob方法的第三个参数
                xpsdw.Write(document);
            }
            catch (Exception e)
            {
                MessageBox.Show("打印失败,失败原因:" + e.Message);
            }
            finally
            {
                defaultPrintQueue.Dispose();
            }
        }