#[derive(Clone, Debug, PartialEq, Default)]
pub enum PaperSize {
#[default]
Letter,
Legal,
Executive,
A3,
A4,
A5,
B4,
B5,
Tabloid,
Custom(u32),
}
impl PaperSize {
pub fn code(&self) -> u32 {
match self {
PaperSize::Letter => 1,
PaperSize::Legal => 5,
PaperSize::Executive => 7,
PaperSize::A3 => 8,
PaperSize::A4 => 9,
PaperSize::A5 => 11,
PaperSize::B4 => 12,
PaperSize::B5 => 13,
PaperSize::Tabloid => 3,
PaperSize::Custom(code) => *code,
}
}
pub fn from_code(code: u32) -> Self {
match code {
1 => PaperSize::Letter,
3 => PaperSize::Tabloid,
5 => PaperSize::Legal,
7 => PaperSize::Executive,
8 => PaperSize::A3,
9 => PaperSize::A4,
11 => PaperSize::A5,
12 => PaperSize::B4,
13 => PaperSize::B5,
other => PaperSize::Custom(other),
}
}
}
#[derive(Clone, Debug, PartialEq, Default)]
pub enum Orientation {
#[default]
Portrait,
Landscape,
}
#[derive(Clone, Debug, PartialEq, Default)]
pub enum PageOrder {
#[default]
DownThenOver,
OverThenDown,
}
#[derive(Clone, Debug, PartialEq, Default)]
pub enum CellComments {
#[default]
None,
AtEnd,
AsDisplayed,
}
#[derive(Clone, Debug, PartialEq, Default)]
pub enum PrintErrors {
#[default]
Displayed,
Blank,
Dash,
NA,
}
#[derive(Clone, Debug)]
pub struct PageMargins {
pub left: f64,
pub right: f64,
pub top: f64,
pub bottom: f64,
pub header: f64,
pub footer: f64,
}
impl Default for PageMargins {
fn default() -> Self {
PageMargins {
left: 0.7,
right: 0.7,
top: 0.75,
bottom: 0.75,
header: 0.3,
footer: 0.3,
}
}
}
impl PageMargins {
pub fn uniform(margin: f64) -> Self {
PageMargins {
left: margin,
right: margin,
top: margin,
bottom: margin,
header: margin / 2.0,
footer: margin / 2.0,
}
}
pub fn narrow() -> Self {
PageMargins {
left: 0.25,
right: 0.25,
top: 0.75,
bottom: 0.75,
header: 0.3,
footer: 0.3,
}
}
pub fn wide() -> Self {
PageMargins {
left: 1.0,
right: 1.0,
top: 1.0,
bottom: 1.0,
header: 0.5,
footer: 0.5,
}
}
}
#[derive(Clone, Debug, Default)]
pub struct HeaderFooterSection {
pub left: Option<String>,
pub center: Option<String>,
pub right: Option<String>,
}
impl HeaderFooterSection {
pub fn parse_encoded(encoded: &str) -> Self {
let mut section = HeaderFooterSection::default();
let mut target: u8 = b'C';
let mut current = String::new();
let mut chars = encoded.chars().peekable();
let flush = |target: u8, text: &mut String, section: &mut HeaderFooterSection| {
if !text.is_empty() {
let value = Some(std::mem::take(text));
match target {
b'L' => section.left = value,
b'R' => section.right = value,
_ => section.center = value,
}
}
};
while let Some(c) = chars.next() {
if c == '&' {
match chars.peek() {
Some('L') | Some('C') | Some('R') => {
flush(target, &mut current, &mut section);
target = *chars.peek().unwrap() as u8;
chars.next();
continue;
}
Some('&') => {
current.push('&');
chars.next();
continue;
}
_ => {}
}
}
current.push(c);
}
flush(target, &mut current, &mut section);
section
}
pub fn new() -> Self {
Self::default()
}
pub fn with_left<S: Into<String>>(mut self, text: S) -> Self {
self.left = Some(text.into());
self
}
pub fn with_center<S: Into<String>>(mut self, text: S) -> Self {
self.center = Some(text.into());
self
}
pub fn with_right<S: Into<String>>(mut self, text: S) -> Self {
self.right = Some(text.into());
self
}
}
impl std::fmt::Display for HeaderFooterSection {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
if let Some(ref left) = self.left {
write!(f, "&L{}", left)?;
}
if let Some(ref center) = self.center {
write!(f, "&C{}", center)?;
}
if let Some(ref right) = self.right {
write!(f, "&R{}", right)?;
}
Ok(())
}
}
#[derive(Clone, Debug, Default)]
pub struct HeaderFooter {
pub odd_header: Option<HeaderFooterSection>,
pub odd_footer: Option<HeaderFooterSection>,
pub even_header: Option<HeaderFooterSection>,
pub even_footer: Option<HeaderFooterSection>,
pub first_header: Option<HeaderFooterSection>,
pub first_footer: Option<HeaderFooterSection>,
pub different_odd_even: bool,
pub different_first: bool,
pub scale_with_doc: bool,
pub align_with_margins: bool,
}
impl HeaderFooter {
pub fn new() -> Self {
HeaderFooter {
scale_with_doc: true,
align_with_margins: true,
..Default::default()
}
}
pub fn with_header(mut self, section: HeaderFooterSection) -> Self {
self.odd_header = Some(section);
self
}
pub fn with_footer(mut self, section: HeaderFooterSection) -> Self {
self.odd_footer = Some(section);
self
}
}
pub mod codes {
pub const PAGE_NUMBER: &str = "&P";
pub const TOTAL_PAGES: &str = "&N";
pub const DATE: &str = "&D";
pub const TIME: &str = "&T";
pub const FILE_PATH: &str = "&Z";
pub const FILE_NAME: &str = "&F";
pub const SHEET_NAME: &str = "&A";
pub const BOLD: &str = "&B";
pub const ITALIC: &str = "&I";
pub const UNDERLINE: &str = "&U";
pub const STRIKETHROUGH: &str = "&S";
pub fn font_size(size: u32) -> String {
format!("&{}", size)
}
pub fn font_name(name: &str) -> String {
format!("&\"{}\"", name)
}
}
#[derive(Clone, Debug, Default)]
pub struct PrintTitles {
pub rows: Option<String>,
pub cols: Option<String>,
}
impl PrintTitles {
pub fn with_rows<S: Into<String>>(mut self, rows: S) -> Self {
self.rows = Some(rows.into());
self
}
pub fn with_cols<S: Into<String>>(mut self, cols: S) -> Self {
self.cols = Some(cols.into());
self
}
}
#[derive(Clone, Debug)]
pub struct PageSetup {
pub paper_size: PaperSize,
pub orientation: Orientation,
pub scale: u32,
pub fit_to_width: Option<u32>,
pub fit_to_height: Option<u32>,
pub first_page_number: Option<u32>,
pub page_order: PageOrder,
pub black_and_white: bool,
pub draft: bool,
pub cell_comments: CellComments,
pub errors: PrintErrors,
pub horizontal_dpi: Option<u32>,
pub vertical_dpi: Option<u32>,
pub copies: u32,
pub margins: PageMargins,
pub header_footer: HeaderFooter,
pub print_titles: PrintTitles,
pub print_area: Option<String>,
pub print_gridlines: bool,
pub print_headings: bool,
pub center_horizontally: bool,
pub center_vertically: bool,
}
impl Default for PageSetup {
fn default() -> Self {
PageSetup {
paper_size: PaperSize::default(),
orientation: Orientation::default(),
scale: 100,
fit_to_width: None,
fit_to_height: None,
first_page_number: None,
page_order: PageOrder::default(),
black_and_white: false,
draft: false,
cell_comments: CellComments::default(),
errors: PrintErrors::default(),
horizontal_dpi: None,
vertical_dpi: None,
copies: 1,
margins: PageMargins::default(),
header_footer: HeaderFooter::new(),
print_titles: PrintTitles::default(),
print_area: None,
print_gridlines: false,
print_headings: false,
center_horizontally: false,
center_vertically: false,
}
}
}
impl PageSetup {
pub fn new() -> Self {
Self::default()
}
pub fn with_paper_size(mut self, size: PaperSize) -> Self {
self.paper_size = size;
self
}
pub fn with_orientation(mut self, orientation: Orientation) -> Self {
self.orientation = orientation;
self
}
pub fn with_scale(mut self, scale: u32) -> Self {
self.scale = scale.clamp(10, 400);
self
}
pub fn fit_to_page(mut self) -> Self {
self.fit_to_width = Some(1);
self.fit_to_height = Some(1);
self
}
pub fn fit_to_width(mut self, pages: u32) -> Self {
self.fit_to_width = Some(pages);
self
}
pub fn with_margins(mut self, margins: PageMargins) -> Self {
self.margins = margins;
self
}
pub fn with_print_area<S: Into<String>>(mut self, area: S) -> Self {
self.print_area = Some(area.into());
self
}
pub fn print_gridlines(mut self) -> Self {
self.print_gridlines = true;
self
}
pub fn center_on_page(mut self) -> Self {
self.center_horizontally = true;
self.center_vertically = true;
self
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_page_setup_default() {
let setup = PageSetup::new();
assert_eq!(setup.paper_size, PaperSize::Letter);
assert_eq!(setup.orientation, Orientation::Portrait);
assert_eq!(setup.scale, 100);
}
#[test]
fn test_page_setup_builder() {
let setup = PageSetup::new()
.with_paper_size(PaperSize::A4)
.with_orientation(Orientation::Landscape)
.with_scale(80)
.print_gridlines()
.center_on_page();
assert_eq!(setup.paper_size, PaperSize::A4);
assert_eq!(setup.orientation, Orientation::Landscape);
assert_eq!(setup.scale, 80);
assert!(setup.print_gridlines);
assert!(setup.center_horizontally);
}
#[test]
fn test_margins() {
let margins = PageMargins::narrow();
assert_eq!(margins.left, 0.25);
assert_eq!(margins.right, 0.25);
}
#[test]
fn test_header_footer_section() {
let section = HeaderFooterSection::new()
.with_left("Left text")
.with_center(format!(
"Page {} of {}",
codes::PAGE_NUMBER,
codes::TOTAL_PAGES
))
.with_right(codes::DATE);
let s = section.to_string();
assert!(s.contains("&L"));
assert!(s.contains("&P"));
assert!(s.contains("&D"));
}
#[test]
fn test_paper_size_code() {
assert_eq!(PaperSize::Letter.code(), 1);
assert_eq!(PaperSize::A4.code(), 9);
}
}
#[cfg(test)]
mod coverage_tests {
use super::*;
#[test]
fn paper_size_code_roundtrip() {
for size in [
PaperSize::Letter,
PaperSize::Legal,
PaperSize::A3,
PaperSize::A4,
PaperSize::A5,
PaperSize::Tabloid,
] {
let code = size.code();
assert_eq!(PaperSize::from_code(code), size);
}
let _ = PaperSize::from_code(9999);
}
#[test]
fn page_margins_presets() {
let u = PageMargins::uniform(1.0);
assert_eq!(u.left, 1.0);
assert_eq!(u.right, 1.0);
let _ = PageMargins::narrow();
let _ = PageMargins::wide();
}
#[test]
fn header_footer_sections() {
let s = HeaderFooterSection::new()
.with_left("L")
.with_center("C")
.with_right("R");
assert_eq!(s.left.as_deref(), Some("L"));
assert_eq!(s.center.as_deref(), Some("C"));
assert_eq!(s.right.as_deref(), Some("R"));
let parsed = HeaderFooterSection::parse_encoded("&LLeft&CCenter&RRight");
assert_eq!(parsed.left.as_deref(), Some("Left"));
assert_eq!(parsed.center.as_deref(), Some("Center"));
assert_eq!(parsed.right.as_deref(), Some("Right"));
let hf = HeaderFooter::new()
.with_header(HeaderFooterSection::new().with_center("Title"))
.with_footer(HeaderFooterSection::new().with_center("Page &P"));
assert!(hf.odd_header.is_some() && hf.odd_footer.is_some());
assert!(codes::font_size(12).contains("12"));
assert!(codes::font_name("Arial").contains("Arial"));
}
#[test]
fn print_titles() {
let t = PrintTitles::default().with_rows("1:1").with_cols("A:A");
assert_eq!(t.rows.as_deref(), Some("1:1"));
assert_eq!(t.cols.as_deref(), Some("A:A"));
}
#[test]
fn page_setup_builders() {
let ps = PageSetup::new()
.with_paper_size(PaperSize::A4)
.with_orientation(Orientation::Landscape)
.with_scale(90)
.with_margins(PageMargins::narrow())
.with_print_area("A1:D20")
.print_gridlines()
.center_on_page();
assert_eq!(ps.orientation, Orientation::Landscape);
assert_eq!(ps.scale, 90);
assert_eq!(ps.print_area.as_deref(), Some("A1:D20"));
let fit = PageSetup::new().fit_to_page().fit_to_width(2);
assert!(fit.fit_to_width.is_some() || fit.fit_to_height.is_some());
}
}