Exemplo n.º 1
0
 internal PrintJobChangeEventArgs(int intJobID, string strJobName, JOBSTATUS jStatus, PrintSystemJobInfo objJobInfo)
 {
     _jobId     = intJobID;
     _jobName   = strJobName;
     _jobStatus = jStatus;
     _jobInfo   = objJobInfo;
 }
Exemplo n.º 2
0
        }//end SpotTroubleUsingJobAttributes

        // </SnippetSpotTroubleUsingJobAttributes>

        //<SnippetHandlePausedJob>
        internal static void HandlePausedJob(PrintSystemJobInfo theJob)
        {
            // If there's no good reason for the queue to be paused, resume it and
            // give user choice to resume or cancel the job.
            Console.WriteLine("The user or someone with administrative rights to the queue" +
                              "\nhas paused the job or queue." +
                              "\nResume the queue? (Has no effect if queue is not paused.)" +
                              "\nEnter \"Y\" to resume, otherwise press return: ");
            String resume = Console.ReadLine();

            if (resume == "Y")
            {
                theJob.HostingPrintQueue.Resume();

                // It is possible the job is also paused. Find out how the user wants to handle that.
                Console.WriteLine("Does user want to resume print job or cancel it?" +
                                  "\nEnter \"Y\" to resume (any other key cancels the print job): ");
                String userDecision = Console.ReadLine();
                if (userDecision == "Y")
                {
                    theJob.Resume();
                }
                else
                {
                    theJob.Cancel();
                }
            } //end if the queue should be resumed
        }     //end HandlePausedJob
Exemplo n.º 3
0
        /// <summary>
        /// Gets the most recently submitted job
        /// </summary>
        /// <returns>The most recent job, or null if there are no jobs</returns>
        private PrintSystemJobInfo getLastJob()
        {
            DateTime           latestJobTime = DateTime.Now;
            PrintSystemJobInfo latestJob     = null;

            PrintQueue queue;

            foreach (string queueName in queueNamesToBlock)
            {
                queue = new PrintQueue(printServer, queueName);
                queue.Refresh();

                foreach (var job in queue.GetPrintJobInfoCollection())
                {
                    job.Refresh();

                    var time = job.TimeJobSubmitted;

                    if (time > latestJobTime)
                    {
                        latestJobTime = time;
                        latestJob     = job;
                    }
                }
            }

            return(latestJob);
        }
Exemplo n.º 4
0
        }     //end HandlePausedJob

        //</SnippetHandlePausedJob>

        //<SnippetReportQueueAndJobAvailability>
        internal static void ReportQueueAndJobAvailability(PrintSystemJobInfo theJob)
        {
            if (!(ReportAvailabilityAtThisTime(theJob.HostingPrintQueue) && ReportAvailabilityAtThisTime(theJob)))
            {
                if (!ReportAvailabilityAtThisTime(theJob.HostingPrintQueue))
                {
                    Console.WriteLine("\nThat queue is not available at this time of day." +
                                      "\nJobs in the queue will start printing again at {0}",
                                      TimeConverter.ConvertToLocalHumanReadableTime(theJob.HostingPrintQueue.StartTimeOfDay).ToShortTimeString());
                    // TimeConverter class is defined in the complete sample
                }

                if (!ReportAvailabilityAtThisTime(theJob))
                {
                    Console.WriteLine("\nThat job is set to print only between {0} and {1}",
                                      TimeConverter.ConvertToLocalHumanReadableTime(theJob.StartTimeOfDay).ToShortTimeString(),
                                      TimeConverter.ConvertToLocalHumanReadableTime(theJob.UntilTimeOfDay).ToShortTimeString());
                }
                Console.WriteLine("\nThe job will begin printing as soon as it reaches the top of the queue after:");
                if (theJob.StartTimeOfDay > theJob.HostingPrintQueue.StartTimeOfDay)
                {
                    Console.WriteLine(TimeConverter.ConvertToLocalHumanReadableTime(theJob.StartTimeOfDay).ToShortTimeString());
                }
                else
                {
                    Console.WriteLine(TimeConverter.ConvertToLocalHumanReadableTime(theJob.HostingPrintQueue.StartTimeOfDay).ToShortTimeString());
                }
            } //end if at least one is not available
        }     //end ReportQueueAndJobAvailability
