### Write CUPS Raster Files in Rust Source: https://context7.com/arcticlampyrid/print_raster.rs/llms.txt This example demonstrates creating CUPS Raster documents with comprehensive page settings, including color management, media properties, and printer options. It leverages the `print_raster` crate and `tokio` for asynchronous I/O. The function sets up a `CupsRasterV1Writer` and writes pixel data to it. Dependencies include `futures` and `print_raster`. ```rust use futures::AsyncWriteExt; use print_raster::{ model::cups::*, writer::{cups::v1::CupsRasterV1Writer, RasterPageWriter, RasterWriter}, }; use std::pin::Pin; #[tokio::main] async fn main() -> Result<(), Box> { let mut output = Vec::::new(); // Create CUPS V1 writer with sync word (version and endianness) let writer = CupsRasterV1Writer::new( Pin::new(&mut output), CupsSyncWord::V1BigEndian ).await?; // Create comprehensive page header let page_header = CupsPageHeaderV1 { media_class: "PwgRaster".to_string(), media_color: String::new(), media_type: "auto".to_string(), output_type: String::new(), advance_distance: 0, advance_media: CupsAdvance::AfterPage, collate: false, cut_media: CupsCut::Never, duplex: false, resolution: CupsResolution { cross_feed: 300, feed: 300, }, imaging_bbox: CupsImagingBoundingBox { left: 0, bottom: 0, right: 2400, top: 2400, }, insert_sheet: false, jog: CupsJog::Never, leading_edge: CupsLeadingEdge::Top, margins: CupsMargins { left: 0, bottom: 0 }, manual_feed: false, media_position: 0, media_weight: 0, mirror_print: false, negative_print: false, num_copies: 1, orientation: CupsOrientation::Portrait, output_face_up: false, page_size: CupsPageSize { width: 2400, height: 2400, }, separations: false, tray_switch: false, tumble: false, width: 800, height: 800, cups_media_type: 0, bits_per_color: 8, bits_per_pixel: 24, bytes_per_line: 2400, color_order: CupsColorOrder::Chunky, color_space: CupsColorSpace::sRGB, cups_compression: 0, cups_row_count: 0, cups_row_feed: 0, cups_row_step: 0, }; // Write page let pixel_data = vec![0u8; 800 * 800 * 3]; let mut page_writer = writer.next_page(&page_header).await?; page_writer.content_mut().write_all(&pixel_data).await?; page_writer.finish().await?; Ok(()) } ``` -------------------------------- ### Read URF Raster Files with Rust Source: https://context7.com/arcticlampyrid/print_raster.rs/llms.txt This snippet demonstrates how to read Universal Raster Format (URF) files page by page using the asynchronous streaming API provided by the print_raster crate. It shows how to open a file, create a UrfReader, iterate through pages, access page metadata (dimensions, DPI, color space), and read pixel data. Dependencies include futures, tokio, and tokio_util. ```rust use futures::{io::BufReader, AsyncReadExt}; use print_raster::reader::{ urf::UrfReader, RasterPageReader, RasterReader, }; use std::{path::Path, pin::pin}; use tokio_util::compat::TokioAsyncReadCompatExt; #[tokio::main] async fn main() -> Result<(), Box> { // Open the URF raster file let file = tokio::fs::File::open("input.urf").await?; let pinned_file_reader = pin!(BufReader::new(file.compat())); // Create a URF reader let reader = UrfReader::new(pinned_file_reader).await?; // Iterate through pages let mut page_index = 0; let mut page_next = reader.next_page().await?; while let Some(mut page) = page_next { // Access page metadata println!("Page {}: {}x{} pixels, {} DPI, {:?} color space", page_index, page.header().width, page.header().height, page.header().dot_per_inch, page.header().color_space ); // Read pixel data let mut pixel_data = Vec::::new(); page.content_mut().read_to_end(&mut pixel_data).await?; println!("Read {} bytes of pixel data", pixel_data.len()); // Move to next page (consumes current page) page_next = page.next_page().await?; page_index += 1; } Ok(()) } ``` -------------------------------- ### Write URF (Apple Raster) Files in Rust Source: https://context7.com/arcticlampyrid/print_raster.rs/llms.txt This snippet demonstrates writing multi-page URF raster documents with custom headers for each page. It utilizes the `print_raster` crate and `tokio` for asynchronous operations. The function takes pixel data and writes it to an output buffer in URF format. Dependencies include `futures` and `print_raster`. ```rust use futures::AsyncWriteExt; use print_raster::{ model::urf::*, writer::{urf::UrfWriter, RasterPageWriter, RasterWriter}, }; use std::pin::Pin; #[tokio::main] async fn main() -> Result<(), Box> { // RGB pixel data (8x8 image, 24 bpp) let pixel_data: Vec = vec![ 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0xff, 0xff, 0x00, // ... 8x8x3 = 192 bytes total ]; // Create output buffer let mut output = Vec::::new(); // Create URF writer with page count let writer = UrfWriter::new( Pin::new(&mut output), &UrfHeader { page_count: 2 } ).await?; // Define page header let page_header = UrfPageHeader { bits_per_pixel: 24, color_space: UrfColorSpace::sRGB, width: 8, height: 8, duplex: UrfDuplex::NoDuplex, quality: UrfQuality::Normal, media_position: UrfMediaPosition::Auto, media_type: UrfMediaType::Auto, dot_per_inch: 300, }; // Write first page let mut page_writer = writer.next_page(&page_header).await?; page_writer.content_mut().write_all(&pixel_data).await?; // Write second page page_writer = page_writer.next_page(&page_header).await?; page_writer.content_mut().write_all(&pixel_data).await?; // Finalize the document (required) page_writer.finish().await?; println!("Wrote {} bytes", output.len()); Ok(()) } ``` -------------------------------- ### Convert CUPS Raster to URF Format in Rust Source: https://context7.com/arcticlampyrid/print_raster.rs/llms.txt This snippet demonstrates reading a CUPS/PWG raster file, extracting page data and headers, and then writing the same content to the URF format. It utilizes asynchronous I/O and the print_raster library for format conversion. Dependencies include the `futures`, `print_raster`, and `tokio` crates. It takes an input file (e.g., 'input.pwg') and writes to an output file ('output.urf'). ```rust use futures::{io::BufReader, AsyncReadExt, AsyncWriteExt}; use print_raster::{ model::{ cups::{CupsColorSpace, CupsPageHeaderV2}, urf::{UrfColorSpace, UrfDuplex, UrfHeader, UrfMediaPosition, UrfMediaType, UrfPageHeader, UrfQuality}, }, reader::{cups::unified::CupsRasterUnifiedReader, RasterPageReader, RasterReader}, writer::{urf::UrfWriter, RasterPageWriter, RasterWriter}, }; use std::pin::Pin; use tokio_util::compat::TokioAsyncReadCompatExt; #[tokio::main] async fn main() -> Result<(), Box> { // Read CUPS/PWG file let file = tokio::fs::File::open("input.pwg").await?; let pinned_reader = pin!(BufReader::new(file.compat())); let reader = CupsRasterUnifiedReader::new(pinned_reader).await?; // Collect page data and headers let mut pages = Vec::new(); let mut page_next = reader.next_page().await?; while let Some(mut page) = page_next { let header = page.header().clone(); let mut data = Vec::new(); page.content_mut().read_to_end(&mut data).await?; pages.push((header, data)); page_next = page.next_page().await?; } // Write URF file let mut output = Vec::::new(); let writer = UrfWriter::new( Pin::new(&mut output), &UrfHeader { page_count: pages.len() as u32 } ).await?; let mut page_writer = None; for (cups_header, data) in pages { let urf_header = convert_header(&cups_header); page_writer = Some(match page_writer { None => writer.next_page(&urf_header).await?, Some(pw) => pw.next_page(&urf_header).await?, }); if let Some(ref mut pw) = page_writer { pw.content_mut().write_all(&data).await?; } } if let Some(pw) = page_writer { pw.finish().await?; } tokio::fs::write("output.urf", output).await?; Ok(()) } fn convert_header(cups: &CupsPageHeaderV2) -> UrfPageHeader { UrfPageHeader { bits_per_pixel: cups.v1.bits_per_pixel as u8, color_space: match cups.v1.color_space { CupsColorSpace::sRGB => UrfColorSpace::sRGB, CupsColorSpace::sGray => UrfColorSpace::sGray, _ => UrfColorSpace::sRGB, }, width: cups.v1.width, height: cups.v1.height, duplex: if cups.v1.duplex { if cups.v1.tumble { UrfDuplex::ShortSide } else { UrfDuplex::LongSide } } else { UrfDuplex::NoDuplex }, quality: UrfQuality::Normal, media_position: UrfMediaPosition::Auto, media_type: UrfMediaType::Auto, dot_per_inch: cups.v1.resolution.cross_feed, } } ``` -------------------------------- ### Read CUPS/PWG Raster Files with Rust Source: https://context7.com/arcticlampyrid/print_raster.rs/llms.txt This code snippet shows how to read CUPS Raster (V1, V2, V3) and PWG Raster files using the unified reader from the print_raster crate. The `CupsRasterUnifiedReader` automatically detects the format version, allowing for consistent handling of different CUPS-based formats. It demonstrates accessing page metadata such as byte order, dimensions, color information, and resolution, as well as reading pixel data. Dependencies include futures, tokio, and tokio_util. ```rust use futures::{io::BufReader, AsyncReadExt}; use print_raster::reader::{ cups::unified::CupsRasterUnifiedReader, RasterPageReader, RasterReader, }; use std::{path::Path, pin::pin}; use tokio_util::compat::TokioAsyncReadCompatExt; #[tokio::main] async fn main() -> Result<(), Box> { // Open CUPS/PWG raster file let file = tokio::fs::File::open("input.pwg").await?; let pinned_file_reader = pin!(BufReader::new(file.compat())); // Unified reader automatically detects version let reader = CupsRasterUnifiedReader::new(pinned_file_reader).await?; let mut page_index = 0; let mut page_next = reader.next_page().await?; while let Some(mut page) = page_next { // Check byte order and access header println!( "Page {}, ByteOrder = ?", page_index ); // Access V2 header (works for all versions) let header = page.header(); println!( " Dimensions: {}x{} pixels", header.v1.width, header.v1.height ); println!( " Color: {} bpp, {:?} space, {:?} order", header.v1.bits_per_pixel, header.v1.color_space, header.v1.color_order ); println!( " Resolution: {} x {} DPI", header.v1.resolution.cross_feed, header.v1.resolution.feed ); // Read image data let mut data = Vec::::new(); page.content_mut().read_to_end(&mut data).await?; page_next = page.next_page().await?; page_index += 1; } Ok(()) } ``` -------------------------------- ### Process URF Raster Files with Error Handling in Rust Source: https://context7.com/arcticlampyrid/print_raster.rs/llms.txt Reads a Unified Raster Format (URF) file asynchronously, handling potential I/O errors and URF-specific parsing issues. It iterates through pages, reads their content, and returns the total number of pages processed. Dependencies include `tokio`, `futures`, and `print_raster`. ```rust use futures::{io::BufReader, AsyncReadExt}; use print_raster::error::UrfError; use print_raster::reader::urf::UrfReader; use print_raster::reader::RasterPageReader; use std::pin::pin; use tokio_util::compat::TokioAsyncReadCompatExt; async fn process_urf(path: &str) -> Result { let file = tokio::fs::File::open(path) .await .map_err(|e| UrfError::Io(e.kind()))?; let pinned_reader = pin!(BufReader::new(file.compat())); let reader = UrfReader::new(pinned_reader).await?; let mut page_count = 0; let mut page_next = reader.next_page().await?; while let Some(mut page) = page_next { let mut data = Vec::new(); page.content_mut() .read_to_end(&mut data) .await .map_err(|e| UrfError::Io(e.kind()))?; page_next = page.next_page().await?; page_count += 1; } Ok(page_count) } ``` -------------------------------- ### Main Function for Raster File Processing in Rust Source: https://context7.com/arcticlampyrid/print_raster.rs/llms.txt The main entry point for the Rust program, demonstrating the usage of `process_urf` and `process_cups` functions. It handles and prints any errors encountered during the processing of both file types. This function requires the `tokio` runtime. ```rust use futures::{io::BufReader, AsyncReadExt}; use print_raster::error::{CupsRasterError, UrfError}; use print_raster::reader::cups::unified::CupsRasterUnifiedReader; use print_raster::reader::urf::UrfReader; use print_raster::reader::{RasterPageReader, RasterReader}; use std::path::Path; use std::pin::pin; use tokio_util::compat::TokioAsyncReadCompatExt; #[tokio::main] async fn main() -> Result<(), Box> { // URF with error handling match process_urf("input.urf").await { Ok(pages) => println!("Successfully processed {} URF pages", pages), Err(e) => eprintln!("URF error: {}", e), } // CUPS with error handling match process_cups("input.pwg").await { Ok(pages) => println!("Successfully processed {} CUPS pages", pages), Err(e) => eprintln!("CUPS error: {}", e), } Ok(()) } // Placeholder for process_urf and process_cups functions if not defined above async fn process_urf(path: &str) -> Result { Ok(0) } async fn process_cups(path: &str) -> Result { Ok(0) } ``` -------------------------------- ### Process CUPS PWG Raster Files with Error Handling in Rust Source: https://context7.com/arcticlampyrid/print_raster.rs/llms.txt Reads a CUPS PWG raster file asynchronously, managing potential I/O errors and CUPS-specific parsing problems. It loops through each page, extracts its data, and returns the count of pages. Requires `tokio`, `futures`, and `print_raster` crates. ```rust use futures::{io::BufReader, AsyncReadExt}; use print_raster::error::CupsRasterError; use print_raster::reader::cups::unified::CupsRasterUnifiedReader; use print_raster::reader::RasterPageReader; use std::pin::pin; use tokio_util::compat::TokioAsyncReadCompatExt; async fn process_cups(path: &str) -> Result { let file = tokio::fs::File::open(path) .await .map_err(|e| CupsRasterError::Io(e.kind()))?; let pinned_reader = pin!(BufReader::new(file.compat())); let reader = CupsRasterUnifiedReader::new(pinned_reader).await?; let mut page_count = 0; let mut page_next = reader.next_page().await?; while let Some(mut page) = page_next { let mut data = Vec::new(); page.content_mut() .read_to_end(&mut data) .await .map_err(|e| CupsRasterError::Io(e.kind()))?; page_next = page.next_page().await?; page_count += 1; } Ok(page_count) } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.