PrintQueue.AddJob Método

Definición

Inserta un nuevo trabajo de impresión en la cola.

Sobrecargas

AddJob(String, String, Boolean, PrintTicket)

Inserta un nuevo trabajo de impresión para un documento de especificación de papel XML (XPS) en la cola, le proporciona el nombre y la configuración especificados y especifica si se debe validar o no.

AddJob(String, PrintTicket)

Inserta un nuevo trabajo de impresión para un documento de especificación de papel XML (XPS) en la cola y le proporciona el nombre y la configuración especificados.

AddJob(String, String, Boolean)

Inserta un nuevo trabajo de impresión para un documento de especificación de papel XML (XPS) en la cola, le da el nombre especificado y especifica si se debe validar o no.

AddJob()

Inserta un nuevo (denominado de forma genérica) trabajo de impresión, cuyo contenido es una matriz Byte, en la cola.

AddJob(String)

Inserta un nuevo trabajo de impresión, cuyo contenido es una matriz Byte, en la cola.

Comentarios

A menos que la cola esté en pausa o en un estado de error, el trabajo se imprime cuando llega a la parte superior de la cola, por lo que se trata de una función de impresión.

Otras formas de imprimir en Windows Presentation Foundation (WPF) incluyen el PrintDialog.PrintDocument método , que se puede usar con o sin abrir el cuadro de diálogo, y los muchos Write métodos y WriteAsync de XpsDocumentWriter.

AddJob(String, String, Boolean, PrintTicket)

Inserta un nuevo trabajo de impresión para un documento de especificación de papel XML (XPS) en la cola, le proporciona el nombre y la configuración especificados y especifica si se debe validar o no.

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

Parámetros

jobName
String

Ruta de acceso y nombre del documento que se va a imprimir.

documentPath
String

Ruta de acceso y nombre del documento que se va a imprimir.

fastCopy
Boolean

true para colar rápidamente sin comentarios de progreso de página a página y sin validar que el archivo es XPS válido; de lo contrario, false.

printTicket
PrintTicket

Los valores del trabajo de impresión.

Devoluciones

Objeto PrintSystemJobInfo que representa el trabajo de impresión y su estado.

Comentarios

Para obtener más información, vea AddJob(String, String, Boolean).

Se aplica a

AddJob(String, PrintTicket)

Inserta un nuevo trabajo de impresión para un documento de especificación de papel XML (XPS) en la cola y le proporciona el nombre y la configuración especificados.

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

Parámetros

jobName
String

Ruta de acceso y nombre del documento que se va a imprimir.

printTicket
PrintTicket

Los valores del trabajo de impresión.

Devoluciones

Objeto PrintSystemJobInfo que representa el trabajo de impresión y su estado.

Comentarios

Para obtener más información, vea AddJob(String).

Se aplica a

AddJob(String, String, Boolean)

Inserta un nuevo trabajo de impresión para un documento de especificación de papel XML (XPS) en la cola, le da el nombre especificado y especifica si se debe validar o no.

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

Parámetros

jobName
String

Nombre del trabajo de impresión.

documentPath
String

Ruta de acceso y nombre del documento que se va a imprimir.

fastCopy
Boolean

true para colar rápidamente sin comentarios de progreso de página a página y sin validar que el archivo es XPS válido; de lo contrario, false.

Devoluciones

Objeto PrintSystemJobInfo que representa el trabajo de impresión y su estado.

Ejemplos

En el ejemplo siguiente se muestra cómo usar AddJob(String, String, Boolean) para imprimir por lotes todos los archivos XML Paper Specification (XPS) de un directorio.

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

Comentarios

Si fastCopy es true, la impresora debe ser información general de impresión. Si no es así, el AddJob(String, String, Boolean) método produce una excepción.

Si fastCopy es false, no es necesario usar una impresora XPSDrv. El archivo XPS que se va a agregar a la cola se convierte en el lenguaje de descripción de página de la impresora, como PCL o Postscript. Sin embargo, este tipo de impresión realiza una llamada al Modelo de objetos componentes (COM). La llamada a COM requiere que el subproceso de llamada tenga un apartamento de subproceso único (STA) en lugar de un apartamento con varios subprocesos (MTA), que es el valor predeterminado en Microsoft .NET 2.0 y versiones posteriores. (Para obtener más información sobre los estados de subprocesos y apartamentos, consulte Subprocesos administrados y no administrados y ApartmentState). Hay dos maneras de hacerlo:

  • La manera más sencilla es agregar STAThreadAttribute (es decir, "[System.STAThreadAttribute()]") justo encima de la primera línea del método de Main la aplicación (normalmente "static void Main(string[] args)").

  • Si necesita que Main el estado del apartamento del subproceso sea MTA, puede hospedar la llamada a AddJob(String, String, Boolean) en un subproceso independiente cuyo estado de apartamento esté establecido STA en con SetApartmentState. En el ejemplo siguiente se muestra esta segunda técnica.

