public void Watch_With_All_Filters_Should_Call_Event() { spoolWatcher.PrinterChange = PrinterChange.PRINTER_CHANGE_ADD_FORM | PrinterChange.PRINTER_CHANGE_CONFIGURE_PORT; spoolWatcher.PrinterNotifyFilter = PrinterNotifyFilters.DATATYPE | PrinterNotifyFilters.STATUS; spoolWatcher.JobNotifyFilter = JobNotifyFilters.DATATYPE | JobNotifyFilters.STATUS; spoolWatcher.Start(); using var waitEv = new ManualResetEventSlim(); spoolWatcher.SpoolerNotificationReached += (o, e) => { waitEv.Set(); }; var job = printQueue.AddJob(); var bytes = Encoding.UTF8.GetBytes("Test printing"); job.JobStream.Write(bytes, 0, bytes.Length); job.JobStream.Close(); Assert.That(waitEv.Wait(timeout: TimeSpan.FromSeconds(10))); spoolWatcher.Stop(); }
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(); }
private void AfterInvokePrint() { if (print == true) { string filename = System.IO.Path.GetTempPath() + "IronPlotPrint.xps"; Package package = Package.Open(filename, FileMode.Create); XpsDocument xpsDoc = new XpsDocument(package); XpsDocumentWriter xpsWriter = XpsDocument.CreateXpsDocumentWriter(xpsDoc); bool direct2D = UseDirect2D; if (direct2D) { UseDirect2D = false; } try { UpdateLayout(); xpsWriter.Write(PlotPanel); xpsDoc.Close(); package.Close(); } finally { if (direct2D) { UseDirect2D = true; } } PrintQueue printQueue = printDialog.PrintQueue; Application.Current.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal, new Action(delegate() { printQueue.AddJob("IronPlot Print", filename, false); })); } }
private void button3_Click(object sender, RoutedEventArgs e) { LocalPrintServer lps = new LocalPrintServer(); PrintQueue pq = lps.DefaultPrintQueue; pq.AddJob("Demo #1", @"C:\demo.xps", false); }
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; }
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(); }
internal static void Print(string filePath, PrintQueue printer, Duplexing?duplexing, bool hole, Stapling?stapling) { if ((duplexing != null) && duplexing.HasValue) { printer.CurrentJobSettings.CurrentPrintTicket.Duplexing = duplexing; } if ((stapling != null) && stapling.HasValue) { printer.CurrentJobSettings.CurrentPrintTicket.Stapling = stapling; } printer.AddJob(Path.GetFileName(filePath), filePath, false).Dispose(); Delete(filePath); }
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
private static void WorkerMethodShared(object state) { Logger.GetInstance().Debug("Started Printing for MyDLP printer: " + sharedPrinterName); PrintQueue pQueue = null; try { PrinterController controller = PrinterController.getInstance(); LocalPrintServer pServer = new LocalPrintServer(); PrintQueueCollection qCollection = pServer.GetPrintQueues(); foreach (PrintQueue q in qCollection) { //Find mathing non secure printer if (q.Name == sharedPrinterName) { pQueue = q; } } if (pQueue == null) { throw new Exception("Unable to find a matching non secure printer for mydlp printer: " + sharedPrinterName); } Logger.GetInstance().Debug("Adding print job on real printer: " + pQueue.Name + ", path:" + sharedXpsPath + ", sharedJobID:" + sharedJobId); if (WaitForFile(sharedXpsPath)) { pQueue.AddJob(sharedJobId, sharedXpsPath, false); Thread.Sleep(1000); Logger.GetInstance().Debug("Removing:" + sharedXpsPath); File.Delete(sharedXpsPath); Logger.GetInstance().Debug("Finished Printing"); } else { Logger.GetInstance().Debug("WorkerMethodShared WaitForFile failed for xps file"); } } catch (Exception e) { Logger.GetInstance().Error("WorkerMethodShared Exception" + e); if (e.InnerException != null) { Logger.GetInstance().Error(e.InnerException.Message + e.InnerException.StackTrace); } } }
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()); }
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); } }
private void btn_Print_Click(object sender, RoutedEventArgs e) { //try //{ string textToPrint = txt_Console.Text; if (fontName == String.Empty) { fontName = "Consolas"; fontStyles = 0; fontSize = 12; } textColor = ((SolidColorBrush)txt_Console.Foreground).Color; PrintableDocument printableDocument = new PrintableDocument(); Font f = new Font(fontName, fontSize, (FontStyle)fontStyles); printableDocument.PrintPage += delegate(object o, PrintPageEventArgs args) { args.Graphics.DrawString(textToPrint, f, new SolidBrush(System.Drawing.Color.Black), 0, 0); }; #if DEBUG Assembly ass = Assembly.GetEntryAssembly(); string directory = ass.Location; string fileName = directory.Substring(0, directory.Length - 21) + @"\Test Print"; printableDocument.PrinterSettings.PrintToFile = true; printableDocument.PrinterSettings.PrintFileName = fileName; printableDocument.PrinterSettings.Copies = 1; txt_Console.Text += "\n Printing To File: " + printableDocument.PrinterSettings.PrintFileName + "\n"; txt_Console.CaretIndex = txt_Console.Text.Length; printableDocument.Print(); PrintSystemJobInfo info = defaultPrintQueue.AddJob(fileName, fileName, false); #else printableDocument.PrinterSettings.PrintToFile = false; printableDocument.Print(); #endif //} //catch (Exception ex) //{ // System.Console.WriteLine(ex.StackTrace); // MessageBox.Show("There was an error while printing the document"); //} }
/// <summary> /// Add a batch of XPS documents to the print queue using a PrintQueue.AddJob method. /// </summary> /// <param name="xpsFilePaths">A collection of XPS documents.</param> /// <param name="fastCopy">Whether to validate the XPS documents.</param> /// <returns>Whether all documents were added to the print queue.</returns> public static bool BatchAddToPrintQueue(IEnumerable <string> xpsFilePaths, bool fastCopy) { bool allAdded = true; // To print without getting the "Save Output File As" dialog, ensure // that your default printer is not the Microsoft XPS Document Writer, // Microsoft Print to PDF, or other print-to-file option. // Get a reference to the default print queue. PrintQueue defaultPrintQueue = LocalPrintServer.GetDefaultPrintQueue(); // Iterate through the document collection. foreach (string xpsFilePath in xpsFilePaths) { // Get document name. string xpsFileName = Path.GetFileName(xpsFilePath); try { // The AddJob method adds a new print job for an XPS // document into the print queue, and assigns a job name. // Use fastCopy to skip XPS validation and progress notifications. // If fastCopy is false, the thread that calls PrintQueue.AddJob // must have a single-threaded apartment state. PrintSystemJobInfo xpsPrintJob = defaultPrintQueue.AddJob(jobName: xpsFileName, documentPath: xpsFilePath, fastCopy); // If the queue is not paused and the printer is working, then jobs will automatically begin printing. Debug.WriteLine($"Added {xpsFileName} to the print queue."); } catch (PrintJobException e) { allAdded = false; Debug.WriteLine($"Failed to add {xpsFileName} to the print queue: {e.Message}\r\n{e.InnerException}"); } } return(allAdded); }
public static void PrintXPS(object sender) { string text = sender.ToString(); new LocalPrintServer(); PrintQueue defaultPrintQueue = LocalPrintServer.GetDefaultPrintQueue(); bool arg_19_0 = defaultPrintQueue.IsXpsDevice; FileInfo fileInfo = new FileInfo(text); try { defaultPrintQueue.AddJob(fileInfo.Name, text, false); } catch (PrintJobException ex) { MessageBox.Show(string.Format("\n\t{0} 无法加入打印队列,请查看打印机设置.", fileInfo.Name)); if (ex.InnerException.Message == "File contains corrupted data.") { MessageBox.Show("\t文档结构出错,请重试"); } } }
static void Main(string[] args) { //<SnippetAddUnnamedJob> // Create the printer server and print queue objects LocalPrintServer localPrintServer = new LocalPrintServer(); PrintQueue defaultPrintQueue = LocalPrintServer.GetDefaultPrintQueue(); // Call AddJob PrintSystemJobInfo myPrintJob = defaultPrintQueue.AddJob(); // Write a Byte buffer to the JobStream and close the stream Stream myStream = myPrintJob.JobStream; Byte[] myByteBuffer = UnicodeEncoding.Unicode.GetBytes("This is a test string for the print job stream."); myStream.Write(myByteBuffer, 0, myByteBuffer.Length); myStream.Close(); //</SnippetAddUnnamedJob> //<SnippetAddNamedJob> // Create the printer server and print queue objects LocalPrintServer localPrintServer2 = new LocalPrintServer(); PrintQueue defaultPrintQueue2 = LocalPrintServer.GetDefaultPrintQueue(); // Call AddJob PrintSystemJobInfo anotherPrintJob = defaultPrintQueue2.AddJob("MyJob"); // Read a file into a StreamReader StreamReader myStreamReader = new StreamReader("C:\\test.txt"); // Write a Byte buffer to the JobStream and close the stream Stream anotherStream = anotherPrintJob.JobStream; Byte[] anotherByteBuffer = UnicodeEncoding.Unicode.GetBytes(myStreamReader.ReadToEnd()); anotherStream.Write(anotherByteBuffer, 0, anotherByteBuffer.Length); anotherStream.Close(); //</SnippetAddNamedJob> } //end Main
private void PrintImage(string fileName, Int32Rect crop, int quantity) { Console.WriteLine(" Print image " + fileName + " in " + quantity.ToString() + " copies."); PrintTicket ticket = _printer.UserPrintTicket; Size paper = new Size(Math.Max(ticket.PageMediaSize.Width.Value, ticket.PageMediaSize.Height.Value), Math.Min(ticket.PageMediaSize.Width.Value, ticket.PageMediaSize.Height.Value)); Size format = new Size(Math.Max(_width, _height) * 96 / 25.4, Math.Min(_width, _height) * 96 / 25.4); double printableWidth; double printableHeight; if (format.Width <= paper.Width && format.Height <= paper.Height) { printableWidth = format.Width; printableHeight = format.Height; } else if (format.Width <= paper.Height && format.Height <= paper.Width) { printableWidth = format.Height; printableHeight = format.Width; } else { printableWidth = paper.Width; printableHeight = paper.Height; } // Swap printable width and height if page orientation is portarait if (ticket.PageOrientation == PageOrientation.Portrait || ticket.PageOrientation == PageOrientation.ReversePortrait) { double temp = printableWidth; printableWidth = printableHeight; printableHeight = temp; } fileName = _orderFolder + fileName; // Create FixedDocument containing the image var fixedDocument = new FixedDocument(); var pageContent = new PageContent(); var fixedPage = new FixedPage(); var image = CreateImage(fileName, printableWidth, printableHeight, crop); fixedPage.Width = printableWidth; fixedPage.Height = printableHeight; fixedPage.Children.Add(image); ((IAddChild)pageContent).AddChild(fixedPage); fixedDocument.Pages.Add(pageContent); // Save FixedDocument to XPS file string xpsFilePath = fileName + _width.ToString() + "x" + _height.ToString() + ".xps"; using (FileStream outputStream = File.Create(xpsFilePath)) { var package = Package.Open(outputStream, FileMode.Create); var xpsDoc = new XpsDocument(package, CompressionOption.Normal); var xpsWriter = XpsDocument.CreateXpsDocumentWriter(xpsDoc); var fixedDocSeq = new FixedDocumentSequence(); var docRef = new DocumentReference(); docRef.BeginInit(); docRef.SetDocument(fixedDocument); docRef.EndInit(); ((IAddChild)fixedDocSeq).AddChild(docRef); xpsWriter.Write(fixedDocSeq.DocumentPaginator); xpsDoc.Close(); package.Close(); } // Add the XPS file to print queue for (int i = 0; i < quantity; i++) { _printer.AddJob("Photo Kiosk", xpsFilePath, false); _success = true; } }
private static void WorkerMethodLocal(object state) { Logger.GetInstance().Debug("Started Printing for MyDLP printer: " + localPrinterName); PrintQueue pQueue = null; try { PrinterController controller = PrinterController.getInstance(); if (controller.IsPrinterConnection(localPrinterName)) { //It will be printerd remotely //It is a network printer connection on local computer PrinterController.PrinterConnection connection = controller.GetPrinterConnection(localPrinterName); IPAddress[] addresslist = Dns.GetHostAddresses(connection.server); Logger.GetInstance().Debug("Initiating remote print remoteprinter: " + connection.name + " on server:" + connection.server + "of File:" + localXpsPath); SeapClient.InitiateRemotePrint(localJobId, connection.name, addresslist[0].ToString(), localXpsPath); } else { //It is a local printer LocalPrintServer pServer = new LocalPrintServer(); PrintQueueCollection qCollection = pServer.GetPrintQueues(); foreach (PrintQueue q in qCollection) { //Find mathing non secure printer if (PrinterController.GetSecurePrinterName(q.Name) == localPrinterName) { pQueue = q; } } if (pQueue == null) { throw new Exception("Unable to find a matching non secure printer for mydlp printer: " + localPrinterName); } Logger.GetInstance().Debug("Adding print job on real printer: " + pQueue.Name + ", path:" + localXpsPath + ", jobID:" + localJobId); if (WaitForFile(localXpsPath)) { pQueue.AddJob(localJobId, localXpsPath, false); Thread.Sleep(1000); Logger.GetInstance().Debug("Removing:" + localXpsPath); File.Delete(localXpsPath); File.Delete(metaPath); Logger.GetInstance().Debug("Finished Printing"); } else { Logger.GetInstance().Debug("WorkerMethodLocal WaitForFile failed for xps file"); } } } catch (Exception e) { Logger.GetInstance().Error("WorkerMethod Exception" + e); if (e.InnerException != null) { Logger.GetInstance().Error(e.InnerException.Message + e.InnerException.StackTrace); } } }
static void Main() { string[] args = Environment.GetCommandLineArgs(); // For the sake of this example, we're just printing the arguments to the console. for (int i = 0; i < args.Length; i++) { Console.WriteLine("args[{0}] == {1}", i, args[i]); } String file = String.Empty; if (args.Length == 3) { //check that there is a XPS file file = args[2]; //"Sample.xps"; } //If args < 3 => app is invoked directly and not from OS print operation. In this //case we will simply show a dialog that printer has been installed. if (args.Length < 3) { MessageBox.Show("Printer has been installed. You can now print to Centennial PDF Printer from any application.", "Centennial PDF Printer"); return; } //At this point in time, the app can take this XPS file and choose to do anything //with this file. For e.g., programmatically convert it to another format like //PDF. There are 3P libraries available as well that can be used to achieve //the same. //For simplicity, we will use the inbox 'Microsoft Print to PDF' soft printer //to convert the XPS to PDF by simply adding XPS print job as a job to this PDF //Printer. try { // Create print server and print queue. LocalPrintServer localPrintServer = new LocalPrintServer(); PrintQueue defaultPrintQueue = LocalPrintServer.GetDefaultPrintQueue(); PrintQueueCollection queueCollection = localPrintServer.GetPrintQueues(); PrintQueue selectedPrintQueue = null; foreach (PrintQueue pq in queueCollection) { if (pq.FullName == "Microsoft Print to PDF") //PrinterName is a classmember { selectedPrintQueue = pq; } } try { // Print the Xps file while providing XPS validation and progress notifications. PrintSystemJobInfo xpsPrintJob = selectedPrintQueue.AddJob("Centennial Test PDF Print Job", file, false); } catch (Exception e) { Console.WriteLine("\n\t{0} could not be added to the print queue.", file.ToString()); 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."); } } } catch (Exception e) { Console.WriteLine("The file could not be read:"); Console.WriteLine(e.Message); } }
public RealPrintSystemJobInfo(PrintQueue queue) { job = queue.AddJob(); }
private void DoPrintJonWithModelSerial(IPrintObject model) { PrintQueue.AddJob(model); printEvent.Set(); }