PrintQueue.AddJob Method

Definition

Inserts a new print job into the queue.

Overloads

AddJob(String, String, Boolean, PrintTicket)

Inserts a new print job for an XML Paper Specification (XPS) Document into the queue, gives it the specified name and settings, and specifies whether or not it should be validated.

AddJob(String, PrintTicket)

Inserts a new print job for an XML Paper Specification (XPS) Document into the queue, and gives it the specified name and settings.

AddJob(String, String, Boolean)

Inserts a new print job for an XML Paper Specification (XPS) Document into the queue, gives it the specified name, and specifies whether or not it should be validated.

AddJob()

Inserts a new (generically named) print job, whose content is a Byte array, into the queue.

AddJob(String)

Inserts a new print job, whose content is a Byte array, into the queue.

Remarks

Unless the queue is paused or in an error state, the job prints when it reaches the top of the queue, so this is a printing function.

Other ways to print in Windows Presentation Foundation (WPF) include the PrintDialog.PrintDocument method, which can be used with or without opening the dialog, and the many Write and WriteAsync methods of the XpsDocumentWriter.

AddJob(String, String, Boolean, PrintTicket)

Inserts a new print job for an XML Paper Specification (XPS) Document into the queue, gives it the specified name and settings, and specifies whether or not it should be validated.

public:
 System::Printing::PrintSystemJobInfo ^ AddJob(System::String ^ jobName, System::String ^ documentPath, bool fastCopy, System::Printing::PrintTicket ^ printTicket);
public System.Printing.PrintSystemJobInfo AddJob (string jobName, string documentPath, bool fastCopy, System.Printing.PrintTicket printTicket);
member this.AddJob : string * string * bool * System.Printing.PrintTicket -> System.Printing.PrintSystemJobInfo
Public Function AddJob (jobName As String, documentPath As String, fastCopy As Boolean, printTicket As PrintTicket) As PrintSystemJobInfo

Parameters

jobName
String

The path and name of the document that is being printed.

documentPath
String

The path and name of the document that is being printed.

fastCopy
Boolean

true to spool quickly without page-by-page progress feedback and without validating that the file is valid XPS; otherwise, false.

printTicket
PrintTicket

The settings of the print job.

Returns

A PrintSystemJobInfo that represents the print job and its status.

Remarks

For more information, see AddJob(String, String, Boolean).

Applies to

AddJob(String, PrintTicket)

Inserts a new print job for an XML Paper Specification (XPS) Document into the queue, and gives it the specified name and settings.

public:
 System::Printing::PrintSystemJobInfo ^ AddJob(System::String ^ jobName, System::Printing::PrintTicket ^ printTicket);
public System.Printing.PrintSystemJobInfo AddJob (string jobName, System.Printing.PrintTicket printTicket);
member this.AddJob : string * System.Printing.PrintTicket -> System.Printing.PrintSystemJobInfo
Public Function AddJob (jobName As String, printTicket As PrintTicket) As PrintSystemJobInfo

Parameters

jobName
String

The path and name of the document that is being printed.

printTicket
PrintTicket

The settings of the print job.

Returns

A PrintSystemJobInfo that represents the print job and its status.

Remarks

For more information, see AddJob(String).

Applies to

AddJob(String, String, Boolean)

Inserts a new print job for an XML Paper Specification (XPS) Document into the queue, gives it the specified name, and specifies whether or not it should be validated.

public:
 System::Printing::PrintSystemJobInfo ^ AddJob(System::String ^ jobName, System::String ^ documentPath, bool fastCopy);
public System.Printing.PrintSystemJobInfo AddJob (string jobName, string documentPath, bool fastCopy);
member this.AddJob : string * string * bool -> System.Printing.PrintSystemJobInfo
Public Function AddJob (jobName As String, documentPath As String, fastCopy As Boolean) As PrintSystemJobInfo

Parameters

jobName
String

The name of the print job.

documentPath
String

The path and name of the document that is being printed.

fastCopy
Boolean

true to spool quickly without page-by-page progress feedback and without validating that the file is valid XPS; otherwise, false.

Returns

A PrintSystemJobInfo that represents the print job and its status.

Examples

The following example shows how to use AddJob(String, String, Boolean) to batch print all the XML Paper Specification (XPS) files in a directory.