Exemplo n.º 5
0
        // получить статус задания
        public static string GetPrinterJobStatus(string prnName, string jobName)
        {
            string prnStatus = GetPrinterStatus(prnName);

            if (prnStatus == null)
            {
                return(null);
            }

            if (prnStatus.ToUpper() == "OK")
            {
                PrintQueue printer = GetPrintQueueByName(prnName);
                if (printer == null)
                {
                    return(null);
                }

                PrintSystemJobInfo job = printer.GetPrintJobInfoCollection().FirstOrDefault <PrintSystemJobInfo>(j => j.JobName == jobName);
                if (job == null)
                {
                    return(null);
                }
                else
                {
                    return(job.JobStatus.ToString());
                }
            }
            else
            {
                return(prnStatus);
            }
        }
Exemplo n.º 6
0
        private static Status CancelJob(PrintQueue printQueue, string uniqueFileName)
        {
            // If you do not "refresh" the print queue, then getting information about the jobs will fail.
            printQueue.Refresh();
            PrintJobInfoCollection jobs = printQueue.GetPrintJobInfoCollection();

            // Extension is pulled out because some applications omit the file extension when it creates the job name.
            string             fileName = Path.GetFileNameWithoutExtension(uniqueFileName);
            PrintSystemJobInfo jobInfo  = jobs.FirstOrDefault(j => j.Name.Contains(fileName));

            jobInfo?.Cancel();

            //wait for 20 seconds to check if the job got deleted
            DateTime expireTime = DateTime.Now + TimeSpan.FromSeconds(20);

            while (jobInfo.IsDeleting && DateTime.Now < expireTime)
            {
                Thread.Sleep(100);
            }

            if (jobInfo.IsDeleted)
            {
                return(Status.Passed);
            }
            return(Status.Failed);
        }
Exemplo n.º 7
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();
        }
Exemplo n.º 8
0
 private void pauseJob(PrintSystemJobInfo job)
 {
     if (!job.IsPaused && job.Submitter.Equals(Environment.UserName))
     {
         job.Pause();
         form.RestoreFromTray();
     }
 }
Exemplo n.º 9
0
 public PrintJobChangeEventArgs(int intJobID, string strJobName, JOBSTATUS jStatus, PrintSystemJobInfo objJobInfo)
     : base()
 {
     _jobID     = intJobID;
     _jobName   = strJobName;
     _jobStatus = jStatus;
     _jobInfo   = objJobInfo;
 }
 public PrintJobChangeEventArgs(int intJobID, string strJobName, JOBSTATUS jStatus, PrintSystemJobInfo objJobInfo )
     : base()
 {
     _jobID = intJobID;
     _jobName = strJobName;
     _jobStatus = jStatus;
     _jobInfo = objJobInfo;
 }
Exemplo n.º 11
0
 private PrintInfo(PrintSystemJobInfo info)
 {
     Size          = info.JobSize;
     Name          = info.Name;
     NumberOfPages = info.NumberOfPages;
     TimeStamp     = DateTime.Now;
     Id            = info.JobIdentifier;
 }
Exemplo n.º 12
0
 private void cmdResumeJob_Click(object sender, RoutedEventArgs e)
 {
     if (lstJobs.SelectedValue != null)
     {
         PrintQueue         queue = printServer.GetPrintQueue(lstQueues.SelectedValue.ToString());
         PrintSystemJobInfo job   = queue.GetJob((int)lstJobs.SelectedValue);
         job.Resume();
     }
 }
 internal PrintJobChangeEventArgs(int intJobID, string unicJobId, string strJobName, JOBSTATUS jStatus, JobDetail detail, PrintSystemJobInfo objJobInfo)
 {
     _jobId         = intJobID;
     _jobName       = strJobName;
     _jobStatus     = jStatus;
     _jobInfo       = objJobInfo;
     _jobDetail     = detail;
     UnicIdentOfJob = unicJobId;
 }
