PrintQueue.AddJob 方法

定义

在队列中插入一个新的打印作业。Inserts a new print job into the queue.

重载

AddJob(String, String, Boolean, PrintTicket)

XML 纸张规范 (XPS)XML Paper Specification (XPS) 文档的新打印作业插入队列中,为其提供指定名称和设置,并指定是否应验证它。Inserts a new print job for an XML 纸张规范 (XPS)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)

XML 纸张规范 (XPS)XML Paper Specification (XPS) 文档的新打印作业插入队列中,为其提供指定名称和设置。Inserts a new print job for an XML 纸张规范 (XPS)XML Paper Specification (XPS) Document into the queue, and gives it the specified name and settings.

AddJob(String, String, Boolean)

XML 纸张规范 (XPS)XML Paper Specification (XPS) 文档的一个新的打印作业插入队列中,赋予其指定名称,并指定是否应验证它。Inserts a new print job for an XML 纸张规范 (XPS)XML Paper Specification (XPS) Document into the queue, gives it the specified name, and specifies whether or not it should be validated.

AddJob()

将一个内容为 Byte 数组的新(一般命名的)打印作业插入到队列中。Inserts a new (generically named) print job, whose content is a Byte array, into the queue.

AddJob(String)

将一个内容为 Byte 数组的新打印作业插入到队列中。Inserts a new print job, whose content is a Byte array, into the queue.

注解

如果队列已暂停或处于错误状态,则作业将在到达队列顶部时打印,因此这是一个打印功能。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.

Windows Presentation Foundation (WPF)Windows Presentation Foundation (WPF) 中打印的其他方式包括 PrintDialog.PrintDocument 方法,该方法可用于或不打开对话框,以及 XpsDocumentWriter的许多 WriteWriteAsync 方法。Other ways to print in Windows Presentation Foundation (WPF)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)

XML 纸张规范 (XPS)XML Paper Specification (XPS) 文档的新打印作业插入队列中,为其提供指定名称和设置,并指定是否应验证它。Inserts a new print job for an XML 纸张规范 (XPS)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

参数

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,则进行快速后台处理,没有逐页的进度反馈,也不验证文件是否为有效 XPSXPS;否则为 falsetrue to spool quickly without page-by-page progress feedback and without validating that the file is valid XPSXPS; otherwise, false.

printTicket
PrintTicket

打印作业的设置。The settings of the print job.

返回

用于表示打印作业及其状态的 PrintSystemJobInfoA PrintSystemJobInfo that represents the print job and its status.

注解

有关详细信息,请参阅 AddJob(String, String, Boolean)For more information, see AddJob(String, String, Boolean).

AddJob(String, PrintTicket)

XML 纸张规范 (XPS)XML Paper Specification (XPS) 文档的新打印作业插入队列中,为其提供指定名称和设置。Inserts a new print job for an XML 纸张规范 (XPS)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

参数

jobName
String

正在打印文档的路径和名称。The path and name of the document that is being printed.

printTicket
PrintTicket

打印作业的设置。The settings of the print job.

返回

用于表示打印作业及其状态的 PrintSystemJobInfoA PrintSystemJobInfo that represents the print job and its status.

注解

有关详细信息,请参阅 AddJob(String)For more information, see AddJob(String).

AddJob(String, String, Boolean)

XML 纸张规范 (XPS)XML Paper Specification (XPS) 文档的一个新的打印作业插入队列中,赋予其指定名称,并指定是否应验证它。Inserts a new print job for an XML 纸张规范 (XPS)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

参数

jobName
String

打印作业的名称。The name of the print job.

documentPath
String

正在打印文档的路径和名称。The path and name of the document that is being printed.

fastCopy
Boolean

如果为 true,则进行快速后台处理,没有逐页的进度反馈,也不验证文件是否为有效 XPSXPS;否则为 falsetrue to spool quickly without page-by-page progress feedback and without validating that the file is valid XPSXPS; otherwise, false.

返回

用于表示打印作业及其状态的 PrintSystemJobInfoA PrintSystemJobInfo that represents the print job and its status.

示例

下面的示例演示如何使用 AddJob(String, String, Boolean) 对目录中的所有 XML 纸张规范 (XPS)XML Paper Specification (XPS) 文件进行批处理打印。The following example shows how to use AddJob(String, String, Boolean) to batch print all the XML 纸张规范 (XPS)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();
   
    }//end Main

}//end Program class

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");
                    }

                }// end for each XPS file
           
            }//end if there are no XPS files in the directory

        }//end if the directory does not exist

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

    }// end PrintXPS method

}// end BatchXPSPrinter class
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

注解

如果 true``fastCopy,则打印机必须是打印概述If fastCopy is true, then the printer must be an Printing Overview. 如果不是,则 AddJob(String, String, Boolean) 方法会引发异常。If it is not, the AddJob(String, String, Boolean) method throws an exception.

