Visão Geral de Impressão
Com Microsoft .NET Framework, os desenvolvedores de aplicativos usando Windows Presentation Foundation (WPF) tem um rico conjunto de novo de gerenciamento de sistema de impressão e imprimir APIs. With Windows Vista, some of these print system enhancements are also available to developers creating Windows Forms applications and developers using unmanaged code. At the core of this new functionality is the new XML Paper Specification (XPS) file format and the XPS print path.
This topic contains the following sections.
About XPS
XPS Print Path
GDI Print Path
XPSDrv Driver Model
Related Topics
About XPS
XPS is an electronic document format, a spool file format and a page description language. É um formato de documento aberto que usa XML, Open Packaging Conventions (OPC)e outros padrões da indústria para criar documentos de várias plataformas. XPSsimplifica o processo pelo qual documentos digitais são criados, compartilhados, impressos, visualizados e arquivados. For additional information on XPS, see the XPS Web Site.
Várias técnicas para impressão XPS com o uso de conteúdo WPF , serão demonstrados em Como: Programmatically Print XPS Files. Talvez você ache útil para fazer referência a essas amostras durante a revisão do conteúdo contido neste tópico. (Os desenvolvedores de código não gerenciado devem ver a Ajuda para o escape de impressora do conversor de documentos do Microsoft XPS. Windows Formsos desenvolvedores devem usar o API na System.Drawing.Printing que não oferece suporte completo do namespace XPS impressão caminho, mas não oferecem suporte a um caminho de impressão híbrido GDI para XPS Consulte arquitetura de caminho de impressão abaixo.)
XPS Print Path
The XML Paper Specification (XPS) print path is a new Windows feature that redefines how printing is handled in Windows applications. Porque XPS pode substituir um idioma de apresentação do documento (como RTF), um formato de spooler de impressão (como WMF) e uma linguagem de descrição de página (como Postscript ou PCL); o novo caminho de impressão mantém o XPS formato de publicação de aplicativo para o final de processamento no driver de impressão ou dispositivo.
The XPS print path is built upon the XPS printer driver model (XPSDrv), which provides several benefits for developers such as "what you see is what you get" (WYSIWYG) printing, improved color support, and significantly improved print performance. (For more on XPSDrv, see the Windows Driver Development Kit.)
The operation of the print spooler for XPS documents is essentially the same as in previous versions of Windows. However, it has been enhanced to support the XPS print path in addition to the existing GDI print path. The new print path natively consumes an XPS spool file. While user-mode printer drivers written for previous versions of Windows will continue to work, an XPS printer driver (XPSDrv) is required in order to use the XPS print path.
The benefits of the XPS print path are significant, and include:
WYSIWYG print support
Native support of advanced color profiles, which include 32 bits per channel (bpc), CMYK, named-colors, n-inks, and native support of transparency and gradients.
Improved print performance for both .NET Framework and Win32 based applications.
Industry standard XPS format.
For basic print scenarios, a simple and intuitive API is available with a single entry point for user interface, configuration and job submission. Para cenários avançados, um suporte adicional é adicionado para user interface (UI) personalização (ou nenhum UI em todos os), impressão síncrona ou assíncrona e lote impressão recursos. Both options provide print support in full or partial trust mode.
XPS was designed with extensibility in mind. By using the extensibility framework, features and capabilities can be added to XPS in a modular manner. Extensibility features include:
Esquema de impressão. O esquema público é atualizado regularmente e habilita a extensão rápida dos recursos do dispositivo. (See PrintTicket and PrintCapabilities below.)
Extensible Filter Pipeline. The XPS printer driver (XPSDrv) filter pipeline was designed to enable both direct and scalable printing of XPS documents. (Lookup "XPSDrv" in the Windows Driver Development Kit.)
Print Path Architecture
While both Win32 and .NET Framework applications support XPS, Win32 and Windows Forms applications use a GDI to XPS conversion in order to create XPS formatted content for the XPS printer driver (XPSDrv). These applications are not required to use the XPS print path, and can continue to use Enhanced Metafile (EMF) based printing. No entanto, a maioria dos XPS recursos e aprimoramentos estão disponíveis somente para aplicativos que se destinam a XPS Imprimir o caminho.
Para ativar o uso de impressoras baseado em XPSDrv, por Win32 e Windows Forms aplicativos, o XPS (XPSDrv) do driver de impressora oferece suporte à conversão de GDI para formato deXPS . O modelo de XPSDrv também fornece um conversor para XPS para GDI formato para que Win32 aplicativos podem imprimir XPS documentos. Para WPF aplicativos, a conversão de XPS para GDI formato é feito automaticamente pela Write e WriteAsync métodos para a XpsDocumentWriter classe sempre que a fila de impressão de destino da operação de gravação não tem um driver de XPSDrv. (Windows Forms aplicativos não é possível imprimir XPS documentos.)
The following illustration depicts the print subsystem and defines the portions provided by Microsoft, and the portions defined by software and hardware vendors.
Basic XPS Printing
WPF defines both a basic and advanced API. For those applications that do not require extensive print customization or access to the complete XPS feature set, basic print support is available. Basic print support is exposed through a print dialog control that requires minimal configuration and features a familiar UI. Many XPS features are available using this simplified print model.
PrintDialog
The System.Windows.Controls.PrintDialog control provides a single entry point for UI, configuration, and XPS job submission. For information about how to instantiate and use the control, see Como: Chamar um diálogo de impressão.
Advanced XPS Printing
To access the complete set of XPS features, the advanced print API must be used. Several relevant API are described in greater detail below. Para obter uma lista completa de XPS Imprimir o caminho APIs, consulte a System.Windows.Xps e System.Printing referências de namespace.
PrintTicket and PrintCapabilities
O PrintTicket e PrintCapabilities classes são a base da avançada XPS recursos. Ambos os tipos de objetos são XML formatadas estruturas de recursos orientados a impressão, como o agrupamento, a impressão dos dois lados, grampeamento, etc. Essas estruturas são definidas pelo esquema de impressão. A PrintTicket instructs a printer how to process a print job. The PrintCapabilities class defines the capabilities of a printer. By querying the capabilities of a printer, a PrintTicket can be created that takes full advantage of a printer's supported features. Similarly, unsupported features can be avoided.
The following example demonstrates how to query the PrintCapabilities of a printer and create a PrintTicket using code.
' ---------------------- GetPrintTicketFromPrinter -----------------------
''' <summary>
''' Returns a PrintTicket based on the current default printer.</summary>
''' <returns>
''' A PrintTicket for the current local default printer.</returns>
Private Function GetPrintTicketFromPrinter() As PrintTicket
Dim printQueue As PrintQueue = Nothing
Dim localPrintServer As New LocalPrintServer()
' Retrieving collection of local printer on user machine
Dim localPrinterCollection As PrintQueueCollection = localPrintServer.GetPrintQueues()
Dim localPrinterEnumerator As System.Collections.IEnumerator = localPrinterCollection.GetEnumerator()
If localPrinterEnumerator.MoveNext() Then
' Get PrintQueue from first available printer
printQueue = CType(localPrinterEnumerator.Current, PrintQueue)
Else
' No printer exist, return null PrintTicket
Return Nothing
End If
' Get default PrintTicket from printer
Dim printTicket As PrintTicket = printQueue.DefaultPrintTicket
Dim printCapabilites As PrintCapabilities = printQueue.GetPrintCapabilities()
' Modify PrintTicket
If printCapabilites.CollationCapability.Contains(Collation.Collated) Then
printTicket.Collation = Collation.Collated
End If
If printCapabilites.DuplexingCapability.Contains(Duplexing.TwoSidedLongEdge) Then
printTicket.Duplexing = Duplexing.TwoSidedLongEdge
End If
If printCapabilites.StaplingCapability.Contains(Stapling.StapleDualLeft) Then
printTicket.Stapling = Stapling.StapleDualLeft
End If
Return printTicket
End Function ' end:GetPrintTicketFromPrinter()
// ---------------------- GetPrintTicketFromPrinter -----------------------
/// <summary>
/// Returns a PrintTicket based on the current default printer.</summary>
/// <returns>
/// A PrintTicket for the current local default printer.</returns>
private PrintTicket GetPrintTicketFromPrinter()
{
PrintQueue printQueue = null;
LocalPrintServer localPrintServer = new LocalPrintServer();
// Retrieving collection of local printer on user machine
PrintQueueCollection localPrinterCollection =
localPrintServer.GetPrintQueues();
System.Collections.IEnumerator localPrinterEnumerator =
localPrinterCollection.GetEnumerator();
if (localPrinterEnumerator.MoveNext())
{
// Get PrintQueue from first available printer
printQueue = (PrintQueue)localPrinterEnumerator.Current;
}
else
{
// No printer exist, return null PrintTicket
return null;
}
// Get default PrintTicket from printer
PrintTicket printTicket = printQueue.DefaultPrintTicket;
PrintCapabilities printCapabilites = printQueue.GetPrintCapabilities();
// Modify PrintTicket
if (printCapabilites.CollationCapability.Contains(Collation.Collated))
{
printTicket.Collation = Collation.Collated;
}
if ( printCapabilites.DuplexingCapability.Contains(
Duplexing.TwoSidedLongEdge) )
{
printTicket.Duplexing = Duplexing.TwoSidedLongEdge;
}
if (printCapabilites.StaplingCapability.Contains(Stapling.StapleDualLeft))
{
printTicket.Stapling = Stapling.StapleDualLeft;
}
return printTicket;
}// end:GetPrintTicketFromPrinter()
// ---------------------- GetPrintTicketFromPrinter -----------------------
/// <summary>
/// Returns a PrintTicket based on the current default printer.</summary>
/// <returns>
/// A PrintTicket for the current local default printer.</returns>
PrintTicket^ GetPrintTicketFromPrinter ()
{
PrintQueue^ printQueue = nullptr;
LocalPrintServer^ localPrintServer = gcnew LocalPrintServer();
// Retrieving collection of local printer on user machine
PrintQueueCollection^ localPrinterCollection = localPrintServer->GetPrintQueues();
System::Collections::IEnumerator^ localPrinterEnumerator = localPrinterCollection->GetEnumerator();
if (localPrinterEnumerator->MoveNext())
{
// Get PrintQueue from first available printer
printQueue = ((PrintQueue^)localPrinterEnumerator->Current);
} else
{
return nullptr;
}
// Get default PrintTicket from printer
PrintTicket^ printTicket = printQueue->DefaultPrintTicket;
PrintCapabilities^ printCapabilites = printQueue->GetPrintCapabilities();
// Modify PrintTicket
if (printCapabilites->CollationCapability->Contains(Collation::Collated))
{
printTicket->Collation = Collation::Collated;
}
if (printCapabilites->DuplexingCapability->Contains(Duplexing::TwoSidedLongEdge))
{
printTicket->Duplexing = Duplexing::TwoSidedLongEdge;
}
if (printCapabilites->StaplingCapability->Contains(Stapling::StapleDualLeft))
{
printTicket->Stapling = Stapling::StapleDualLeft;
}
return printTicket;
};// end:GetPrintTicketFromPrinter()
PrintServer and PrintQueue
The PrintServer class represents a network print server and the PrintQueue class represents a printer and the output job queue associated with it. Together, these APIs allow advanced management of a server's print jobs. A PrintServer, or one of its derived classes, is used to manage a PrintQueue. The AddJob method is used to insert a new print job into the queue.
The following example demonstrates how to create a LocalPrintServer and access its default PrintQueue by using code.
' -------------------- GetPrintXpsDocumentWriter() -------------------
''' <summary>
''' Returns an XpsDocumentWriter for the default print queue.</summary>
''' <returns>
''' An XpsDocumentWriter for the default print queue.</returns>
Private Function GetPrintXpsDocumentWriter() As XpsDocumentWriter
' Create a local print server
Dim ps As New LocalPrintServer()
' Get the default print queue
Dim pq As PrintQueue = ps.DefaultPrintQueue
' Get an XpsDocumentWriter for the default print queue
Dim xpsdw As XpsDocumentWriter = PrintQueue.CreateXpsDocumentWriter(pq)
Return xpsdw
End Function ' end:GetPrintXpsDocumentWriter()
// -------------------- GetPrintXpsDocumentWriter() -------------------
/// <summary>
/// Returns an XpsDocumentWriter for the default print queue.</summary>
/// <returns>
/// An XpsDocumentWriter for the default print queue.</returns>
private XpsDocumentWriter GetPrintXpsDocumentWriter()
{
// Create a local print server
LocalPrintServer ps = new LocalPrintServer();
// Get the default print queue
PrintQueue pq = ps.DefaultPrintQueue;
// Get an XpsDocumentWriter for the default print queue
XpsDocumentWriter xpsdw = PrintQueue.CreateXpsDocumentWriter(pq);
return xpsdw;
}// end:GetPrintXpsDocumentWriter()
XpsDocumentWriter
An XpsDocumentWriter, with its many the Write and WriteAsync methods, is used to write XPS documents to a PrintQueue. For example, the Write(FixedPage, PrintTicket) method is used to output an XPS document and PrintTicket synchronously. The WriteAsync(FixedDocument, PrintTicket) method is used to output an XPS document and PrintTicket asynchronously.
The following example demonstrates how to create an XpsDocumentWriter using code.
' -------------------- GetPrintXpsDocumentWriter() -------------------
''' <summary>
''' Returns an XpsDocumentWriter for the default print queue.</summary>
''' <returns>
''' An XpsDocumentWriter for the default print queue.</returns>
Private Function GetPrintXpsDocumentWriter() As XpsDocumentWriter
' Create a local print server
Dim ps As New LocalPrintServer()
' Get the default print queue
Dim pq As PrintQueue = ps.DefaultPrintQueue
' Get an XpsDocumentWriter for the default print queue
Dim xpsdw As XpsDocumentWriter = PrintQueue.CreateXpsDocumentWriter(pq)
Return xpsdw
End Function ' end:GetPrintXpsDocumentWriter()
// -------------------- GetPrintXpsDocumentWriter() -------------------
/// <summary>
/// Returns an XpsDocumentWriter for the default print queue.</summary>
/// <returns>
/// An XpsDocumentWriter for the default print queue.</returns>
private XpsDocumentWriter GetPrintXpsDocumentWriter()
{
// Create a local print server
LocalPrintServer ps = new LocalPrintServer();
// Get the default print queue
PrintQueue pq = ps.DefaultPrintQueue;
// Get an XpsDocumentWriter for the default print queue
XpsDocumentWriter xpsdw = PrintQueue.CreateXpsDocumentWriter(pq);
return xpsdw;
}// end:GetPrintXpsDocumentWriter()
The AddJob methods also provide ways to print. See Como: Programmatically Print XPS Files. Para obter detalhes.
GDI Print Path
Enquanto WPF aplicativos nativamente suporte a XPS Imprimir o caminho, Win32 e Windows Forms aplicativos também podem tirar proveito de alguns XPS recursos. The XPS printer driver (XPSDrv) can convert GDI based output to XPS format. Para cenários avançados, a conversão personalizada de conteúdo é suportado usando o escape de impressora do conversor de documentos do Microsoft XPS. Da mesma forma, WPF aplicativos também podem dar saída a GDI caminho de impressão, chamando um da Write ou WriteAsync métodos da XpsDocumentWriter classe e designando uma impressora não XpsDrv como o destino de impressão fila.
For applications that do not require XPS functionality or support, the current GDI print path remains unchanged.
- Para o material de referência adicional sobre o GDI Imprimir o caminho e as várias XPS Opções de conversão, consulte escape de impressora do conversor de documentos do Microsoft XPS e "xpsdrv" no Windows Driver Development Kit.
XPSDrv Driver Model
The XPS print path improves spooler efficiency by using XPS as the native print spool format when printing to an XPS -enabled printer or driver. The simplified spooling process eliminates the need to generate an intermediate spool file, such as an EMF data file, before the document is spooled. Through smaller spool file sizes, the XPS print path can reduce network traffic and improve print performance.
EMF is a closed format that represents application output as a series of calls into GDI for rendering services. Unlike EMF, the XPS spool format represents the actual document without requiring further interpretation when output to an XPS-based printer driver (XPSDrv). The drivers can operate directly on the data in the format. This capability eliminates the data and color space conversions required when you use EMF files and GDI-based print drivers.
Spool file sizes are usually reduced when you use XPS Documents that target an XPS printer driver (XPSDrv) compared with their EMF equivalents; however, there are exceptions:
A vector graphic that is very complex, multi-layered, or inefficiently written can be larger than a bitmapped version of the same graphic.
For screen display purposes, XPS files embed device fonts as well as computer-based fonts; whereas GDI spool files do not embed device fonts. But both kinds of fonts are subsetted (see below) and printer drivers can remove the device fonts before transmitting the file to the printer.
Spool size reduction is performed through several mechanisms:
Font subsetting. Only characters used within the actual document are stored in the XPS file.
Advanced Graphics Support. Native support for transparency and gradient primitives avoids rasterization of content in the XPS Document.
Identification of common resources. Resources that are used multiple times (such as an image that represents a corporate logo) are treated as shared resources and are loaded only once.
ZIP compression. All XPS documents use ZIP compression.
Consulte também
Referência
escape de impressora do conversor de documentos do Microsoft XPS
Conceitos
Serialização e Armazenamento de Documento