PrintQueue.AddJob Método
Definição
Importante
Algumas informações dizem respeito a um produto pré-lançado que pode ser substancialmente modificado antes de ser lançado. A Microsoft não faz garantias, de forma expressa ou implícita, em relação à informação aqui apresentada.
Insere um novo trabalho de impressão na fila.
Sobrecargas
| Name | Description |
|---|---|
| AddJob(String, String, Boolean, PrintTicket) |
Insere um novo trabalho de impressão para um Documento XML Paper Specification (XPS) na fila, atribui-lhe o nome e as definições especificados, e especifica se deve ou não ser validado. |
| AddJob(String, PrintTicket) |
Insere um novo trabalho de impressão para um Documento de Especificação XML em Papel (XPS) na fila e atribui-lhe o nome e as definições especificadas. |
| AddJob(String, String, Boolean) |
Insere um novo trabalho de impressão para um Documento de Especificação XML em Papel (XPS) na fila, atribui-lhe o nome especificado e especifica se deve ou não ser validado. |
| AddJob() |
Insere um novo trabalho de impressão (genericamente nomeado), cujo conteúdo é um Byte array, na fila. |
| AddJob(String) |
Insere um novo trabalho de impressão, cujo conteúdo é um Byte array, na fila. |
Observações
A menos que a fila esteja pausada ou em estado de erro, o trabalho imprime quando chega ao topo da fila, por isso isto é uma função de impressão.
Outras formas de imprimir em Windows Presentation Foundation (WPF) incluem o método PrintDialog.PrintDocument, que pode ser usado com ou sem abrir o diálogo, e os muitos métodos Write e WriteAsync do XpsDocumentWriter.
AddJob(String, String, Boolean, PrintTicket)
Insere um novo trabalho de impressão para um Documento XML Paper Specification (XPS) na fila, atribui-lhe o nome e as definições especificados, e especifica se 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á a ser impresso.
- documentPath
- String
O caminho e o nome do documento que está a ser impresso.
- fastCopy
- Boolean
true para fazer spool rapidamente sem feedback de progresso página a página e sem validar que o ficheiro é um XPS válido; caso contrário, false.
- printTicket
- PrintTicket
As definições do trabalho de impressão.
Devoluções
A PrintSystemJobInfo que representa o trabalho de impressão e o seu estado.
Observações
Para obter mais informações, veja AddJob(String, String, Boolean).
Aplica-se a
AddJob(String, PrintTicket)
Insere um novo trabalho de impressão para um Documento de Especificação XML em Papel (XPS) na fila e atribui-lhe o nome e as definições especificadas.
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á a ser impresso.
- printTicket
- PrintTicket
As definições do trabalho de impressão.
Devoluções
A PrintSystemJobInfo que representa o trabalho de impressão e o seu estado.
Observações
Para obter mais informações, veja AddJob(String).
Aplica-se a
AddJob(String, String, Boolean)
Insere um novo trabalho de impressão para um Documento de Especificação XML em Papel (XPS) na fila, atribui-lhe o nome especificado e especifica se 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á a ser impresso.
- fastCopy
- Boolean
true para fazer spool rapidamente sem feedback de progresso página a página e sem validar que o ficheiro é um XPS válido; caso contrário, false.
Devoluções
A PrintSystemJobInfo que representa o trabalho de impressão e o seu estado.
Exemplos
O exemplo seguinte mostra como imprimir AddJob(String, String, Boolean) em lote todos os ficheiros XML Paper Specification (XPS) num 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
Observações
Se fastCopy for true, então a impressora deve ser uma Visão Geral de Impressão. Se não for, o AddJob(String, String, Boolean) método lança uma exceção.
Se fastCopy for false, então não é necessário usar uma impressora XPSDrv. O ficheiro XPS adicionado à fila é convertido para a linguagem de descrição da página da impressora, como PCL ou Postscript. No entanto, este tipo de impressão faz uma chamada para o Modelo de Objeto Componente (COM). A chamada para COM exige que a thread que chama tenha um apartamento single-threaded (STA) em vez de um apartamento com múltiplas threads (MTA), que é o padrão. Existem duas formas de o fazer:
A forma mais simples é adicionar o STAThreadAttribute (isto é, "
[System.STAThreadAttribute()]") logo acima da primeira linha do método daMainaplicação (normalmente "static void Main(string[] args)").Se precisares que o estado do apartamento do teu
Maintópico seja MTA, podes alojar a chamada para AddJob(String, String, Boolean) num fio separado cujo estado do apartamento está definido para STA .SetApartmentState O exemplo abaixo ilustra esta segunda técnica.
Note
Não podes aplicar o STAThreadAttribute a nenhum método, exceto Main e não podes usar SetApartmentState para o Main tópico.
Outras formas de imprimir em Windows Presentation Foundation (WPF) incluem o método PrintDialog.PrintDocument, que pode ser usado com ou sem abrir o diálogo, e os muitos métodos Write e WriteAsync do XpsDocumentWriter.
Ver também
- ApartmentState
- STAThreadAttribute
- Expondo componentes COM ao .NET Framework
- ferramenta de conformidade isXPS
Aplica-se a
AddJob()
Insere um novo trabalho de impressão (genericamente nomeado), cujo conteúdo é um Byte array, na fila.
public:
System::Printing::PrintSystemJobInfo ^ AddJob();
public System.Printing.PrintSystemJobInfo AddJob();
member this.AddJob : unit -> System.Printing.PrintSystemJobInfo
Public Function AddJob () As PrintSystemJobInfo
Devoluções
A PrintSystemJobInfo que representa o trabalho de impressão e o seu estado.
Exemplos
O exemplo seguinte mostra como enviar AddJob() um Byte array para uma fila de impressão. Este código só funciona com impressoras que conseguem detetar e imprimir texto simples. Alguns não conseguem.
// 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()
Observações
Use este método para escrever informação específica do dispositivo, num ficheiro de spool, que não é automaticamente incluída pelo spooler de Microsoft Windows. Claro que precisa de saber se o ficheiro do spool é Enhanced Metafile (EMF) ou XML Paper Specification (XPS). Se preferires trabalhar com a Stream API, podes usar a PrintQueueStream classe em vez deste método.
Depois de o AddJob método ser chamado, deve escrever um Byte array na JobStream propriedade de PrintSystemJobInfo que é devolvido por AddJob ou não é criado nenhum trabalho de impressão. Este array é o que imprime se a impressora estiver a funcionar e não estiver pausada.
Atenção
Se a JobStream thread não for fechada com Close antes do fim da thread em que AddJob é chamada, então an InvalidOperationException é lançada quando essa thread termina porque a thread spooler não consegue controlar o Stream objeto.
Na interface gráfica (GUI) da fila de impressão, o trabalho tem o nome "Print System Document". Para dar um nome diferente ao trabalho, usa a AddJob(String) sobrecarga.
Outras formas de imprimir em Windows Presentation Foundation (WPF) incluem o método PrintDialog.PrintDocument, que pode ser usado com ou sem abrir o diálogo, e os muitos métodos Write e WriteAsync do XpsDocumentWriter.
Aplica-se a
AddJob(String)
Insere um novo trabalho de impressão, cujo conteúdo é um Byte array, 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.
Devoluções
A PrintSystemJobInfo que representa o trabalho de impressão e o seu estado.
Exemplos
O exemplo seguinte mostra como ler AddJob(String) um ficheiro num Byte array e enviar o array para uma fila de impressão. Este código assume que existe um ficheiro chamado test.txt na raiz da unidade C:. Este código só funciona com impressoras que conseguem detetar e imprimir texto simples. Alguns não conseguem.
// 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()
Observações
Use este método para escrever informação específica do dispositivo, num ficheiro de spool, que não é automaticamente incluída pelo spooler de Microsoft Windows. Claro que precisa de saber se o ficheiro do spool é Enhanced Metafile (EMF) ou XML Paper Specification (XPS). Se preferires trabalhar com a Stream API, podes usar a PrintQueueStream classe em vez deste método.
Depois de o AddJob método ser chamado, deve escrever um Byte array na JobStream propriedade de PrintSystemJobInfo que é devolvido por AddJob ou não é criado nenhum trabalho de impressão. Este array é o que imprime se a impressora estiver a funcionar e não estiver pausada.
Atenção
Se a JobStream thread não for fechada com Close antes do fim da thread em que AddJob é chamada, então an InvalidOperationException é lançada quando essa thread termina porque a thread spooler não consegue controlar o Stream objeto.
Outras formas de imprimir em Windows Presentation Foundation (WPF) incluem o método PrintDialog.PrintDocument, que pode ser usado com ou sem abrir o diálogo, e os muitos métodos Write e WriteAsync do XpsDocumentWriter.