Skip to main content

rust_pdf_box/pd/
rectangle.rs

1use crate::cos::object::{COSArray, COSObject};
2
3/// A rectangle in default user space units (1/72 inch).
4/// Lower-left (x, y) to Upper-right (x, y).
5#[derive(Debug, Clone, Copy, PartialEq)]
6pub struct PDRectangle {
7    pub lower_left_x: f64,
8    pub lower_left_y: f64,
9    pub upper_right_x: f64,
10    pub upper_right_y: f64,
11}
12
13impl PDRectangle {
14    pub const A4: PDRectangle = PDRectangle::new(0.0, 0.0, 595.276, 841.890);
15    pub const A3: PDRectangle = PDRectangle::new(0.0, 0.0, 841.890, 1190.551);
16    pub const A5: PDRectangle = PDRectangle::new(0.0, 0.0, 419.528, 595.276);
17    pub const LETTER: PDRectangle = PDRectangle::new(0.0, 0.0, 612.0, 792.0);
18    pub const LEGAL: PDRectangle = PDRectangle::new(0.0, 0.0, 612.0, 1008.0);
19    pub const TABLOID: PDRectangle = PDRectangle::new(0.0, 0.0, 792.0, 1224.0);
20
21    pub const fn new(llx: f64, lly: f64, urx: f64, ury: f64) -> Self {
22        Self {
23            lower_left_x: llx,
24            lower_left_y: lly,
25            upper_right_x: urx,
26            upper_right_y: ury,
27        }
28    }
29
30    pub fn width(&self) -> f64 {
31        (self.upper_right_x - self.lower_left_x).abs()
32    }
33
34    pub fn height(&self) -> f64 {
35        (self.upper_right_y - self.lower_left_y).abs()
36    }
37
38    pub fn center(&self) -> (f64, f64) {
39        (
40            (self.lower_left_x + self.upper_right_x) / 2.0,
41            (self.lower_left_y + self.upper_right_y) / 2.0,
42        )
43    }
44
45    pub fn to_cos_array(&self) -> COSArray {
46        let mut arr = COSArray::new();
47        arr.push(self.lower_left_x);
48        arr.push(self.lower_left_y);
49        arr.push(self.upper_right_x);
50        arr.push(self.upper_right_y);
51        arr
52    }
53
54    pub fn from_cos_array(arr: &COSArray) -> Option<Self> {
55        if arr.len() < 4 {
56            return None;
57        }
58        let llx = arr.get(0)?.as_float()?;
59        let lly = arr.get(1)?.as_float()?;
60        let urx = arr.get(2)?.as_float()?;
61        let ury = arr.get(3)?.as_float()?;
62        Some(Self::new(llx, lly, urx, ury))
63    }
64}
65
66impl From<PDRectangle> for COSObject {
67    fn from(rect: PDRectangle) -> Self {
68        COSObject::Array(rect.to_cos_array())
69    }
70}