如果 false``fastCopy,则无需使用 XPSDrv 打印机。If fastCopy is false, then it is not necessary to use an XPSDrv printer. 要添加到队列中的 XPSXPS 文件转换为打印机的页面描述语言,如 PCL 或 Postscript。The XPSXPS file being added to the queue is converted to the printer's page description language, such as PCL or Postscript. 但是,这种打印会调用 组件对象模型 (COM)Component Object Model (COM)However, this kind of printing makes a call to 组件对象模型 (COM)Component Object Model (COM). 调用 COMCOM 要求调用线程具有单线程单元(STA)而不是多线程单元(MTA),这是 Microsoft .NETMicrosoft .NET 2.0 及更高版本中的默认值。The call to COMCOM requires that the calling thread have a single-threaded apartment (STA) instead of multiple-threaded apartment (MTA) which is the default in Microsoft .NETMicrosoft .NET 2.0 and later. (有关线程处理和单元状态的详细信息,请参阅托管和非托管线程处理ApartmentState。)可以通过两种方法执行此操作:(For more on threading and apartment states, see Managed and Unmanaged Threading, and ApartmentState.) There are two ways of doing this:

  • 最简单的方法是在应用程序 Main 方法(通常为 "static void Main(string[] args)")的第一行上方添加 STAThreadAttribute (即 "[System.STAThreadAttribute()]")。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)").

  • 如果需要 MTAMain 线程的单元状态,则可以在单独的线程中承载 AddJob(String, String, Boolean) 的调用,其单元状态设置为与 SetApartmentStateSTAIf 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.

备注

不能将 STAThreadAttribute 应用到除 Main 之外的任何方法,并且不能将 SetApartmentState 用于 Main 线程。You cannot apply the STAThreadAttribute to any method except Main and you cannot use SetApartmentState for the Main thread.

Windows Presentation Foundation (WPF)Windows Presentation Foundation (WPF) 中打印的其他方式包括 PrintDialog.PrintDocument 方法,该方法可用于或不打开对话框,以及 XpsDocumentWriter的许多 WriteWriteAsync 方法。Other ways to print in Windows Presentation Foundation (WPF)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()

将一个内容为 Byte 数组的新(一般命名的)打印作业插入到队列中。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

返回

用于表示打印作业及其状态的 PrintSystemJobInfoA PrintSystemJobInfo that represents the print job and its status.

示例

下面的示例演示如何使用 AddJob()Byte 数组发送到打印队列。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()

注解

使用此方法将设备特定的信息写入到假脱机文件,Microsoft WindowsMicrosoft Windows 后台处理程序不会自动包含这些信息。Use this method to write device specific information, to a spool file, that is not automatically included by the Microsoft WindowsMicrosoft Windows spooler. 当然,您需要知道假脱机文件是 增强型图元文件 (EMF)Enhanced Metafile (EMF) 还是 XML 纸张规范 (XPS)XML Paper Specification (XPS)Of course, you need to know whether the spool file is 增强型图元文件 (EMF)Enhanced Metafile (EMF) or XML 纸张规范 (XPS)XML Paper Specification (XPS). 如果希望使用 Stream API,则可以使用 PrintQueueStream 类,而不是使用此方法。If you prefer to work with the Stream API, you can use the PrintQueueStream class instead of this method.

调用 AddJob 方法后,必须将 Byte 数组写入 AddJob 返回的 PrintSystemJobInfoJobStream 属性,否则不会创建打印作业。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.

注意

如果 JobStream 未在调用了 AddJob 的线程结束之前 Close 关闭,则当该线程结束时,将引发 InvalidOperationException,因为后台处理程序线程无法获取对 Stream 对象的控制。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.

在打印队列的 图形用户界面 (GUI)graphical user interface (GUI)中,该作业的名称为 "打印系统文档"。In the print queue's 图形用户界面 (GUI)graphical user interface (GUI), the job has the name "Print System Document". 若要为作业指定不同的名称,请使用 AddJob(String) 重载。To give the job a different name, use the AddJob(String) overload.

Windows Presentation Foundation (WPF)Windows Presentation Foundation (WPF) 中打印的其他方式包括 PrintDialog.PrintDocument 方法,该方法可用于或不打开对话框,以及 XpsDocumentWriter的许多 WriteWriteAsync 方法。Other ways to print in Windows Presentation Foundation (WPF)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)

将一个内容为 Byte 数组的新打印作业插入到队列中。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

参数

jobName
String

打印作业的名称。The name of the print job.

返回

用于表示打印作业及其状态的 PrintSystemJobInfoA PrintSystemJobInfo that represents the print job and its status.

示例

下面的示例演示如何使用 AddJob(String) 将文件读入 Byte 数组,并将数组发送到打印队列。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. 此代码假定 C:驱动器的根目录中有一个名为 test.txt 的文件。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()

注解

使用此方法将设备特定的信息写入到假脱机文件,Microsoft WindowsMicrosoft Windows 后台处理程序不会自动包含这些信息。Use this method to write device specific information, to a spool file, that is not automatically included by the Microsoft WindowsMicrosoft Windows spooler. 当然,您需要知道假脱机文件是 增强型图元文件 (EMF)Enhanced Metafile (EMF) 还是 XML 纸张规范 (XPS)XML Paper Specification (XPS)Of course, you need to know whether the spool file is 增强型图元文件 (EMF)Enhanced Metafile (EMF) or XML 纸张规范 (XPS)XML Paper Specification (XPS). 如果希望使用 Stream API,则可以使用 PrintQueueStream 类,而不是使用此方法。If you prefer to work with the Stream API, you can use the PrintQueueStream class instead of this method.

调用 AddJob 方法后,必须将 Byte 数组写入 AddJob 返回的 PrintSystemJobInfoJobStream 属性,否则不会创建打印作业。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.

注意

如果 JobStream 未在调用了 AddJob 的线程结束之前 Close 关闭,则当该线程结束时,将引发 InvalidOperationException,因为后台处理程序线程无法获取对 Stream 对象的控制。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.

Windows Presentation Foundation (WPF)Windows Presentation Foundation (WPF) 中打印的其他方式包括 PrintDialog.PrintDocument 方法,该方法可用于或不打开对话框,以及 XpsDocumentWriter的许多 WriteWriteAsync 方法。Other ways to print in Windows Presentation Foundation (WPF)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.

适用于