Compartir a través de


Cómo: Validar y combinar elementos PrintTicket

El Esquema de impresión de Microsoft Windows incluye los elementos flexibles y extensibles PrintCapabilities y PrintTicket. El primero establece las funcionalidades de un dispositivo de impresión, mientras que el segundo especifica cómo debe usar el dispositivo esas funcionalidades con una determinada secuencia de documentos, con documentos individuales o con páginas individuales.

La siguiente sería una secuencia típica de tareas de una aplicación que admite la impresión.

  1. Determinar las funcionalidades de una impresora

  2. Configurar un elemento PrintTicket para usar esas funcionalidades

  3. Validar el elemento PrintTicket

En este artículo se explica cómo hacerlo.

Ejemplo

En el ejemplo sencillo siguiente solo nos interesa si una impresora puede admitir la impresión a doble cara. Estos son los pasos fundamentales.

  1. Obtenga un objeto PrintCapabilities con el método GetPrintCapabilities.

  2. Realice pruebas para confirmar la existencia de la funcionalidad que desea. En el siguiente ejemplo, probamos la propiedad DuplexingCapability del objeto PrintCapabilities para confirmar la existencia de la funcionalidad de impresión a doble cara de una hoja de papel con el "giro de página" por el lado largo de la hoja. Como DuplexingCapability es una colección, usamos el método Contains de ReadOnlyCollection<T>.

    Nota:

    Este paso no es estrictamente necesario. El método MergeAndValidatePrintTicket que se usa a continuación comprobará cada solicitud en el elemento PrintTicket en las funcionalidades de la impresora. Si la impresora no admite la funcionalidad solicitada, el controlador de impresora sustituirá una solicitud alternativa en el elemento PrintTicket devuelto por el método.

  3. Si la impresora admite impresión a doble cara, el código de ejemplo crea un elemento PrintTicket que solicita esa impresión a doble cara. Pero la aplicación no especifica todas las opciones de impresora posibles disponibles en el elemento PrintTicket. Eso sería un desperdicio tanto del programador como del tiempo del programa. En su lugar, el código establece solo la solicitud de impresión a doble cara y, a continuación, combina este elemento PrintTicket con un elemento PrintTicket existente, totalmente configurado y validado; en este caso, el elemento PrintTicket predeterminado del usuario.

  4. De igual modo, el código de ejemplo llama al método MergeAndValidatePrintTicket para combinar el nuevo elemento mínimo PrintTicket con el elemento PrintTicket predeterminado del usuario. Esto devuelve un elemento ValidationResult que incluye el nuevo elemento PrintTicket como una de sus propiedades.

  5. A continuación, el código de ejemplo comprueba que el nuevo elemento PrintTicket solicita la impresión a doble cara. Si la tiene, el código de ejemplo lo convierte en el nuevo vale de impresión predeterminado del usuario. Si el paso 2 anterior se hubiera dejado fuera y la impresora no admitiera la impresión a doble cara por el lado largo de la hoja, la prueba habría dado como resultado false (vea la nota anterior).

  6. El último paso significativo es confirmar el cambio en la propiedad UserPrintTicket de PrintQueue con el método Commit.

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

Para que pueda probar rápidamente este ejemplo, aquí incluimos la parte restante. Cree un proyecto y un espacio de nombres y, a continuación, pegue los dos fragmentos de código de este artículo en el bloque de espacio de nombres.

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

Vea también