Поделиться через


PrintQueue.AddJob Метод

Определение

Вставляет новое задание печати в очередь.

Перегрузки

Имя Описание
AddJob(String, String, Boolean, PrintTicket)

Вставляет новое задание печати для документа XML Paper (XPS) в очередь, дает ему указанное имя и параметры, а также указывает, следует ли проверять его.

AddJob(String, PrintTicket)

Вставляет новое задание печати для документа XML Paper (XPS) в очередь и предоставляет ему указанное имя и параметры.

AddJob(String, String, Boolean)

Вставляет новое задание печати для документа XML Paper (XPS) в очередь, дает ему указанное имя и указывает, следует ли проверять его.

AddJob()

Вставляет новое (универсально именованное) задание печати, содержимое которого является массивом Byte , в очередь.

AddJob(String)

Вставляет новое задание печати, содержимое которого является массивом Byte , в очередь.

Комментарии

Если очередь не приостановлена или находится в состоянии ошибки, задание печатается при достижении верхней части очереди, поэтому это функция печати.

Другие способы печати в Windows Presentation Foundation (WPF) включают PrintDialog.PrintDocument метод, который можно использовать с или без открытия диалогового окна, а также многие Write и WriteAsync методы.XpsDocumentWriter

AddJob(String, String, Boolean, PrintTicket)

Вставляет новое задание печати для документа XML Paper (XPS) в очередь, дает ему указанное имя и параметры, а также указывает, следует ли проверять его.

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

Параметры

jobName
String

Путь и имя документа, который печатается.

documentPath
String

Путь и имя документа, который печатается.

fastCopy
Boolean

true для быстрого восстановления без обратной связи о ходе выполнения страниц и без проверки допустимости файла XPS; falseв противном случае .

printTicket
PrintTicket

Параметры задания печати.

Возвращаемое значение

Объект, PrintSystemJobInfo представляющий задание печати и его состояние.

Комментарии

Дополнительные сведения см. в разделе AddJob(String, String, Boolean).

Применяется к

AddJob(String, PrintTicket)

Вставляет новое задание печати для документа XML Paper (XPS) в очередь и предоставляет ему указанное имя и параметры.

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

Параметры

jobName
String

Путь и имя документа, который печатается.

printTicket
PrintTicket

Параметры задания печати.

Возвращаемое значение

Объект, PrintSystemJobInfo представляющий задание печати и его состояние.

Комментарии

Дополнительные сведения см. в разделе AddJob(String).

Применяется к

AddJob(String, String, Boolean)

Вставляет новое задание печати для документа XML Paper (XPS) в очередь, дает ему указанное имя и указывает, следует ли проверять его.

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

Параметры

jobName
String

Имя задания печати.

documentPath
String

Путь и имя документа, который печатается.

fastCopy
Boolean

true для быстрого восстановления без обратной связи о ходе выполнения страниц и без проверки допустимости файла XPS; falseв противном случае .

Возвращаемое значение

Объект, PrintSystemJobInfo представляющий задание печати и его состояние.

Примеры

В следующем примере показано, AddJob(String, String, Boolean) как пакетно печатать все файлы спецификации XML (XPS) в каталоге.

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

Комментарии

Если fastCopy это trueтак, принтер должен быть обзором печати. Если это не так, AddJob(String, String, Boolean) метод создает исключение.

В противном fastCopyfalseслучае не требуется использовать принтер XPSDrv. Файл XPS, добавляемый в очередь, преобразуется в язык описания страниц принтера, например PCL или Postscript. Однако такой тип печати вызывает объектную модель компонента (COM). Вызов COM требует, чтобы вызывающий поток был однопотоковой квартирой (STA) вместо многопоточной квартиры (MTA), которая является значением по умолчанию. Это можно сделать двумя способами.

  • Самый простой способ заключается в добавлении STAThreadAttribute[System.STAThreadAttribute()]. е. "") над первой строкой метода приложения Main (обычно "static void Main(string[] args)").

  • Если вам нужно, чтобы MTAсостояние квартиры вашего Main потока было, вы можете разместить вызов AddJob(String, String, Boolean) в отдельном потоке, с которым установлено STASetApartmentStateсостояние квартиры. В приведенном ниже примере показан этот второй метод.