Nota:

No se puede aplicar a STAThreadAttribute ningún método excepto Main y no se puede usar SetApartmentState para el Main subproceso.

Otras formas de imprimir en Windows Presentation Foundation (WPF) incluyen el PrintDialog.PrintDocument método , que se puede usar con o sin abrir el cuadro de diálogo, y los muchos Write métodos y WriteAsync de XpsDocumentWriter.

Consulte también

Se aplica a

AddJob()

Inserta un nuevo (denominado de forma genérica) trabajo de impresión, cuyo contenido es una matriz Byte, en la cola.

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

Devoluciones

Objeto PrintSystemJobInfo que representa el trabajo de impresión y su estado.

Ejemplos

En el ejemplo siguiente se muestra cómo usar AddJob() para enviar una Byte matriz a una cola de impresión. Este código solo funciona con impresoras que pueden detectar e imprimir texto sin formato. Algunos de ellos no pueden.

// 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()

Comentarios

Use este método para escribir información específica del dispositivo, en un archivo de cola, que el administrador de colas de Microsoft Windows no incluye automáticamente. Por supuesto, debe saber si el archivo de cola es metarchivo mejorado (EMF) o especificación de papel XML (XPS). Si prefiere trabajar con la Stream API, puede usar la PrintQueueStream clase en lugar de este método.

Una vez que se haya llamado al AddJob método , debe escribir una Byte matriz en la JobStream propiedad del PrintSystemJobInfo que devuelve o no se AddJob crea ningún trabajo de impresión. Esta matriz es lo que imprime si la impresora está funcionando y no está en pausa.

Precaución

JobStream Si no se cierra con Close antes del final del subproceso en el que AddJob se llama, se produce una InvalidOperationException excepción cuando finaliza ese subproceso porque el subproceso de cola no puede obtener control sobre el Stream objeto.

En la interfaz gráfica de usuario (GUI) de la cola de impresión, el trabajo tiene el nombre "Imprimir documento del sistema". Para asignar un nombre diferente al trabajo, use la AddJob(String) sobrecarga.

Otras formas de imprimir en Windows Presentation Foundation (WPF) incluyen el PrintDialog.PrintDocument método , que se puede usar con o sin abrir el cuadro de diálogo, y los muchos Write métodos y WriteAsync de XpsDocumentWriter.

Se aplica a

AddJob(String)

Inserta un nuevo trabajo de impresión, cuyo contenido es una matriz Byte, en la cola.

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

Parámetros

jobName
String

Nombre del trabajo de impresión.

Devoluciones

Objeto PrintSystemJobInfo que representa el trabajo de impresión y su estado.

Ejemplos

En el ejemplo siguiente se muestra cómo usar AddJob(String) para leer un archivo en una Byte matriz y enviar la matriz a una cola de impresión. En este código se supone que hay un archivo denominado test.txt en la raíz de la unidad C: . Este código solo funciona con impresoras que pueden detectar e imprimir texto sin formato. Algunos de ellos no pueden.

// 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()

Comentarios

Use este método para escribir información específica del dispositivo, en un archivo de cola, que el administrador de colas de Microsoft Windows no incluye automáticamente. Por supuesto, debe saber si el archivo de cola es metarchivo mejorado (EMF) o especificación de papel XML (XPS). Si prefiere trabajar con la Stream API, puede usar la PrintQueueStream clase en lugar de este método.

Una vez que se haya llamado al AddJob método , debe escribir una Byte matriz en la JobStream propiedad del PrintSystemJobInfo que devuelve o no se AddJob crea ningún trabajo de impresión. Esta matriz es lo que imprime si la impresora está funcionando y no está en pausa.

Precaución

JobStream Si no se cierra con Close antes del final del subproceso en el que AddJob se llama, se produce una InvalidOperationException excepción cuando finaliza ese subproceso porque el subproceso de cola no puede obtener control sobre el Stream objeto.

Otras formas de imprimir en Windows Presentation Foundation (WPF) incluyen el PrintDialog.PrintDocument método , que se puede usar con o sin abrir el cuadro de diálogo, y los muchos Write métodos y WriteAsync de XpsDocumentWriter.

Se aplica a