class Program
{
    [System.MTAThreadAttribute()] // Added for clarity, but this line is redundant because MTA is the default.
    static void Main(string[] args)
    {
        // Create the secondary thread and pass the printing method for 
        // the constructor's ThreadStart delegate parameter. The BatchXPSPrinter
        // class is defined below.
        Thread printingThread = new Thread(BatchXPSPrinter.PrintXPS);

        // Set the thread that will use PrintQueue.AddJob to single threading.
        printingThread.SetApartmentState(ApartmentState.STA);

        // Start the printing thread. The method passed to the Thread 
        // constructor will execute.
        printingThread.Start();
    }
}

public class BatchXPSPrinter
{
    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();
    }
}
Friend Class Program
    <System.MTAThreadAttribute()>
    Shared Sub Main(ByVal args() As String) ' Added for clarity, but this line is redundant because MTA is the default.
        ' Create the secondary thread and pass the printing method for 
        ' the constructor's ThreadStart delegate parameter. The BatchXPSPrinter
        ' class is defined below.
        Dim printingThread As New Thread(AddressOf BatchXPSPrinter.PrintXPS)

        ' Set the thread that will use PrintQueue.AddJob to single threading.
        printingThread.SetApartmentState(ApartmentState.STA)

        ' Start the printing thread. The method passed to the Thread 
        ' constructor will execute.
        printingThread.Start()

    End Sub

End Class