Exemplo n.º 14
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();
        }
Exemplo n.º 15
0
        private void resumeLastJob()
        {
            PrintSystemJobInfo lastJob = getLastJob();

            if (lastJob != null)
            {
                lastJob.Resume();
                lastJob.Refresh();
            }
        }
Exemplo n.º 16
0
        public void DeleteLastJob()
        {
            PrintSystemJobInfo lastJob = getLastJob();

            if (lastJob != null)
            {
                lastJob.Cancel();
                lastJob.Refresh();
            }
        }
Exemplo n.º 17
0
 public PrintJobChangeEventArgs(int intJobID, string strJobName, JOBSTATUS jStatus, PrintSystemJobInfo objJobInfo, uint uintJobTotalPages, short shortJobCopies)
     : base()
 {
     JobID         = intJobID;
     JobName       = strJobName;
     JobStatus     = jStatus;
     JobInfo       = objJobInfo;
     JobTotalPages = uintJobTotalPages;
     JobCopies     = shortJobCopies;
 }
Exemplo n.º 18
0
        private void cmdCancelJob_Click(object sender, RoutedEventArgs e)
        {
            if (lstJobs.SelectedValue != null)
            {
                PrintQueue         queue = printServer.GetPrintQueue(lstQueues.SelectedValue.ToString());
                PrintSystemJobInfo job   = queue.GetJob((int)lstJobs.SelectedValue);
                job.Cancel();

                lstQueues_SelectionChanged(null, null);
            }
        }
Exemplo n.º 19
0
 void ExportToXpsCompleted(Task <byte[]> task)
 {
     IsBusy = false;
     if (TaskIsFauledOrCancelled(task, "Print"))
     {
         return;
     }
     using (PrintSystemJobInfo jobInfo = PrintDialogService.PrintQueue.AddJob("Print Job Name")) {
         jobInfo.JobStream.Write(task.Result, 0, task.Result.Length);
     }
 }
Exemplo n.º 20
0
 public PrintJobChangeEventArgs(int intJobID, string strPrintName, string strDriveName, string strJobName, JOBSTATUS jStatus, PrintSystemJobInfo objJobInfo, int intJobSize)
     : base()
 {
     _jobID     = intJobID;
     _jobName   = strJobName;
     _printName = strPrintName;
     _driveName = strDriveName;
     _jobStatus = jStatus;
     _jobInfo   = objJobInfo;
     _jobSize   = intJobSize;
 }
