PrintQueue.AddJob Método

Definição

Insere um novo trabalho de impressão na fila.

Sobrecargas

AddJob(String, String, Boolean, PrintTicket)

Insere um novo trabalho de impressão para um documento XPS (Especificação de Papel XML) na fila, fornece o nome e as configurações especificados e especifica se ele deve ou não ser validado.

AddJob(String, PrintTicket)

Insere um novo trabalho de impressão para um documento XPS (Especificação de Papel XML) na fila e fornece o nome e as configurações especificados.

AddJob(String, String, Boolean)

Insere um novo trabalho de impressão para um documento XPS (Especificação de Papel XML) na fila, fornece o nome especificado e especifica se ele deve ou não ser validado.

AddJob()

Insere um novo trabalho de impressão (nomeado genericamente), cujo conteúdo é uma matriz Byte, na fila.

AddJob(String)

Insere um novo trabalho de impressão, cujo conteúdo é uma matriz Byte, na fila.

Comentários

A menos que a fila esteja pausada ou em um estado de erro, o trabalho é impresso quando atinge a parte superior da fila, portanto, essa é uma função de impressão.

Outras maneiras de imprimir em Windows Presentation Foundation (WPF) incluem o PrintDialog.PrintDocument método , que pode ser usado com ou sem abrir a caixa de diálogo e os muitos Write métodos e WriteAsync do XpsDocumentWriter.

AddJob(String, String, Boolean, PrintTicket)

Insere um novo trabalho de impressão para um documento XPS (Especificação de Papel XML) na fila, fornece o nome e as configurações especificados e especifica se ele deve ou não ser validado.

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

O caminho e o nome do documento que está sendo impresso.

documentPath
String

O caminho e o nome do documento que está sendo impresso.

fastCopy
Boolean

true para fazer spool rapidamente sem comentários de progresso de página por página e sem validar se o arquivo é um XPS válido; caso contrário, false.

printTicket
PrintTicket

As configurações do trabalho de impressão.

Retornos

Um PrintSystemJobInfo que representa o trabalho de impressão e seu status.

Comentários

Para obter mais informações, consulte AddJob(String, String, Boolean).

Aplica-se a

AddJob(String, PrintTicket)

Insere um novo trabalho de impressão para um documento XPS (Especificação de Papel XML) na fila e fornece o nome e as configurações 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

O caminho e o nome do documento que está sendo impresso.

printTicket
PrintTicket

As configurações do trabalho de impressão.

Retornos

Um PrintSystemJobInfo que representa o trabalho de impressão e seu status.

Comentários

Para obter mais informações, consulte AddJob(String).

Aplica-se a

AddJob(String, String, Boolean)

Insere um novo trabalho de impressão para um documento XPS (Especificação de Papel XML) na fila, fornece o nome especificado e especifica se ele deve ou não ser validado.

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

O nome do trabalho de impressão.

documentPath
String

O caminho e o nome do documento que está sendo impresso.

fastCopy
Boolean

true para fazer spool rapidamente sem comentários de progresso de página por página e sem validar se o arquivo é um XPS válido; caso contrário, false.

Retornos

Um PrintSystemJobInfo que representa o trabalho de impressão e seu status.

Exemplos

O exemplo a seguir mostra como usar AddJob(String, String, Boolean) para imprimir em lote todos os arquivos XPS (Especificação de Papel XML) em um diretório.

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

Comentários

Se fastCopy for true, a impressora deverá ser uma Visão Geral de Impressão. Se não estiver, o AddJob(String, String, Boolean) método gerará uma exceção.

Se fastCopy for false, não será necessário usar uma impressora XPSDrv. O arquivo XPS que está sendo adicionado à fila é convertido na linguagem de descrição da página da impressora, como PCL ou Postscript. No entanto, esse tipo de impressão faz uma chamada para COM (Component Object Model). A chamada para COM requer que o thread de chamada tenha um apartment de thread único (STA) em vez de apartment de vários threads (MTA), que é o padrão no Microsoft .NET 2.0 e posterior. (Para obter mais informações sobre os estados de threading e apartment, consulte Threading gerenciado e não gerenciado e ApartmentState.) Há duas maneiras de fazer isso:

  • A maneira mais simples é adicionar o STAThreadAttribute (ou seja, "[System.STAThreadAttribute()]") logo acima da primeira linha do método do Main aplicativo (geralmente "static void Main(string[] args)").

  • Se você precisar que o estado do apartamento do thread Main seja MTA, poderá hospedar a chamada para AddJob(String, String, Boolean) em um thread separado cujo estado de apartamento está definido STA como com SetApartmentState. O exemplo a seguir ilustra essa segunda técnica.