Замечание

Вы не можете применить к любому методу STAThreadAttribute , кроме Main того, что вы не можете использовать SetApartmentState для Main потока.

Другие способы печати в Windows Presentation Foundation (WPF) включают PrintDialog.PrintDocument метод, который можно использовать с или без открытия диалогового окна, а также многие Write и WriteAsync методы.XpsDocumentWriter

См. также раздел

Применяется к

AddJob()

Вставляет новое (универсально именованное) задание печати, содержимое которого является массивом Byte , в очередь.

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

Возвращаемое значение

Объект, PrintSystemJobInfo представляющий задание печати и его состояние.

Примеры

В следующем примере показано, как отправить AddJob()Byte массив в очередь печати. Этот код работает только с принтерами, которые могут обнаруживать и печатать обычный текст. Некоторые из них не могут.

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

Комментарии

Используйте этот метод для записи определенных сведений об устройстве в файл спула, который не включается автоматически в средство spooler Microsoft Windows. Конечно, необходимо знать, является ли spool-файл расширенным метафайлом (EMF) или спецификацией XML-бумаги (XPS). Если вы предпочитаете работать с Stream API, можно использовать PrintQueueStream класс вместо этого метода.

AddJob После вызова метода необходимо написать Byte массив JobStream в свойство PrintSystemJobInfo возвращаемого AddJob задания печати или без него. Этот массив печатается, если принтер работает и не приостановлен.

Предостережение

JobStream Если поток не закрыт Close до конца вызываемого AddJob потока, возникает, когда этот поток заканчивается, InvalidOperationException так как поток spooler не может контролировать Stream объект.

В графическом пользовательском интерфейсе очереди печати (GUI) задание имеет имя "Печать системного документа". Чтобы присвоить заданию другое имя, используйте перегрузку AddJob(String) .

Другие способы печати в Windows Presentation Foundation (WPF) включают PrintDialog.PrintDocument метод, который можно использовать с или без открытия диалогового окна, а также многие Write и WriteAsync методы.XpsDocumentWriter

Применяется к

AddJob(String)

Вставляет новое задание печати, содержимое которого является массивом Byte , в очередь.

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

Параметры

jobName
String

Имя задания печати.

Возвращаемое значение

Объект, PrintSystemJobInfo представляющий задание печати и его состояние.

Примеры

В следующем примере показано, как считывать AddJob(String) файл в Byte массив и отправлять массив в очередь печати. Этот код предполагает, что файл называется test.txt в корневом каталоге диска C: Этот код работает только с принтерами, которые могут обнаруживать и печатать обычный текст. Некоторые из них не могут.

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

Комментарии

Используйте этот метод для записи определенных сведений об устройстве в файл спула, который не включается автоматически в средство spooler Microsoft Windows. Конечно, необходимо знать, является ли spool-файл расширенным метафайлом (EMF) или спецификацией XML-бумаги (XPS). Если вы предпочитаете работать с Stream API, можно использовать PrintQueueStream класс вместо этого метода.

AddJob После вызова метода необходимо написать Byte массив JobStream в свойство PrintSystemJobInfo возвращаемого AddJob задания печати или без него. Этот массив печатается, если принтер работает и не приостановлен.

Предостережение

JobStream Если поток не закрыт Close до конца вызываемого AddJob потока, возникает, когда этот поток заканчивается, InvalidOperationException так как поток spooler не может контролировать Stream объект.

Другие способы печати в Windows Presentation Foundation (WPF) включают PrintDialog.PrintDocument метод, который можно использовать с или без открытия диалогового окна, а также многие Write и WriteAsync методы.XpsDocumentWriter

Применяется к