Skip to main content

laser_pdf/
utils.rs

1use pdf_writer::Content;
2// use printpdf::*;
3
4// pub fn circle(layer: &PdfLayerReference, pos: [f32; 2], radius: f32) {
5//     let circle = printpdf::utils::calculate_points_for_circle(Pt(radius), Pt(pos[0]), Pt(pos[1]));
6
7//     layer.add_shape(Line {
8//         points: circle,
9//         is_closed: true,
10//         has_fill: true,
11//         has_stroke: false,
12//         is_clipping_path: false,
13//     });
14// }
15
16pub fn line(layer: &mut Content, pos: (f32, f32), width: f32, thickness: f32) {
17    // TODO: mm_to_pt
18    layer
19        .set_line_width(thickness)
20        .move_to(mm_to_pt(pos.0), mm_to_pt(pos.1))
21        .line_to(mm_to_pt(pos.0 + width), mm_to_pt(pos.1))
22        .stroke();
23}
24
25pub fn mm_to_pt(mm: f32) -> f32 {
26    // (mm as f64 * 2.834_646) as f32
27    // (mm as f64 * 72. / 25.4) as f32
28    mm * 72. / 25.4
29}
30
31pub fn pt_to_mm(pt: f32) -> f32 {
32    // (pt as f64 * 0.352_778) as f32
33    pt * 25.4 / 72.
34}
35
36pub fn u32_to_color_and_alpha(color: u32) -> ([f32; 3], f32) {
37    (
38        [
39            ((color & 0xff_00_00_00) >> 24) as f32 / 255.0,
40            ((color & 0x00_ff_00_00) >> 16) as f32 / 255.0,
41            ((color & 0x00_00_ff_00) >> 8) as f32 / 255.0,
42        ],
43        (color & 0x00_00_00_ff) as f32 / 255.0,
44    )
45}
46
47pub fn u32_to_rgb_color_array(color: u32) -> [u8; 3] {
48    [
49        ((color & 0xff_00_00_00) >> 24) as u8,
50        ((color & 0x00_ff_00_00) >> 16) as u8,
51        ((color & 0x00_00_ff_00) >> 8) as u8,
52    ]
53}
54
55pub fn rgb_color_array_to_u32(color: [u8; 3]) -> u32 {
56    ((color[0] as u32) << 24) | ((color[1] as u32) << 16) | ((color[2] as u32) << 8) | 0xFF
57}
58
59pub fn max_optional_size(a: Option<f32>, b: Option<f32>) -> Option<f32> {
60    match (a, b) {
61        (None, None) => None,
62        (None, Some(x)) | (Some(x), None) => Some(x),
63        (Some(a), Some(b)) => Some(a.max(b)),
64    }
65}
66
67pub fn add_optional_size(a: Option<f32>, b: Option<f32>) -> Option<f32> {
68    match (a, b) {
69        (None, None) => None,
70        (None, Some(x)) | (Some(x), None) => Some(x),
71        (Some(a), Some(b)) => Some(a + b),
72    }
73}
74
75pub fn add_optional_size_with_gap(a: Option<f32>, b: Option<f32>, gap: f32) -> Option<f32> {
76    match (a, b) {
77        (None, None) => None,
78        (None, Some(x)) | (Some(x), None) => Some(x),
79        (Some(a), Some(b)) => Some(a + gap + b),
80    }
81}
82
83pub fn set_fill_color(layer: &mut Content, color: u32) {
84    let (color, _) = u32_to_color_and_alpha(color);
85    layer.set_fill_rgb(color[0], color[1], color[2]);
86}
87
88pub fn set_stroke_color(layer: &mut Content, color: u32) {
89    let (color, _) = u32_to_color_and_alpha(color);
90    layer.set_stroke_rgb(color[0], color[1], color[2]);
91}
92
93pub fn scale(scale: f32) -> [f32; 6] {
94    [scale, 0., 0., scale, 0., 0.]
95}