Observação

Você não pode aplicar o STAThreadAttribute a nenhum método, exceto Main e não pode usar SetApartmentState para o Main thread.

Outras maneiras de imprimir em Windows Presentation Foundation (WPF) incluem o PrintDialog.PrintDocument método , que pode ser usado com ou sem abrir a caixa de diálogo e os muitos Write métodos e WriteAsync do XpsDocumentWriter.

Confira também

Aplica-se a

AddJob()

Insere um novo trabalho de impressão (nomeado genericamente), cujo conteúdo é uma matriz Byte, na fila.

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

Retornos

Um PrintSystemJobInfo que representa o trabalho de impressão e seu status.

Exemplos

O exemplo a seguir mostra como usar AddJob() para enviar uma Byte matriz para uma fila de impressão. Esse código funciona apenas com impressoras que podem detectar e imprimir texto sem formatação. Alguns deles não podem.

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

Comentários

Use esse método para gravar informações específicas do dispositivo, em um arquivo de spool, que não são incluídas automaticamente pelo spooler do Microsoft Windows. É claro que você precisa saber se o arquivo de spool é EMF (Enhanced Metafile) ou XPS (XML Paper Specification). Se preferir trabalhar com a Stream API, você poderá usar a PrintQueueStream classe em vez desse método.

Depois que o AddJob método tiver sido chamado, você deverá gravar uma Byte matriz na JobStream propriedade do PrintSystemJobInfo que é retornado por AddJob ou nenhum trabalho de impressão será criado. Essa matriz é o que imprime se a impressora está funcionando e não está em pausa.

Cuidado

Se o JobStream não for fechado com Close antes do final do thread no qual AddJob é chamado, um InvalidOperationException será gerado quando esse thread terminar porque o thread do spooler não poderá obter controle sobre o Stream objeto .

Na GUI (interface gráfica do usuário) da fila de impressão, o trabalho tem o nome "Documento do Sistema de Impressão". Para dar ao trabalho um nome diferente, use a AddJob(String) sobrecarga.

Outras maneiras de imprimir em Windows Presentation Foundation (WPF) incluem o PrintDialog.PrintDocument método , que pode ser usado com ou sem abrir a caixa de diálogo e os muitos Write métodos e WriteAsync do XpsDocumentWriter.

Aplica-se a

AddJob(String)

Insere um novo trabalho de impressão, cujo conteúdo é uma matriz Byte, na fila.

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

O nome do trabalho de impressão.

Retornos

Um PrintSystemJobInfo que representa o trabalho de impressão e seu status.

Exemplos

O exemplo a seguir mostra como usar AddJob(String) para ler um arquivo em uma Byte matriz e enviar a matriz para uma fila de impressão. Esse código pressupõe que haja um arquivo chamado test.txt na raiz da unidade C:. Esse código funciona apenas com impressoras que podem detectar e imprimir texto sem formatação. Alguns deles não podem.

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

Comentários

Use esse método para gravar informações específicas do dispositivo, em um arquivo de spool, que não são incluídas automaticamente pelo spooler do Microsoft Windows. É claro que você precisa saber se o arquivo de spool é EMF (Enhanced Metafile) ou XPS (XML Paper Specification). Se preferir trabalhar com a Stream API, você poderá usar a PrintQueueStream classe em vez desse método.

Depois que o AddJob método tiver sido chamado, você deverá gravar uma Byte matriz na JobStream propriedade do PrintSystemJobInfo que é retornado por AddJob ou nenhum trabalho de impressão será criado. Essa matriz é o que imprime se a impressora está funcionando e não está em pausa.

Cuidado

Se o JobStream não for fechado com Close antes do final do thread no qual AddJob é chamado, um InvalidOperationException será gerado quando esse thread terminar porque o thread do spooler não poderá obter controle sobre o Stream objeto .

Outras maneiras de imprimir em Windows Presentation Foundation (WPF) incluem o PrintDialog.PrintDocument método , que pode ser usado com ou sem abrir a caixa de diálogo e os muitos Write métodos e WriteAsync do XpsDocumentWriter.

Aplica-se a