marlon_printers/
lib.rs

1//! Get printers and print files or bytes on unix and windows
2//!
3//! Printers **is not a lib for printer drivers or cups**. Printers is a simple lib to call printers apis for unix *(cups)* and windows *(winspool)* systems.
4//! Printer can provide a list of printers available on the system and perform document printing.
5//!
6//! ```rust
7//! use printers;
8//!
9//! let printers = printers::get_printers();
10//!
11//! for printer in printers {
12//!     let job1 = printer.print("42".as_bytes(), Some("Everything"));
13//!     let job2 = printer.print_file("/path/to/any.file", None);
14//!
15//!     println!("{:?}", printer);
16//!     println!("{:?}", job1);
17//!     println!("{:?}", job2);
18//! }
19//! ```
20//!
21//!
22use std::env;
23use std::fs::File;
24use std::io::Write;
25use std::time::{SystemTime, UNIX_EPOCH};
26
27
28/// Printer and Job control
29pub mod printer;
30pub mod shared;
31
32#[cfg(target_family = "unix")]
33mod unix;
34
35#[cfg(target_family = "windows")]
36mod windows;
37
38/**
39 * Print bytes on specific printer
40 */
41pub fn print(printer_name: &str, buffer: &[u8], job_name: Option<&str>) -> Result<bool, String> {
42    let time = SystemTime::now()
43        .duration_since(UNIX_EPOCH)
44        .unwrap()
45        .subsec_nanos();
46
47    let tmp_file_path = env::temp_dir().join(time.to_string());
48
49    let mut tmp_file = File::create(&tmp_file_path).unwrap();
50    let save = tmp_file.write(buffer);
51
52    if save.is_err() {
53        let error = save.err().unwrap();
54        return Err(error.to_string())
55    }
56
57    return print_file(printer_name, tmp_file_path.to_str().unwrap(), job_name);
58
59}
60
61/**
62 * Print specific file on a specific printer
63 */
64pub fn print_file(printer_name: &str, file_path: &str, job_name: Option<&str>) -> Result<bool, String> {
65
66    #[cfg(target_family = "unix")]
67    return unix::print(printer_name, file_path, job_name);
68
69    #[cfg(target_family = "windows")]
70    return windows::print(printer_name, file_path, job_name);
71
72}
73
74/**
75 * Return all available printers on system
76 */
77pub fn get_printers() -> Vec<printer::Printer> {
78    #[cfg(target_family = "windows")]
79    return windows::get_printers();
80
81    #[cfg(target_family = "unix")]
82    return unix::get_printers();
83
84    #[cfg(target_family = "wasm")]
85    panic!("Unsupported Platform");
86}
87
88/**
89 * If you known the printer Name you can try get the printer directly from they
90 */
91pub fn get_printer_by_name(name: &str) -> Option<printer::Printer> {
92    let printers = get_printers();
93
94    let opt = printers.iter().find(|&printer| {
95        return printer.clone().name.eq(name) || printer.clone().system_name.eq(name);
96    });
97
98    return opt.cloned();
99}