Partager via


Comment : valider et fusionner des PrintTicket

Le schéma d’impression Microsoft Windows inclut les éléments flexibles et PrintTicket extensiblesPrintCapabilities. L’ancien itemise les fonctionnalités d’un appareil d’impression et spécifie comment l’appareil doit utiliser ces fonctionnalités en ce qui concerne une séquence particulière de documents, de documents individuels ou de pages individuelles.

Une séquence classique de tâches pour une application qui prend en charge l’impression serait la suivante.

  1. Déterminez les fonctionnalités d’une imprimante.

  2. Configurez une PrintTicket option pour utiliser ces fonctionnalités.

  3. Validez le PrintTicket.

Cet article explique comment faire.

Exemple

Dans l’exemple simple ci-dessous, nous sommes intéressés uniquement par le fait qu’une imprimante puisse prendre en charge l’impression recto verso : impression à deux côtés. Les principales étapes sont les suivantes.

  1. Obtenir un PrintCapabilities objet avec la GetPrintCapabilities méthode.

  2. Testez la présence de la fonctionnalité souhaitée. Dans l’exemple ci-dessous, nous testons la DuplexingCapability propriété de l’objet PrintCapabilities pour la présence de la capacité d’impression sur les deux côtés d’une feuille de papier avec la « page tournant » le long du côté long de la feuille. Étant donné qu’il DuplexingCapability s’agit d’une collection, nous utilisons la Contains méthode de ReadOnlyCollection<T>.

    Remarque

    Cette étape n’est pas strictement nécessaire. La MergeAndValidatePrintTicket méthode utilisée ci-dessous case activée chaque requête par PrintTicket rapport aux fonctionnalités de l’imprimante. Si la fonctionnalité demandée n’est pas prise en charge par l’imprimante, le pilote d’imprimante remplace une autre demande dans la PrintTicket méthode retournée.

  3. Si l’imprimante prend en charge le duplexing, l’exemple de code crée un PrintTicket fichier qui demande le duplexage. Mais l’application ne spécifie pas chaque paramètre d’imprimante possible disponible dans l’élément PrintTicket . Ce serait gaspiller le programmeur et le temps du programme. Au lieu de cela, le code définit uniquement la requête duplexing, puis fusionne cela PrintTicket avec un élément existant, entièrement configuré et validé, PrintTicketdans ce cas, la valeur par défaut PrintTicketde l’utilisateur.

  4. En conséquence, l’exemple appelle la MergeAndValidatePrintTicket méthode pour fusionner le nouveau, minimal, PrintTicket avec la valeur par défaut PrintTicketde l’utilisateur. Cela retourne une ValidationResult valeur qui inclut la nouvelle PrintTicket en tant que l’une de ses propriétés.

  5. L’exemple teste ensuite que les nouvelles PrintTicket demandes recto verso sont effectuées. Si c’est le cas, l’exemple le rend le nouveau ticket d’impression par défaut pour l’utilisateur. Si l’étape 2 ci-dessus avait été laissée à l’écart et que l’imprimante ne prenait pas en charge le duplexing sur le long côté, le test aurait abouti.false (Voir la note ci-dessus.)

  6. La dernière étape significative consiste à valider la modification apportée à la UserPrintTicket propriété de la PrintQueueCommit méthode.

/// <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>
''' 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>
Private Shared Sub ChangePrintTicketSetting(ByVal queue As PrintQueue)
    '
    ' Obtain the printer's PrintCapabilities so we can determine whether or not
    ' duplexing printing is supported by the printer.
    '
    Dim printcap As PrintCapabilities = 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) Then
        '
        ' To change the user-default PrintTicket, we can first create a delta PrintTicket with
        ' the new duplexing setting.
        '
        Dim deltaTicket As 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.
        '
        Dim result As ValidationResult = 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 Then
            '
            ' 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)
        End If
    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)
    End If
End Sub

Pour que vous puissiez tester rapidement cet exemple, le reste de celui-ci est présenté ci-dessous. Créez un projet et un espace de noms, puis collez les extraits de code de cet article dans le bloc d’espace de noms.

/// <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
''' <summary>
''' Displays the correct command line syntax to run this sample program.
''' </summary>
Private Shared Sub 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()
End Sub


<STAThread>
Public Shared Sub Main(ByVal args() As String)
    Try
        If (args.Length = 1) AndAlso (args(0) = "-a") Then
            '
            ' Change PrintTicket setting for all local and network printer connections.
            '
            Dim server As New LocalPrintServer()

            Dim queue_types() As EnumeratedPrintQueueTypes = {EnumeratedPrintQueueTypes.Local, EnumeratedPrintQueueTypes.Connections}

            '
            ' Enumerate through all the printers.
            '
            For Each queue As PrintQueue In server.GetPrintQueues(queue_types)
                '
                ' Change the PrintTicket setting queue by queue.
                '
                ChangePrintTicketSetting(queue)
            Next queue 'end if -a

        ElseIf (args.Length = 2) AndAlso (args(0) = "-l") Then
            '
            ' Change PrintTicket setting only for the specified local printer.
            '
            Dim server As New LocalPrintServer()
            Dim queue As New PrintQueue(server, args(1))
            ChangePrintTicketSetting(queue) 'end if -l

        ElseIf (args.Length = 2) AndAlso (args(0) = "-r") Then
            '
            ' Change PrintTicket setting only for the specified remote printer.
            '
            Dim serverName As String = args(1).Remove(args(1).LastIndexOf("\"))
            Dim printerName As String = args(1).Remove(0, args(1).LastIndexOf("\")+1)
            Dim ps As New PrintServer(serverName)
            Dim queue As 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()
        End If
    Catch e As Exception
        Console.WriteLine(e.Message)
        Console.WriteLine(e.StackTrace)

        '
        ' Show inner exception information if it's provided.
        '
        If e.InnerException IsNot Nothing Then
            Console.WriteLine("--- Inner Exception ---")
            Console.WriteLine(e.InnerException.Message)
            Console.WriteLine(e.InnerException.StackTrace)
        End If
    Finally
        Console.WriteLine("Press Return to continue...")
        Console.ReadLine()
    End Try
End Sub

Voir aussi