如何:验证和合并 PrintTicket

更新:2007 年 11 月

Windows Vista 有一个新增功能:Print Schema(打印架构),它包括灵活且可扩展的 PrintCapabilitiesPrintTicket 元素。前者可以详细列举打印设备的功能,后者用于指定该设备应该如何使用这些功能来处理特定文档序列、单个文档或单个页面。

支持打印的应用程序的典型任务序列如下所示:

  1. 确定打印机的功能。

  2. 配置 PrintTicket 以使用这些功能。

  3. 验证 PrintTicket

本文演示如何进行以上操作。

示例

在下面的简单示例中,我们只关注打印机是否支持双面打印。主要步骤如下所示。

  1. 使用 GetPrintCapabilities 方法获取 PrintCapabilities 对象。

  2. 测试是否存在所需的功能。在下面的示例中,我们测试 PrintCapabilities 对象的 DuplexingCapability 属性,验证是否能够使用“页面翻转”沿页面长边在一页纸的双面进行打印。因为 DuplexingCapability 是一个集合,所以我们使用 ReadOnlyCollection<T>Contains 方法。

    说明:

    此步骤不是必需的。下面使用的 MergeAndValidatePrintTicket 方法将针对打印机的功能检测 PrintTicket 中的每个请求。如果打印机不支持请求的功能,则打印机驱动程序将替换为该方法返回的 PrintTicket 中的另一个请求。

  3. 如果打印机支持双面打印,则示例代码会创建请求双面打印的 PrintTicket。但是应用程序不会指定 PrintTicket 元素中提供的每个可能的打印机设置。这将浪费程序员时间和程序时间。代码仅设置双面打印请求,然后将此 PrintTicket 与现有的、完全配置且经过验证的 PrintTicket(在此例中,是用户的默认 PrintTicket)进行合并。

  4. 相应地,本示例调用 MergeAndValidatePrintTicket 方法将最小的新 PrintTicket 与用户的默认 PrintTicket 合并。这会返回 ValidationResult,它包含新 PrintTicket 作为其属性之一。

  5. 然后代码会测试新 PrintTicket 是否请求双面打印。如果它请求双面打印,那么代码会将其作为用户的新默认打印票证。如果没有执行上述步骤 2,并且打印机不支持沿长边进行双面打印,则测试将导致 false。(请参见上述“注意”部分。)

  6. 最后一个重要步骤是使用 Commit 方法提交对 PrintQueueUserPrintTicket 属性的更改。

/// <summary>
/// Changes the user-default PrintTicket setting of the specified print queue.
/// </summary>
/// <param name="queue">the printer whose user-default PrintTicket setting needs to be changed</param>
static private void ChangePrintTicketSetting(PrintQueue queue)
{
    //
    // Obtain the printer's PrintCapabilities so we can determine whether or not
    // duplexing printing is supported by the printer.
    //
    PrintCapabilities printcap = queue.GetPrintCapabilities();

    //
    // The printer's duplexing capability is returned as a read-only collection of duplexing options
    // that can be supported by the printer. If the collection returned contains the duplexing
    // option we want to set, it means the duplexing option we want to set is supported by the printer,
    // so we can make the user-default PrintTicket setting change.
    //
    if (printcap.DuplexingCapability.Contains(Duplexing.TwoSidedLongEdge))
    {
        //
        // To change the user-default PrintTicket, we can first create a delta PrintTicket with
        // the new duplexing setting.
        //
        PrintTicket deltaTicket = new PrintTicket();
        deltaTicket.Duplexing = Duplexing.TwoSidedLongEdge;

        //
        // Then merge the delta PrintTicket onto the printer's current user-default PrintTicket,
        // and validate the merged PrintTicket to get the new PrintTicket we want to set as the
        // printer's new user-default PrintTicket.
        //
        ValidationResult result = queue.MergeAndValidatePrintTicket(queue.UserPrintTicket, deltaTicket);

        //
        // The duplexing option we want to set could be constrained by other PrintTicket settings
        // or device settings. We can check the validated merged PrintTicket to see whether the
        // the validation process has kept the duplexing option we want to set unchanged.
        //
        if (result.ValidatedPrintTicket.Duplexing == Duplexing.TwoSidedLongEdge)
        {
            //
            // Set the printer's user-default PrintTicket and commit the set operation.
            //
            queue.UserPrintTicket = result.ValidatedPrintTicket;
            queue.Commit();
            Console.WriteLine("PrintTicket new duplexing setting is set on '{0}'.", queue.FullName);
        }
        else
        {
            //
            // The duplexing option we want to set has been changed by the validation process
            // when it was resolving setting constraints.
            //
            Console.WriteLine("PrintTicket new duplexing setting is constrained on '{0}'.", queue.FullName);
        }
    }
    else
    {
        //
        // If the printer doesn't support the duplexing option we want to set, skip it.
        //
        Console.WriteLine("PrintTicket new duplexing setting is not supported on '{0}'.", queue.FullName);
    }
}