Exemplo n.º 21
0
        }//end SpotTroubleUsingProperties

        // </SnippetSpotTroubleUsingJobProperties>

        // <SnippetSpotTroubleUsingJobAttributes>
        // Check for possible trouble states of a print job using the flags of the JobStatus property
        internal static void SpotTroubleUsingJobAttributes(PrintSystemJobInfo theJob)
        {
            if ((theJob.JobStatus & PrintJobStatus.Blocked) == PrintJobStatus.Blocked)
            {
                Console.WriteLine("The job is blocked.");
            }
            if (((theJob.JobStatus & PrintJobStatus.Completed) == PrintJobStatus.Completed)
                ||
                ((theJob.JobStatus & PrintJobStatus.Printed) == PrintJobStatus.Printed))
            {
                Console.WriteLine("The job has finished. Have user recheck all output bins and be sure the correct printer is being checked.");
            }
            if (((theJob.JobStatus & PrintJobStatus.Deleted) == PrintJobStatus.Deleted)
                ||
                ((theJob.JobStatus & PrintJobStatus.Deleting) == PrintJobStatus.Deleting))
            {
                Console.WriteLine("The user or someone with administration rights to the queue has deleted the job. It must be resubmitted.");
            }
            if ((theJob.JobStatus & PrintJobStatus.Error) == PrintJobStatus.Error)
            {
                Console.WriteLine("The job has errored.");
            }
            if ((theJob.JobStatus & PrintJobStatus.Offline) == PrintJobStatus.Offline)
            {
                Console.WriteLine("The printer is offline. Have user put it online with printer front panel.");
            }
            if ((theJob.JobStatus & PrintJobStatus.PaperOut) == PrintJobStatus.PaperOut)
            {
                Console.WriteLine("The printer is out of paper of the size required by the job. Have user add paper.");
            }

            if (((theJob.JobStatus & PrintJobStatus.Paused) == PrintJobStatus.Paused)
                ||
                ((theJob.HostingPrintQueue.QueueStatus & PrintQueueStatus.Paused) == PrintQueueStatus.Paused))
            {
                HandlePausedJob(theJob);
                //HandlePausedJob is defined in the complete example.
            }

            if ((theJob.JobStatus & PrintJobStatus.Printing) == PrintJobStatus.Printing)
            {
                Console.WriteLine("The job is printing now.");
            }
            if ((theJob.JobStatus & PrintJobStatus.Spooling) == PrintJobStatus.Spooling)
            {
                Console.WriteLine("The job is spooling now.");
            }
            if ((theJob.JobStatus & PrintJobStatus.UserIntervention) == PrintJobStatus.UserIntervention)
            {
                Console.WriteLine("The printer needs human intervention.");
            }
        }//end SpotTroubleUsingJobAttributes
Exemplo n.º 22
0
        /// <summary>
        /// Constructor de la ventna.
        /// </summary>
        /// <param name="printWrapper">Encapsula si se imprime o no el trabajo</param>
        /// <param name="jobToPrint">Trabajo que se desea imprimir</param>
        /// <param name="sqlConn">Datos de la conexión a la base de datos</param>
        public Print_Window(PrintJobWrapper printWrapper, PrintSystemJobInfo jobToPrint, SqlConnection sqlConn)
        {
            this.InitializeComponent();

            WindowFormat.CenterWindowOnScreen(this);

            _jobToPrint = jobToPrint;
            _printJobWrapper = printWrapper;
            _sqlConn = sqlConn;

            FillJobInfoFields();

            FillUserInfoFields();
        }
Exemplo n.º 23
0
        private void lstJobs_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (lstJobs.SelectedValue == null)
            {
                lblJobStatus.Text = "";
            }
            else
            {
                PrintQueue         queue = printServer.GetPrintQueue(lstQueues.SelectedValue.ToString());
                PrintSystemJobInfo job   = queue.GetJob((int)lstJobs.SelectedValue);

                lblJobStatus.Text = "Job Status: " + job.JobStatus.ToString();
            }
        }
Exemplo n.º 24
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
Exemplo n.º 25
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());
        }
Exemplo n.º 26
0
        /// <summary>
        /// StartDoc
        /// </summary>
        private void StartDoc(string jobName)
        {
            MediaSystem.Startup();

            if (IsPremium())
            {
                if (SpoolEdoc())
                {
                    // Job
                    PrintSystemJobInfo jobinfo = _queue.AddJob(typeof(PrintSystemEDocumentJob));

                    _eDocJob = jobinfo.JobData as PrintSystemEDocumentJob;

                    _eDocJob.Name = jobName;
                    _eDocJob.Commit();

                    // Document
                    PrintSystemDocument doc = _eDocJob.AddDocument("XAML Document");

                    doc.Name      = "XAML Document";
                    doc.JobTicket = _jobTicket.XmlStream;
                    doc.Commit();

                    // Rendition
                    _eDocRendition           = doc.AddRendition("Letter");
                    _eDocRendition.Name      = "A4 Rendition";
                    _eDocRendition.JobTicket = _jobTicket.XmlStream;
                    _eDocRendition.Commit();
                }
                else
                {
                    string filename = GetOutputFilename();

                    _stream             = new FileStream(filename, FileMode.Create, FileAccess.ReadWrite);
                    _writer             = new System.Xml.XmlTextWriter(_stream, System.Text.Encoding.UTF8);
                    _writer.Formatting  = System.Xml.Formatting.Indented;
                    _writer.Indentation = 4;
                    _writer.WriteStartElement("Document");
                    _writer.WriteAttributeString("xmlns", "http://schemas.microsoft.com/winfx/2006/xaml/presentation");
                    _writer.WriteAttributeString("xmlns:def", "http://schemas.microsoft.com/winfx/2006/xaml");
                    _writer.WriteStartElement("FixedPanel");
                }
            }
        }
