다음을 통해 공유


방법: PrintTicket 유효성 검사 및 병합

Microsoft Windows 인쇄 스키마에는 유연하고 확장 가능한 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과 병합합니다. 이로 인해 PrintTicket을 속성 중 하나로 포함하는 ValidationResult가 반환됩니다.

  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>
        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
/// <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>
        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 'end Main
/// <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

참고 항목

참조

PrintCapabilities

PrintTicket

GetPrintQueues

PrintServer

EnumeratedPrintQueueTypes

PrintQueue

GetPrintCapabilities

개념

WPF의 문서

인쇄 개요

기타 리소스

Print Schema