在下面显示了代码的剩余部分,以便于您能快速测试本示例。创建项目和命名空间,然后将本文中的两个代码段粘贴到命名空间块中。

/// <summary>
/// Displays the correct command line syntax to run this sample program.
/// </summary>
static private void DisplayUsage()
{
    Console.WriteLine();
    Console.WriteLine("Usage #1: printticket.exe -l \"<printer_name>\"");
    Console.WriteLine("      Run program on the specified local printer");
    Console.WriteLine();
    Console.WriteLine("      Quotation marks may be omitted if there are no spaces in printer_name.");
    Console.WriteLine();
    Console.WriteLine("Usage #2: printticket.exe -r \"\\\\<server_name>\\<printer_name>\"");
    Console.WriteLine("      Run program on the specified network printer");
    Console.WriteLine();
    Console.WriteLine("      Quotation marks may be omitted if there are no spaces in server_name or printer_name.");
    Console.WriteLine();
    Console.WriteLine("Usage #3: printticket.exe -a");
    Console.WriteLine("      Run program on all installed printers");
    Console.WriteLine();
}


[STAThread]
static public void Main(string[] args)
{
    try
    {
        if ((args.Length == 1) && (args[0] == "-a"))
        {
            //
            // Change PrintTicket setting for all local and network printer connections.
            //
            LocalPrintServer server = new LocalPrintServer();

            EnumeratedPrintQueueTypes[] queue_types = {EnumeratedPrintQueueTypes.Local,
                                                       EnumeratedPrintQueueTypes.Connections};

            //
            // Enumerate through all the printers.
            //
            foreach (PrintQueue queue in server.GetPrintQueues(queue_types))
            {
                //
                // Change the PrintTicket setting queue by queue.
                //
                ChangePrintTicketSetting(queue);
            }
        }//end if -a

        else if ((args.Length == 2) && (args[0] == "-l"))
        {
            //
            // Change PrintTicket setting only for the specified local printer.
            //
            LocalPrintServer server = new LocalPrintServer();
            PrintQueue queue = new PrintQueue(server, args[1]);
            ChangePrintTicketSetting(queue);
        }//end if -l

        else if ((args.Length == 2) && (args[0] == "-r"))
        {
            //
            // Change PrintTicket setting only for the specified remote printer.
            //
            String serverName = args[1].Remove(args[1].LastIndexOf(@"\"));
            String printerName = args[1].Remove(0, args[1].LastIndexOf(@"\")+1);
            PrintServer ps = new PrintServer(serverName);
            PrintQueue queue = new PrintQueue(ps, printerName);
            ChangePrintTicketSetting(queue);
         }//end if -r

        else
        {
            //
            // Unrecognized command line.
            // Show user the correct command line syntax to run this sample program.
            //
            DisplayUsage();
        }
    }
    catch (Exception e)
    {
        Console.WriteLine(e.Message);
        Console.WriteLine(e.StackTrace);

        //
        // Show inner exception information if it's provided.
        //
        if (e.InnerException != null)
        {
            Console.WriteLine("--- Inner Exception ---");
            Console.WriteLine(e.InnerException.Message);
            Console.WriteLine(e.InnerException.StackTrace);
        }
    }
    finally
    {
        Console.WriteLine("Press Return to continue...");
        Console.ReadLine();
    }
}//end Main

请参见

概念

Windows Presentation Foundation 中的文档

打印概述

参考

PrintCapabilities

PrintTicket

GetPrintQueues

PrintServer

EnumeratedPrintQueueTypes

PrintQueue

GetPrintCapabilities

其他资源

打印示例