Exemplo n.º 27
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);
            }
        }
Exemplo n.º 28
0
        }//end ReportAvailabilityAtThisTime

        //</SnippetPrintQueueStartUntil>

        // <SnippetUsingJobStartAndUntilTimes>
        private static Boolean ReportAvailabilityAtThisTime(PrintSystemJobInfo theJob)
        {
            Boolean available = true;

            if (theJob.StartTimeOfDay != theJob.UntilTimeOfDay) // If the job cannot be printed at all times of day
            {
                DateTime utcNow = DateTime.UtcNow;
                Int32    utcNowAsMinutesAfterMidnight = (utcNow.TimeOfDay.Hours * 60) + utcNow.TimeOfDay.Minutes;

                // If "now" is not within the range of available times . . .
                if (!((theJob.StartTimeOfDay < utcNowAsMinutesAfterMidnight)
                      &&
                      (utcNowAsMinutesAfterMidnight < theJob.UntilTimeOfDay)))
                {
                    available = false;
                }
            }
            return(available);
        }//end ReportAvailabilityAtThisTime
Exemplo n.º 29
0
        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");
            //}
        }
Exemplo n.º 30
0
        /// <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);
        }
Exemplo n.º 31
0
        internal static void HandlePausedJob(PrintSystemJobInfo theJob)
        {
            Console.WriteLine("The user or someone with administrative rights to the queue" +
                              "\nhas paused the job or queue." +
                              "\nResume the queue? (Has no effect if queue is not paused.)" +
                              "\nEnter \"Y\" to resume, otherwise press return: ");
            String resume = Console.ReadLine();

            if (resume == "Y")
            {
                theJob.HostingPrintQueue.Resume();
                Console.WriteLine("Does user want to resume print job or cancel it?" + "\nEnter \"Y\" to resume (any other key cancels the print job): ");
                String userDecision = Console.ReadLine();
                if (userDecision == "Y")
                {
                    theJob.Resume();
                }
                else
                {
                    theJob.Cancel();
                }
            }
        }
Exemplo n.º 32
0
        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
Exemplo n.º 33
0
 /// <summary>
 /// Constructor de la clase.
 /// </summary>
 /// <param name="printJob">Variable que indica que se desea imprimir un trabajo</param>
 /// <param name="currentPrintJob">Trabajo que se está imprimiendo actualmente</param>
 public PrintJobWrapper(bool printJob, PrintSystemJobInfo currentPrintJob)
 {
     PrintJob = printJob;
     CurrentPrintingJob = currentPrintJob;
 }
Exemplo n.º 34
0
        /// <summary>
        /// Método que checa si se está cargando o no el trabajo.
        /// </summary>
        /// <param name="job">Trabajo que checaremos, para comprobar que se está cargando</param>
        /// <returns>true si se está cargando aún el archivo, false en caso contrario</returns>
        private bool IsJobSpooling(PrintSystemJobInfo job)
        {
            if (job.IsSpooling)
            {
                MessageBox.Show("Wait until the file is completely loaded.", "Print queue", MessageBoxButton.OK, MessageBoxImage.Warning);
                return true;
            }
            else
            {
                return false;
            }

        }