Public Class BatchXPSPrinter
    Public Shared Sub PrintXPS()
        ' Create print server and print queue.
        Dim localPrintServer As New LocalPrintServer()
        Dim defaultPrintQueue As PrintQueue = LocalPrintServer.GetDefaultPrintQueue()

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

        ' If the user mistyped, end the thread and return to the Main thread.
        If Not dir.Exists Then
            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 Then
                Console.WriteLine("There are no XPS files in the directory.")
            Else
                Console.WriteLine(vbLf & "Jobs 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.
                For Each f As FileInfo In dir.GetFiles("*.xps")
                    Dim nextFile As String = directoryPath & "\" & f.Name
                    Console.WriteLine("Adding {0} to queue.", nextFile)

                    Try
                        ' Print the Xps file while providing XPS validation and progress notifications.
                        Dim xpsPrintJob As PrintSystemJobInfo = defaultPrintQueue.AddJob(f.Name, nextFile, False)
                    Catch e As PrintJobException
                        Console.WriteLine(vbLf & vbTab & "{0} could not be added to the print queue.", f.Name)
                        If e.InnerException.Message = "File contains corrupted data." Then
                            Console.WriteLine(vbTab & "It is not a valid XPS file. Use the isXPS Conformance Tool to debug it.")
                        End If
                        Console.WriteLine(vbTab & "Continuing with next XPS file." & vbLf)
                    End Try

                Next f ' end for each XPS file

            End If 'end if there are no XPS files in the directory

        End If 'end if the directory does not exist

        Console.WriteLine("Press Enter to end program.")
        Console.ReadLine()

    End Sub

End Class

Remarks

If fastCopy is true, then the printer must be an Printing Overview. If it is not, the AddJob(String, String, Boolean) method throws an exception.

If fastCopy is false, then it is not necessary to use an XPSDrv printer. The XPS file being added to the queue is converted to the printer's page description language, such as PCL or Postscript. However, this kind of printing makes a call to Component Object Model (COM). The call to COM requires that the calling thread have a single-threaded apartment (STA) instead of multiple-threaded apartment (MTA) which is the default in Microsoft .NET 2.0 and later. (For more on threading and apartment states, see Managed and Unmanaged Threading, and ApartmentState.) There are two ways of doing this:

  • The simplest way is to add the STAThreadAttribute (that is, "[System.STAThreadAttribute()]") just above the first line of the application's Main method (usually "static void Main(string[] args)").

  • If you need your Main thread's apartment state to be MTA, you can house the call to AddJob(String, String, Boolean) in a separate thread whose apartment state is set to STA with SetApartmentState. The example below illustrates this second technique.

Note

You cannot apply the STAThreadAttribute to any method except Main and you cannot use SetApartmentState for the Main thread.

Other ways to print in Windows Presentation Foundation (WPF) include the PrintDialog.PrintDocument method, which can be used with or without opening the dialog, and the many Write and WriteAsync methods of the XpsDocumentWriter.

See also

Applies to

AddJob()

Inserts a new (generically named) print job, whose content is a Byte array, into the queue.

public:
 System::Printing::PrintSystemJobInfo ^ AddJob();
public System.Printing.PrintSystemJobInfo AddJob ();
member this.AddJob : unit -> System.Printing.PrintSystemJobInfo
Public Function AddJob () As PrintSystemJobInfo

Returns

A PrintSystemJobInfo that represents the print job and its status.

Examples

The following example shows how to use AddJob() to send a Byte array to a print queue. This code only works with printers that can detect and print plain text. Some of them cannot.

// 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();
' Create the printer server and print queue objects
Dim localPrintServer As New LocalPrintServer()
Dim defaultPrintQueue As PrintQueue = LocalPrintServer.GetDefaultPrintQueue()

' Call AddJob
Dim myPrintJob As PrintSystemJobInfo = defaultPrintQueue.AddJob()

' Write a Byte buffer to the JobStream and close the stream
Dim myStream As Stream = myPrintJob.JobStream
Dim myByteBuffer() As Byte = UnicodeEncoding.Unicode.GetBytes("This is a test string for the print job stream.")
myStream.Write(myByteBuffer, 0, myByteBuffer.Length)
myStream.Close()

Remarks

Use this method to write device specific information, to a spool file, that is not automatically included by the Microsoft Windows spooler. Of course, you need to know whether the spool file is Enhanced Metafile (EMF) or XML Paper Specification (XPS). If you prefer to work with the Stream API, you can use the PrintQueueStream class instead of this method.

After the AddJob method has been called, you must write a Byte array to the JobStream property of the PrintSystemJobInfo that is returned by AddJob or no print job is created. This array is what prints if the printer is working and is not paused.

Caution

If the JobStream is not closed with Close before the end of the thread in which AddJob is called, then an InvalidOperationException is thrown when that thread ends because the spooler thread cannot gain control over the Stream object.

In the print queue's graphical user interface (GUI), the job has the name "Print System Document". To give the job a different name, use the AddJob(String) overload.

Other ways to print in Windows Presentation Foundation (WPF) include the PrintDialog.PrintDocument method, which can be used with or without opening the dialog, and the many Write and WriteAsync methods of the XpsDocumentWriter.

Applies to

AddJob(String)

Inserts a new print job, whose content is a Byte array, into the queue.

public:
 System::Printing::PrintSystemJobInfo ^ AddJob(System::String ^ jobName);
public System.Printing.PrintSystemJobInfo AddJob (string jobName);
member this.AddJob : string -> System.Printing.PrintSystemJobInfo
Public Function AddJob (jobName As String) As PrintSystemJobInfo

Parameters

jobName
String

The name of the print job.

Returns

A PrintSystemJobInfo that represents the print job and its status.

Examples

The following example shows how to use AddJob(String) to read a file into a Byte array and send the array to a print queue. This code assumes that there is a file called test.txt in the root of the C: drive. This code only works with printers that can detect and print plain text. Some of them cannot.

// 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();
' Create the printer server and print queue objects
Dim localPrintServer2 As New LocalPrintServer()
Dim defaultPrintQueue2 As PrintQueue = LocalPrintServer.GetDefaultPrintQueue()

' Call AddJob 
Dim anotherPrintJob As PrintSystemJobInfo = defaultPrintQueue2.AddJob("MyJob")

' Read a file into a StreamReader
Dim myStreamReader As New StreamReader("C:\test.txt")

' Write a Byte buffer to the JobStream and close the stream
Dim anotherStream As Stream = anotherPrintJob.JobStream
Dim anotherByteBuffer() As Byte = UnicodeEncoding.Unicode.GetBytes(myStreamReader.ReadToEnd())
anotherStream.Write(anotherByteBuffer, 0, anotherByteBuffer.Length)
anotherStream.Close()

Remarks

Use this method to write device specific information, to a spool file, that is not automatically included by the Microsoft Windows spooler. Of course, you need to know whether the spool file is Enhanced Metafile (EMF) or XML Paper Specification (XPS). If you prefer to work with the Stream API, you can use the PrintQueueStream class instead of this method.

After the AddJob method has been called, you must write a Byte array to the JobStream property of the PrintSystemJobInfo that is returned by AddJob or no print job is created. This array is what prints if the printer is working and is not paused.

Caution

If the JobStream is not closed with Close before the end of the thread in which AddJob is called, then an InvalidOperationException is thrown when that thread ends because the spooler thread cannot gain control over the Stream object.

Other ways to print in Windows Presentation Foundation (WPF) include the PrintDialog.PrintDocument method, which can be used with or without opening the dialog, and the many Write and WriteAsync methods of the XpsDocumentWriter.

Applies to