### Complete Printing Workflow Example Source: https://github.com/arcticlampyrid/winprint.rs/blob/main/_autodocs/README.md Demonstrates a full printing workflow: finding a printer, querying its capabilities, building a print ticket with specific media size and orientation, and finally printing an XPS document. Ensure the 'report.xps' file exists and the printer 'HP LaserJet Pro' is installed. ```rust use winprint::printer::{PrinterDevice, FilePrinter, XpsPrinter}; use winprint::ticket::{PrintTicketBuilder, PrintCapabilities, PredefinedMediaName}; use std::path::Path; fn main() -> Result<(), Box> { // 1. Find printer let device = PrinterDevice::all()? .into_iter() .find(|d| d.name() == "HP LaserJet Pro") .ok_or("Printer not found")?; println!("Found printer: {}", device.name()); println!("Local: {}, Remote: {}", device.is_local(), device.is_remote()); // 2. Query capabilities let capabilities = PrintCapabilities::fetch(&device)?; println!("Supports {} media sizes", capabilities.page_media_sizes().count()); // 3. Build print ticket with A4 + Landscape let mut builder = PrintTicketBuilder::new(&device)?; let a4 = capabilities .page_media_sizes() .find(|m| m.as_predefined_name() == Some(PredefinedMediaName::ISOA4)) .ok_or("A4 not supported")?; builder.merge(a4)?; let landscape = capabilities .page_orientations() .find(|o| o.as_predefined_name() == Some(PredefinedPageOrientation::Landscape)) .ok_or("Landscape not supported")?; builder.merge(landscape)?; let ticket = builder.build()?; // 4. Print document let printer = XpsPrinter::new(device); printer.print(Path::new("report.xps"), ticket)?; println!("Print job submitted successfully"); Ok(()) } ``` -------------------------------- ### Enumerate and Find a Specific Printer Source: https://github.com/arcticlampyrid/winprint.rs/blob/main/_autodocs/api-reference-printer-device.md This example demonstrates how to find a specific printer by name from a list of all available devices. It uses `PrinterDevice::all` to get the list and `find` to locate the desired printer. Ensure the printer name matches exactly. ```rust use winprint::printer::PrinterDevice; fn find_printer(name: &str) -> Result> { let devices = PrinterDevice::all()?; devices .into_iter() .find(|d| d.name() == name) .ok_or_else(|| format!("Printer '{}' not found", name).into()) } let device = find_printer("HP LaserJet")?; assert!(device.is_local()); ``` -------------------------------- ### Common Printer Pattern: Printing an XPS Document Source: https://github.com/arcticlampyrid/winprint.rs/blob/main/_autodocs/api-reference-printers.md Demonstrates the common pattern for printing documents across different printer types in Winprint. This example shows how to get a printer device, create an XpsPrinter instance, set up a print ticket, and initiate the print job. ```rust use winprint::printer::{FilePrinter, PrinterDevice, XpsPrinter}; use winprint::ticket::PrintTicket; use std::path::Path; fn print_xps_document(file_path: &str, printer_name: &str) -> Result<(), Box> { // 1. Get printer device let device = PrinterDevice::all()? .into_iter() .find(|d| d.name() == printer_name) .ok_or("Printer not found")?; // 2. Create printer instance let printer = XpsPrinter::new(device); // 3. Create or customize print ticket let ticket = PrintTicket::default(); // 4. Print printer.print(Path::new(file_path), ticket)?; Ok(()) } ``` -------------------------------- ### FilePrinter Options Type Example (XpsPrinter) Source: https://github.com/arcticlampyrid/winprint.rs/blob/main/_autodocs/api-reference-file-printer.md Illustrates the Options type for XpsPrinter, which is PrintTicket. ```rust // For XpsPrinter type Options = PrintTicket; ``` -------------------------------- ### FilePrinter::print Method Example Source: https://github.com/arcticlampyrid/winprint.rs/blob/main/_autodocs/api-reference-file-printer.md Demonstrates how to use the print method of a FilePrinter implementation (XpsPrinter) to send a file to a printer with default options. ```rust use winprint::printer::{PrinterDevice, FilePrinter, XpsPrinter}; use std::path::Path; let device = PrinterDevice::all() .unwrap() .into_iter() .find(|d| d.name() == "My Printer") .unwrap(); let printer = XpsPrinter::new(device); let path = Path::new("document.xps"); // Print with default options match printer.print(path, Default::default()) { Ok(()) => println!("Document sent to printer"), Err(e) => eprintln!("Print error: {}", e), } ``` -------------------------------- ### Print Schema Structure Example Source: https://github.com/arcticlampyrid/winprint.rs/blob/main/_autodocs/api-reference-feature-options.md An XML example illustrating the structure of a Print Schema feature option pack, specifically for PageMediaSize with ISOA4 dimensions. ```xml 210000 297000 ``` -------------------------------- ### Install Dependencies on Arch Linux Source: https://github.com/arcticlampyrid/winprint.rs/blob/main/utils/gen-visual-regression-data/README.md Installs the necessary command-line tools for generating visual regression data on Arch Linux. This includes Python, reportlab, poppler, libtiff, and ghostscript. ```bash sudo pacman -S python python-reportlab poppler libtiff ghostscript ``` -------------------------------- ### Configure Media Size to A4 Source: https://github.com/arcticlampyrid/winprint.rs/blob/main/_autodocs/configuration.md This example shows how to fetch printer capabilities and configure the print ticket to use the A4 media size. Ensure A4 is supported by the printer. ```rust use winprint::ticket::{PrintCapabilities, PrintTicketBuilder, PredefinedMediaName}; let capabilities = PrintCapabilities::fetch(&device)?; let mut builder = PrintTicketBuilder::new(&device)?; // Find and use A4 let a4 = capabilities .page_media_sizes() .find(|m| m.as_predefined_name() == Some(PredefinedMediaName::ISOA4)) .ok_or("A4 not supported")?; builder.merge(a4)?; ``` -------------------------------- ### WinPdfPrinter Creation Example Source: https://github.com/arcticlampyrid/winprint.rs/blob/main/_autodocs/api-reference-printers.md Instantiate WinPdfPrinter by providing a `PrinterDevice`. This printer is specifically designed for PDF documents and utilizes the Windows Runtime (WinRT) PDF API for rendering and printing. ```rust use winprint::printer::{PrinterDevice, WinPdfPrinter}; let device = PrinterDevice::all() .unwrap() .into_iter() .find(|d| d.name() == "My Printer") .unwrap(); let pdf_printer = WinPdfPrinter::new(device); ``` -------------------------------- ### Explore Printer Capabilities (Media Sizes, Orientations, Colors, Copies) Source: https://github.com/arcticlampyrid/winprint.rs/blob/main/_autodocs/api-reference-print-capabilities.md A comprehensive example demonstrating how to fetch printer capabilities and explore various settings like supported media sizes, orientations, output colors, and maximum copies. This function requires a printer name and iterates through different capability types, printing relevant information. ```rust use winprint::printer::PrinterDevice; use winprint::ticket::PrintCapabilities; fn explore_printer(printer_name: &str) -> Result<(), Box> { let device = PrinterDevice::all()? .into_iter() .find(|d| d.name() == printer_name) .ok_or("Printer not found")?; let capabilities = PrintCapabilities::fetch(&device)?; // Media sizes println!("Supported media sizes:"); for media in capabilities.page_media_sizes() { if let Some(name) = media.as_predefined_name() { println!(" - {:?}", name); } } // Orientations println!("Supported orientations:"); for orientation in capabilities.page_orientations() { if let Some(name) = orientation.as_predefined_name() { println!(" - {:?}", name); } } // Output colors println!("Supported colors:"); for color in capabilities.page_output_colors() { println!(" - {:?}", color.display_name()); } // Max copies if let Some(max_copies) = capabilities.max_copies() { println!("Max copies: {}", max_copies.value()); } Ok(()) } ``` -------------------------------- ### Example Test Usage with Null Device Source: https://github.com/arcticlampyrid/winprint.rs/blob/main/_autodocs/configuration.md Demonstrates how to use the null device from the test-utils feature to create a virtual printer for testing XPS printing. The null device is automatically cleaned up. ```rust use winprint::test_utils::null_device; use std::path::Path; #[test] fn test_print_xps() { let device = null_device::thread_local(); let printer = XpsPrinter::new(device); printer.print(Path::new("test.xps"), Default::default()).unwrap(); } ``` -------------------------------- ### Create a default PrintTicket Source: https://github.com/arcticlampyrid/winprint.rs/blob/main/_autodocs/api-reference-print-ticket.md Use the `default` method to create a `PrintTicket` with minimal configuration. This is useful for starting with a basic ticket structure. ```rust use winprint::ticket::PrintTicket; let ticket = PrintTicket::default(); ``` -------------------------------- ### Catching DxgiPrintContextError Source: https://github.com/arcticlampyrid/winprint.rs/blob/main/_autodocs/errors.md Illustrates how to catch errors during the creation of a DXGI print context. This example specifically handles the `InitializeDirectX` error. ```rust use winprint::printer::DxgiPrintContext; match DxgiPrintContext::new(&device, &ticket, job_name) { Ok(ctx) => { /* use context */ } Err(DxgiPrintContextError::InitializeDirectX(e)) => { eprintln!("Cannot initialize Direct3D: {}", e); } Err(e) => eprintln!("DXGI error: {}", e), } ``` -------------------------------- ### Get OS Server Name Source: https://github.com/arcticlampyrid/winprint.rs/blob/main/_autodocs/api-reference-printer-device.md Retrieves the server name associated with the printer. For local printers, this will be an empty string. The example demonstrates checking if a printer is local based on this value. ```rust let device = PrinterDevice::all().unwrap().into_iter().next().unwrap(); if device.os_server().is_empty() { println!("Local printer"); } else { println!("Server: {:?}", device.os_server()); } ``` -------------------------------- ### Run Windows VM Tests on Linux Source: https://github.com/arcticlampyrid/winprint.rs/blob/main/README.md This command executes the test suite within a Windows 11 VM on a Linux host. Ensure Docker with BuildKit and KVM support are installed. The first run initializes the VM, subsequent runs are faster. ```bash ./utils/test-in-windows-vm/run.sh ``` -------------------------------- ### Print Ticket XML with Multiple Settings Source: https://github.com/arcticlampyrid/winprint.rs/blob/main/_autodocs/configuration.md An example demonstrating how to construct a print ticket XML with multiple settings, including media size (A4), orientation (Landscape), color (Monochrome), and duplex (Long Edge). ```xml 210000 297000 ``` -------------------------------- ### Catching WinPdfPrinterError Source: https://github.com/arcticlampyrid/winprint.rs/blob/main/_autodocs/errors.md Demonstrates how to handle specific errors when printing a PDF using WinPdfPrinter. This example shows how to match against the `FailedToOpenDocument` variant. ```rust use winprint::printer::{WinPdfPrinter, FilePrinter, WinPdfPrinterError}; let printer = WinPdfPrinter::new(device); match printer.print(Path::new("doc.pdf"), Default::default()) { Ok(()) => println!("PDF printed"), Err(WinPdfPrinterError::FailedToOpenDocument(e)) => { eprintln!("Cannot open PDF: {}", e); } Err(e) => eprintln!("PDF print error: {}", e), } ``` -------------------------------- ### Configure Page Orientation to Landscape Source: https://github.com/arcticlampyrid/winprint.rs/blob/main/_autodocs/configuration.md This example configures the print ticket to use landscape orientation. It first fetches the printer's capabilities and then finds the landscape option. ```rust use winprint::ticket::{PrintCapabilities, PrintTicketBuilder, PredefinedPageOrientation}; let capabilities = PrintCapabilities::fetch(&device)?; let mut builder = PrintTicketBuilder::new(&device)?; let landscape = capabilities .page_orientations() .find(|o| o.as_predefined_name() == Some(PredefinedPageOrientation::Landscape)) .ok_or("Landscape not supported")?; builder.merge(landscape)?; ``` -------------------------------- ### PrintTicket::default Source: https://github.com/arcticlampyrid/winprint.rs/blob/main/_autodocs/api-reference-print-ticket.md Creates a default PrintTicket with minimal configuration. This is useful for starting with a standard set of printer settings. ```APIDOC ## PrintTicket::default ### Description Creates a default print ticket with minimal configuration. ### Signature ```rust impl Default for PrintTicket { fn default() -> Self } ``` ### Parameters None ### Return Type `PrintTicket` — A ticket with the default Print Schema XML structure ### Example ```rust use winprint::ticket::PrintTicket; let ticket = PrintTicket::default(); ``` ``` -------------------------------- ### Automated XPS Printing Test Source: https://github.com/arcticlampyrid/winprint.rs/blob/main/_autodocs/README.md Shows how to use the `test-utils` feature to perform automated testing of XPS printing. This example utilizes a null device, which discards print output, ensuring tests are fast and deterministic. ```rust #[cfg(test)] mod tests { use winprint::printer::{FilePrinter, XpsPrinter}; use winprint::test_utils::null_device; use std::path::Path; #[test] fn test_xps_printing() { let device = null_device::thread_local(); let printer = XpsPrinter::new(device); printer.print(Path::new("test.xps"), Default::default()).unwrap(); } } ``` -------------------------------- ### Get Supported Page Resolutions Source: https://github.com/arcticlampyrid/winprint.rs/blob/main/_autodocs/api-reference-print-capabilities.md Fetches print capabilities and iterates through all supported page resolutions, printing their display names. Ensure PrintCapabilities::fetch is called with a valid device. ```rust let capabilities = PrintCapabilities::fetch(&device)?; for resolution in capabilities.page_resolutions() { println!("Resolution: {:?}", resolution.display_name()); } ``` -------------------------------- ### WinPdfPrinter File Printing Example Source: https://github.com/arcticlampyrid/winprint.rs/blob/main/_autodocs/api-reference-printers.md Print PDF documents using WinPdfPrinter. This method takes a file path and print ticket options, leveraging the WinRT PDF API for compatibility with modern Windows versions. Requires a `device` object. ```rust use winprint::printer::{WinPdfPrinter, FilePrinter}; use std::path::Path; let printer = WinPdfPrinter::new(device); printer.print(Path::new("document.pdf"), Default::default())?; ``` -------------------------------- ### Catching FetchPrintCapabilitiesError Source: https://github.com/arcticlampyrid/winprint.rs/blob/main/_autodocs/errors.md Demonstrates how to handle specific variants of FetchPrintCapabilitiesError using a match statement. This example shows how to differentiate between parsing errors and general capability fetching errors. ```rust use winprint::ticket::{PrintCapabilities, FetchPrintCapabilitiesError}; match PrintCapabilities::fetch(&device) { Ok(caps) => { /* use capabilities */ } Err(FetchPrintCapabilitiesError::ParseError(e)) => { eprintln!("Capabilities XML is invalid: {}", e); } Err(FetchPrintCapabilitiesError::CannotGetPrintCapabilities(msg, _)) => { eprintln!("Device error: {}", msg); } Err(e) => eprintln!("Cannot fetch capabilities: {}", e), } ``` -------------------------------- ### Basic Print Ticket XML Structure Source: https://github.com/arcticlampyrid/winprint.rs/blob/main/_autodocs/configuration.md An example of the fundamental XML structure for a print ticket, including namespace declarations required by the Print Schema Framework. ```xml ``` -------------------------------- ### ImagePrinter File Printing Example Source: https://github.com/arcticlampyrid/winprint.rs/blob/main/_autodocs/api-reference-printers.md Use ImagePrinter to print image files like TIFFs. It decodes images using WIC and renders them with Direct2D. Multi-frame images are printed as separate pages. Requires a `device` object and uses default print ticket options. ```rust use winprint::printer::{ImagePrinter, FilePrinter}; use std::path::Path; let printer = ImagePrinter::new(device); printer.print(Path::new("image.tiff"), Default::default())?; ``` -------------------------------- ### Filter Page Media Sizes by Name Prefix Source: https://github.com/arcticlampyrid/winprint.rs/blob/main/_autodocs/api-reference-feature-options.md Demonstrates filtering the list of page media sizes to find those whose predefined names start with "ISOA". The results are collected into a Vec. ```rust let iso_sizes: Vec<_> = PageMediaSize::list(&capabilities) .filter(|m| { if let Some(name) = m.as_predefined_name() { name.to_string().starts_with("ISOA") } else { false } }) .collect(); ``` -------------------------------- ### Get Default Parameters for Specific Filters Source: https://github.com/arcticlampyrid/winprint.rs/blob/main/_autodocs/api-reference-print-capabilities.md Retrieves default parameter initializations that match the provided filters. Use this when you need to set specific parameters based on predefined criteria. ```rust use xml::name::OwnedName; let capabilities = PrintCapabilities::fetch(&device)?; let ns = "http://schemas.microsoft.com/windows/2003/08/printing/printschemakeywords"; let filters = vec![ OwnedName::qualified("PageMediaSize", ns, Some("psk")), ]; for param in capabilities.default_parameters_for(&filters) { println!("Param: {:?}", param); } ``` -------------------------------- ### Get All Supported Page Media Sizes Source: https://github.com/arcticlampyrid/winprint.rs/blob/main/_autodocs/api-reference-print-capabilities.md Retrieves an iterator over all supported page media sizes. This is useful for displaying available paper sizes to the user or for finding a specific size like A4. ```rust use winprint::ticket::PredefinedMediaName; let capabilities = PrintCapabilities::fetch(&device)?; for media in capabilities.page_media_sizes() { let name = media.as_predefined_name(); let size = media.size(); println!("Media: {:?} - {}×{} µm", name, size.width_in_micron(), size.height_in_micron()); } // Find A4 let a4 = capabilities .page_media_sizes() .find(|m| m.as_predefined_name() == Some(PredefinedMediaName::ISOA4)); ``` -------------------------------- ### Get Available Options for a Print Feature Source: https://github.com/arcticlampyrid/winprint.rs/blob/main/_autodocs/api-reference-print-capabilities.md Retrieves all available options for a given print feature, identified by its name and namespace. Use this to discover supported settings for features like page media size. ```rust let capabilities = PrintCapabilities::fetch(&device)?; let psk_ns = "http://schemas.microsoft.com/windows/2003/08/printing/printschemakeywords"; let media_feature = OwnedName::qualified("PageMediaSize", psk_ns, Some("psk")); for option in capabilities.options_for_feature(media_feature) { println!("Option: {:?}", option.name); } ``` -------------------------------- ### Get Printer Name Source: https://github.com/arcticlampyrid/winprint.rs/blob/main/_autodocs/api-reference-printer-device.md Retrieves the human-readable name of the printer. This is useful for displaying printer information to the user. The example shows how to find a specific printer by its name. ```rust let device = PrinterDevice::all() .unwrap() .into_iter() .find(|x| x.name() == "My Printer") .expect("Printer not found"); ``` -------------------------------- ### Get OS Printer Name Source: https://github.com/arcticlampyrid/winprint.rs/blob/main/_autodocs/api-reference-printer-device.md Retrieves the printer name as it is known to the operating system, suitable for Windows API calls. The example simply prints this OS-specific name. ```rust let device = PrinterDevice::all().unwrap().into_iter().next().unwrap(); println!("OS name: {:?}", device.os_name()); ``` -------------------------------- ### Typical Configuration Workflow for Printing Source: https://github.com/arcticlampyrid/winprint.rs/blob/main/_autodocs/configuration.md Illustrates a common workflow for printing a file with specific settings. This involves selecting a printer, checking its capabilities, building a custom print ticket, and then printing. ```rust use winprint::printer::{PrinterDevice, FilePrinter, XpsPrinter}; use winprint::ticket::{PrintCapabilities, PrintTicketBuilder, PredefinedMediaName}; use std::path::Path; fn print_with_settings(file_path: &str) -> Result<(), Box> { // 1. Select device let device = PrinterDevice::all()? .into_iter() .find(|d| d.name() == "My Printer") .ok_or("Printer not found")?; // 2. Check capabilities let capabilities = PrintCapabilities::fetch(&device)?; // 3. Build ticket with selected features let mut builder = PrintTicketBuilder::new(&device)?; // Add A4 size let a4 = capabilities .page_media_sizes() .find(|m| m.as_predefined_name() == Some(PredefinedMediaName::ISOA4)) .ok_or("A4 not supported")?; builder.merge(a4)?; // Add landscape orientation let landscape = capabilities .page_orientations() .find(|o| o.as_predefined_name() == Some(PredefinedPageOrientation::Landscape)) .ok_or("Landscape not supported")?; builder.merge(landscape)?; // Build final ticket let ticket = builder.build()?; // 4. Print let printer = XpsPrinter::new(device); printer.print(Path::new(file_path), ticket)?; Ok(()) } ``` -------------------------------- ### Get OS Attributes Bitmask Source: https://github.com/arcticlampyrid/winprint.rs/blob/main/_autodocs/api-reference-printer-device.md Retrieves the Windows printer attributes as a bitmask. This can be used to check specific flags related to the printer's capabilities or status. The example prints the bitmask in hexadecimal format. ```rust let device = PrinterDevice::all().unwrap().into_iter().next().unwrap(); let attrs = device.os_attributes(); println!("Attributes bitmask: 0x{:08x}", attrs); ``` -------------------------------- ### Build Custom Print Ticket with Multiple Options Source: https://github.com/arcticlampyrid/winprint.rs/blob/main/_autodocs/api-reference-feature-options.md Demonstrates a workflow for building a custom print ticket by fetching capabilities, creating a builder, finding specific options (media size, orientation, color), and merging them into the builder before building the final ticket. ```rust use winprint::ticket::{ PrintCapabilities, PrintTicketBuilder, FeatureOptionPack, PredefinedMediaName, PredefinedPageOrientation }; let capabilities = PrintCapabilities::fetch(&device)?; let mut builder = PrintTicketBuilder::new(&device)?; // Collect desired options let a4 = PageMediaSize::list(&capabilities) .find(|m| m.as_predefined_name() == Some(PredefinedMediaName::ISOA4))?; let landscape = PageOrientation::list(&capabilities) .find(|o| o.as_predefined_name() == Some(PredefinedPageOrientation::Landscape))?; let bw = PageOutputColor::list(&capabilities) .find(|c| c.as_predefined_name() == Some(PredefinedPageOutputColor::Monochrome))?; // Merge all at once or sequentially builder.merge(a4)?; builder.merge(landscape)?; builder.merge(bw)?; let ticket = builder.build()?; ``` -------------------------------- ### Get capabilities Source: https://github.com/arcticlampyrid/winprint.rs/blob/main/_autodocs/INDEX.md Fetches the printing capabilities of the selected printer. ```APIDOC ## PrintCapabilities fetch() ### Description Fetches the printing capabilities of the selected printer. ### Method `PrintCapabilities.fetch()` ### Parameters None ### Response - A `PrintCapabilities` object containing printer capabilities. ``` -------------------------------- ### Get printers Source: https://github.com/arcticlampyrid/winprint.rs/blob/main/_autodocs/INDEX.md Retrieves a list of all available printers on the system. ```APIDOC ## PrinterDevice all() ### Description Retrieves a list of all available printers on the system. ### Method `PrinterDevice.all()` ### Parameters None ### Response - A list of `PrinterDevice` objects representing available printers. ``` -------------------------------- ### DxgiPrintContext::new Source: https://github.com/arcticlampyrid/winprint.rs/blob/main/_autodocs/api-reference-dxgi.md Creates and initializes a new DXGI print context. This involves setting up Direct3D, Direct2D, and DXGI devices, as well as print job targets and controls. ```APIDOC ## DxgiPrintContext::new ### Description Create and initialize a new DXGI print context. ### Method `new` ### Signature `pub fn new(device: &PrinterDevice, options: &PrintTicket, job_name: &OsStr) -> Result` ### Parameters #### Path Parameters - **device** (`&PrinterDevice`) - Required - Target printer device - **options** (`&PrintTicket`) - Required - Print settings and preferences - **job_name** (`&OsStr`) - Required - Name for the print job (appears in printer queue) ### Return Type `Result` — Initialized context ready for rendering ### Throws/Rejects - `DxgiPrintContextError::PrintTicketError`: Print ticket conversion to DEVMODE fails - `DxgiPrintContextError::FailedToCreateEvent`: Cannot create event handle for job completion - `DxgiPrintContextError::InitializeDirectX`: Direct3D, Direct2D, or DXGI initialization fails - `DxgiPrintContextError::FailedToStartJob`: Cannot create print job or establish print control - `DxgiPrintContextError::StreamNotAllocated`: Memory stream allocation for print ticket fails ### Example ```rust use winprint::printer::PrinterDevice; use winprint::ticket::PrintTicket; use winprint::printer::DxgiPrintContext; use std::ffi::OsStr; let device = PrinterDevice::all() .unwrap() .into_iter() .find(|d| d.name() == "My Printer") .unwrap(); let ticket = PrintTicket::default(); let context = DxgiPrintContext::new( &device, &ticket, OsStr::new("My Print Job"), )?; // Use context.d2d_context for drawing... // Use context.print_control to add pages... context.close_and_wait()?; ``` ``` -------------------------------- ### PageResolution Source: https://github.com/arcticlampyrid/winprint.rs/blob/main/_autodocs/api-reference-feature-options.md Represents page resolution options, providing methods to get DPI and display name. ```APIDOC ## PageResolution ### Description Represents page resolution options, providing methods to get DPI and display name. ### Predefined Names Device-dependent (no standard enum) ### Queryable From `PrintCapabilities::page_resolutions()` ### Methods - `resolution() -> (u32, u32)` — (X DPI, Y DPI) - `display_name() -> Option<&str>` ### Example ```rust for resolution in capabilities.page_resolutions() { if let Some(name) = resolution.display_name() { println!("Resolution: {}", name); } } ``` ``` -------------------------------- ### Create XpsPrinter Instance Source: https://github.com/arcticlampyrid/winprint.rs/blob/main/_autodocs/api-reference-printers.md Instantiate an XpsPrinter for a specific printer device. Ensure the PrinterDevice is correctly identified. ```rust use winprint::printer::{PrinterDevice, XpsPrinter}; let device = PrinterDevice::all() .unwrap() .into_iter() .find(|d| d.name() == "My Printer") .unwrap(); let xps_printer = XpsPrinter::new(device); ``` -------------------------------- ### Catching EnumDeviceError Source: https://github.com/arcticlampyrid/winprint.rs/blob/main/_autodocs/errors.md Example of how to catch and handle the EnumDeviceError when enumerating printer devices. This demonstrates specific error matching. ```rust use winprint::printer::{PrinterDevice, EnumDeviceError}; match PrinterDevice::all() { Ok(devices) => { /* use devices */ }, Err(EnumDeviceError::FailedToEnumPrinterDevice(e)) => { eprintln!("Cannot enumerate printers: {}", e); } } ``` -------------------------------- ### Custom Print Rendering with DxgiPrintContext Source: https://github.com/arcticlampyrid/winprint.rs/blob/main/_autodocs/api-reference-dxgi.md Demonstrates how to use DxgiPrintContext for custom rendering scenarios. It shows how to obtain Direct2D context, create a command list, draw content, and add it as a page to the print job. Ensure `close_and_wait()` is called before the context is dropped. ```rust use winprint::printer::{PrinterDevice, DxgiPrintContext}; use winprint::ticket::PrintTicket; use std::ffi::OsStr; fn custom_print_rendering(device: &PrinterDevice) -> Result<(), Box> { let ticket = PrintTicket::default(); let context = DxgiPrintContext::new(device, &ticket, OsStr::new("Custom Job"))?; // Get Direct2D context for drawing let d2d_context = &context.d2d_context; let print_control = &context.print_control; let wic_factory = &context.wic_factory; unsafe { // Example: Create a command list and add as a page let command_list = d2d_context.CreateCommandList()?; d2d_context.SetTarget(&command_list); d2d_context.BeginDraw(); // Draw content here... d2d_context.EndDraw(None, None)?; command_list.Close()?; // Add page to print job use winprint::printer::DxgiPrintContext; use windows::Win32::Graphics::Direct2D::Common::D2D_SIZE_F; let page_size = D2D_SIZE_F { width: 8.5 * 96.0, // 8.5 inches at 96 DPI height: 11.0 * 96.0, // 11 inches at 96 DPI }; print_control.AddPage(&command_list, page_size, None, None, None)?; } context.close_and_wait()?; Ok(()) } ``` -------------------------------- ### PageMediaSize Source: https://github.com/arcticlampyrid/winprint.rs/blob/main/_autodocs/api-reference-feature-options.md Represents standard page media sizes. It provides methods to get the physical dimensions and convert to predefined names. ```APIDOC ## PageMediaSize ### Description Represents standard page media sizes. It provides methods to get the physical dimensions and convert to predefined names. ### Queryable From `PrintCapabilities::page_media_sizes()` ### Methods - `size() -> MediaSizeTuple` — Physical dimensions in microns - `as_predefined_name() -> Option` - `display_name() -> Option<&str>` ### Example ```rust let media = capabilities.page_media_sizes() .find(|m| m.as_predefined_name() == Some(PredefinedMediaName::ISOA4)) .unwrap(); let size = media.size(); println!("A4: {}×{} µm", size.width_in_micron(), size.height_in_micron()); ``` ``` -------------------------------- ### Configure Print Ticket with Media Size Source: https://github.com/arcticlampyrid/winprint.rs/blob/main/_autodocs/README.md Builds a print ticket and configures it with a specific media size, like ISO A4. Requires a PrintCapabilities instance. ```rust use winprint::ticket::{PrintTicketBuilder, PredefinedMediaName}; let mut builder = PrintTicketBuilder::new(&device)?; // Add A4 size let a4 = capabilities .page_media_sizes() .find(|m| m.as_predefined_name() == Some(PredefinedMediaName::ISOA4)) .unwrap(); builder.merge(a4)?; let ticket = builder.build()?; ``` -------------------------------- ### Create and Initialize DxgiPrintContext Source: https://github.com/arcticlampyrid/winprint.rs/blob/main/_autodocs/api-reference-dxgi.md Initializes a new DXGI print context with the specified printer device, print ticket, and job name. This context is required for subsequent drawing and page submission operations. Ensure the printer device is valid and the job name is correctly formatted. ```rust use winprint::printer::PrinterDevice; use winprint::ticket::PrintTicket; use winprint::printer::DxgiPrintContext; use std::ffi::OsStr; let device = PrinterDevice::all() .unwrap() .into_iter() .find(|d| d.name() == "My Printer") .unwrap(); let ticket = PrintTicket::default(); let context = DxgiPrintContext::new( &device, &ticket, OsStr::new("My Print Job"), )?; // Use context.d2d_context for drawing... // Use context.print_control to add pages... context.close_and_wait()?; ``` -------------------------------- ### Get All Supported Duplex Modes Source: https://github.com/arcticlampyrid/winprint.rs/blob/main/_autodocs/api-reference-print-capabilities.md Retrieves an iterator over all supported duplex (two-sided printing) modes. This corresponds to the Print Schema's JobDuplexAllDocumentsContiguously keyword. ```rust let capabilities = PrintCapabilities::fetch(&device)?; for duplex in capabilities.duplexes() { println!("Duplex option: {:?}", duplex.display_name()); } ``` -------------------------------- ### Catching XpsPrinterError Source: https://github.com/arcticlampyrid/winprint.rs/blob/main/_autodocs/errors.md Example of how to catch and handle XpsPrinterError during XPS printing. This demonstrates handling specific errors like object factory creation or stream availability. ```rust use winprint::printer::{XpsPrinter, FilePrinter, XpsPrinterError}; use std::path::Path; let printer = XpsPrinter::new(device); match printer.print(Path::new("doc.xps"), Default::default()) { Ok(()) => println!("Printed successfully"), Err(XpsPrinterError::FailedToCreateObjectFactory(e)) => { eprintln!("XPS factory error: {}", e); } Err(XpsPrinterError::StreamNotAvailable) => { eprintln!("XPS stream initialization failed"); } Err(e) => eprintln!("XPS print error: {}", e), } ``` -------------------------------- ### Create New PrintTicketBuilder Source: https://github.com/arcticlampyrid/winprint.rs/blob/main/_autodocs/api-reference-print-ticket.md Initializes a new PrintTicketBuilder for a specified printer device. Ensure a printer device is available. ```rust use winprint::ticket::PrintTicketBuilder; use winprint::printer::PrinterDevice; let device = PrinterDevice::all()?.into_iter().next().unwrap(); let builder = PrintTicketBuilder::new(&device)?; ``` -------------------------------- ### PdfiumPrinter::new Source: https://github.com/arcticlampyrid/winprint.rs/blob/main/_autodocs/api-reference-printers.md Initializes a new PDFium printer instance, which uses the PDFium library for rendering PDF documents before printing. ```APIDOC ## PdfiumPrinter::new ### Description Creates a new PDFium printer instance for the given device. ### Method `new` ### Signature `pub fn new(printer: PrinterDevice) -> Self` ### Parameters - **printer** (`PrinterDevice`) - Required - Target printer device ### Return Type `PdfiumPrinter` - A new printer instance bound to the device ### Example ```rust use winprint::printer::{PrinterDevice, PdfiumPrinter}; let device = PrinterDevice::all() .unwrap() .into_iter() .find(|d| d.name() == "My Printer") .unwrap(); let pdf_printer = PdfiumPrinter::new(device); ``` ``` -------------------------------- ### Consume PrintTicket to get XML bytes Source: https://github.com/arcticlampyrid/winprint.rs/blob/main/_autodocs/api-reference-print-ticket.md Use the `into_xml` method to extract the underlying XML bytes from a `PrintTicket` by consuming it. This is useful when the ticket is no longer needed. ```rust use winprint::ticket::PrintTicket; let ticket = PrintTicket::default(); let xml = ticket.into_xml(); println!("XML bytes: {} bytes", xml.len()); ``` -------------------------------- ### XpsPrinter::new Source: https://github.com/arcticlampyrid/winprint.rs/blob/main/_autodocs/api-reference-printers.md Creates a new XPS printer instance for a specified printer device. This is used to initialize the printer for handling XPS documents. ```APIDOC ## XpsPrinter::new ### Description Creates a new XPS printer instance for the given device. ### Method `new` ### Signature `pub fn new(printer: PrinterDevice) -> Self` ### Parameters - **printer** (`PrinterDevice`) - Required - Target printer device ### Return Type `XpsPrinter` - A new printer instance bound to the device ### Example ```rust use winprint::printer::{PrinterDevice, XpsPrinter}; let device = PrinterDevice::all() .unwrap() .into_iter() .find(|d| d.name() == "My Printer") .unwrap(); let xps_printer = XpsPrinter::new(device); ``` ``` -------------------------------- ### Get Maximum Copies Source: https://github.com/arcticlampyrid/winprint.rs/blob/main/_autodocs/api-reference-print-capabilities.md Fetches print capabilities and retrieves the maximum number of copies the printer can handle. Prints the value if available, otherwise indicates it's not reported. ```rust let capabilities = PrintCapabilities::fetch(&device)?; if let Some(max) = capabilities.max_copies() { println!("Max copies: {:?}", max.value()); } ``` -------------------------------- ### Get All Supported Page Orientations Source: https://github.com/arcticlampyrid/winprint.rs/blob/main/_autodocs/api-reference-print-capabilities.md Retrieves an iterator over all supported page orientations (e.g., Portrait, Landscape). Use this to determine the valid orientation settings for a print job. ```rust use winprint::ticket::PredefinedPageOrientation; let capabilities = PrintCapabilities::fetch(&device)?; for orientation in capabilities.page_orientations() { println!("Orientation: {:?}", orientation.as_predefined_name()); } ``` -------------------------------- ### Create PdfiumPrinter Instance Source: https://github.com/arcticlampyrid/winprint.rs/blob/main/_autodocs/api-reference-printers.md Instantiate a PdfiumPrinter for a specific printer device. This printer uses the PDFium library for rendering. ```rust use winprint::printer::{PrinterDevice, PdfiumPrinter}; let device = PrinterDevice::all() .unwrap() .into_iter() .find(|d| d.name() == "My Printer") .unwrap(); let pdf_printer = PdfiumPrinter::new(device); ``` -------------------------------- ### Listing Available Page Media Sizes Source: https://github.com/arcticlampyrid/winprint.rs/blob/main/_autodocs/api-reference-feature-options.md Iterates through all available page media size options from the printer capabilities and prints their predefined names. Requires fetching print capabilities first. ```rust use winprint::ticket::FeatureOptionPack; let capabilities = PrintCapabilities::fetch(&device)?; for media in PageMediaSize::list(&capabilities) { println!("Option: {:?}", media.as_predefined_name()); } ``` -------------------------------- ### DxgiPrintContextError Enum Source: https://github.com/arcticlampyrid/winprint.rs/blob/main/_autodocs/api-reference-dxgi.md Defines the possible errors that can occur when using the DxgiPrintContext. These include issues with print tickets, COM initialization, DirectX, starting jobs, and stream allocation. ```rust pub enum DxgiPrintContextError { /// Print ticket error. PrintTicketError(#[source] ToDevModeError), /// Failed to create event. FailedToCreateEvent(#[source] windows::core::Error), /// Failed to initialize DirectX. InitializeDirectX(#[source] windows::core::Error), /// Failed to start job. FailedToStartJob(#[source] windows::core::Error), /// Stream not allocated. StreamNotAllocated, /// Failed to close print control. FailedToClosePrintControl(#[source] windows::core::Error), } ``` -------------------------------- ### Create a PrintTicket from XML Source: https://github.com/arcticlampyrid/winprint.rs/blob/main/_autodocs/api-reference-print-ticket.md Use the `from_xml` method to create a `PrintTicket` from custom XML bytes. The XML should be valid Print Schema. Validation occurs during printing or merging. ```rust use winprint::ticket::PrintTicket; let xml = r###""###; let ticket = PrintTicket::from_xml(xml); ``` -------------------------------- ### Create printer Source: https://github.com/arcticlampyrid/winprint.rs/blob/main/_autodocs/INDEX.md Creates a new printer instance, typically for XPS printing. ```APIDOC ## XpsPrinter new() ### Description Creates a new printer instance, typically for XPS printing. ### Method `XpsPrinter.new()` ### Parameters None ### Response - A new `XpsPrinter` object. ``` -------------------------------- ### Iterating Through Available Options Source: https://github.com/arcticlampyrid/winprint.rs/blob/main/_autodocs/api-reference-feature-options.md Shows how to iterate through the available options for a given feature, such as page media sizes, using the `list` method. This allows developers to discover and process all possible settings. ```APIDOC ## Iterating Options ```rust for media in PageMediaSize::list(&capabilities) { println!("Media: {:?}", media.as_predefined_name()); if let Some(name) = media.display_name() { println!(" Display: {}", name); } } ``` ``` -------------------------------- ### Get All Supported Output Color Modes Source: https://github.com/arcticlampyrid/winprint.rs/blob/main/_autodocs/api-reference-print-capabilities.md Retrieves an iterator over all supported output color modes (e.g., color, monochrome). Use this to check the available color printing options. ```rust let capabilities = PrintCapabilities::fetch(&device)?; for color in capabilities.page_output_colors() { println!("Color mode: {:?}", color.display_name()); } ``` -------------------------------- ### Iterate Through Page Media Sizes Source: https://github.com/arcticlampyrid/winprint.rs/blob/main/_autodocs/api-reference-feature-options.md Shows how to iterate over all available page media sizes from the print capabilities, printing their predefined names and display names if available. ```rust for media in PageMediaSize::list(&capabilities) { println!("Media: {:?}", media.as_predefined_name()); if let Some(name) = media.display_name() { println!(" Display: {}", name); } } ``` -------------------------------- ### Build Custom Print Ticket with Specific Settings Source: https://github.com/arcticlampyrid/winprint.rs/blob/main/_autodocs/api-reference-print-ticket.md This snippet shows how to construct a custom print ticket by fetching printer capabilities and merging specific settings like media size (A4) and orientation (Landscape). It then uses an XpsPrinter to print a file with the custom ticket. ```rust use winprint::printer::{PrinterDevice, FilePrinter, XpsPrinter}; use winprint::ticket::{PrintTicketBuilder, PrintCapabilities, PredefinedMediaName}; use std::path::Path; fn print_with_custom_settings(file_path: &str) -> Result<(), Box> { // Get printer device let device = PrinterDevice::all()? .into_iter() .find(|d| d.name() == "My Printer") .ok_or("Printer not found")?; // Fetch capabilities let capabilities = PrintCapabilities::fetch(&device)?; // Build custom ticket let mut builder = PrintTicketBuilder::new(&device)?; // Merge A4 media size let a4 = capabilities .page_media_sizes() .find(|m| m.as_predefined_name() == Some(PredefinedMediaName::ISOA4)) .ok_or("A4 not supported")?; builder.merge(a4)?; // Merge landscape orientation let landscape = capabilities .page_orientations() .find(|o| o.as_predefined_name() == Some(PredefinedPageOrientation::Landscape)) .ok_or("Landscape not supported")?; builder.merge(landscape)?; // Build final ticket let ticket = builder.build()?; // Print let printer = XpsPrinter::new(device); printer.print(Path::new(file_path), ticket)?; Ok(()) } ``` -------------------------------- ### Check if Printer is Local Source: https://github.com/arcticlampyrid/winprint.rs/blob/main/_autodocs/api-reference-printer-device.md Determines if a printer device is connected locally to the system. This is a convenient way to filter for local printers. The example iterates through all devices and prints the names of local ones. ```rust let devices = PrinterDevice::all().unwrap(); for device in devices { if device.is_local() { println!("Local printer: {}", device.name()); } } ``` -------------------------------- ### WinPdfPrinter::new Source: https://github.com/arcticlampyrid/winprint.rs/blob/main/_autodocs/api-reference-printers.md Creates a new Windows PDF printer instance for a given printer device. ```APIDOC ## WinPdfPrinter::new ### Description Creates a new Windows PDF printer instance for the given device using the Windows Runtime (WinRT) PDF API. ### Method `new` ### Signature `pub fn new(printer: PrinterDevice) -> Self` ### Parameters #### Path Parameters - `printer` (PrinterDevice) - Required - The target printer device. ### Return Type `WinPdfPrinter` - A new printer instance bound to the device. ``` -------------------------------- ### Create ImagePrinter Instance Source: https://github.com/arcticlampyrid/winprint.rs/blob/main/_autodocs/api-reference-printers.md Instantiate an ImagePrinter for a specific printer device. This printer is suitable for raster image files. ```rust use winprint::printer::{PrinterDevice, ImagePrinter}; let device = PrinterDevice::all() .unwrap() .into_iter() .find(|d| d.name() == "My Printer") .unwrap(); let image_printer = ImagePrinter::new(device); ``` -------------------------------- ### Get a reference to PrintTicket XML bytes Source: https://github.com/arcticlampyrid/winprint.rs/blob/main/_autodocs/api-reference-print-ticket.md Use the `get_xml` method to obtain an immutable reference to the XML bytes of a `PrintTicket` without consuming it. This is useful for inspecting the ticket's content. ```rust use winprint::ticket::PrintTicket; let ticket = PrintTicket::default(); let xml_ref = ticket.get_xml(); println!("XML size: {} bytes", xml_ref.len()); ``` -------------------------------- ### XpsPrinterError Variants Source: https://github.com/arcticlampyrid/winprint.rs/blob/main/_autodocs/errors.md Defines various errors that can occur during XPS document printing. This includes issues with event creation, object factories, job start, print tickets, and document writing. ```rust pub enum XpsPrinterError { /// Failed to create event. #[error("Failed to create event")] FailedToCreateEvent(#[source] windows::core::Error), /// Failed to create object factory. #[error("Failed to create object factory")] FailedToCreateObjectFactory(#[source] windows::core::Error), /// Failed to start job. #[error("Failed to start job")] FailedToStartJob(#[source] windows::core::Error), /// Failed to apply print ticket. #[error("Failed to apply print ticket")] FailedToApplyPrintTicket(#[source] windows::core::Error), /// Failed to write document. #[error("Failed to write document")] FailedToWriteDocument(#[source] windows::core::Error), /// Stream is not available. #[error("Stream is not available")] StreamNotAvailable, } ``` -------------------------------- ### Implement PredefinedName Trait for Enum Source: https://github.com/arcticlampyrid/winprint.rs/blob/main/_autodocs/api-reference-feature-options.md Example implementation of the `from_name` method for the `PredefinedName` trait, converting an XML qualified name to an enum variant. It checks the namespace and attempts to parse the local name. ```rust impl PredefinedName for PredefinedMediaName { fn from_name(name: &OwnedName) -> Option { if name.namespace_ref() == Some(NS_PSK) { Self::from_str(name.local_name.as_str()).ok() } else { None } } } ``` -------------------------------- ### Add winprint Dependency (Default) Source: https://github.com/arcticlampyrid/winprint.rs/blob/main/_autodocs/README.md Includes the winprint crate with default features enabled, such as PDFium support. ```toml [dependencies] winprint = "0.2" ```