qrcode-pdf 2.0.0

Pure Rust PDF rendering backend for qrcode-rs.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
//! PDF rendering support.
//!
//! # Example
//!
//! ```
//! use qrcode_core::Color as ModuleColor;
//! use qrcode_pdf::Color;
//! use qrcode_render::Renderer;
//!
//! let modules = [ModuleColor::Dark, ModuleColor::Light, ModuleColor::Light, ModuleColor::Dark];
//! let pdf_data = Renderer::<Color>::new(&modules, 2, 1).build();
//! println!("PDF size: {} bytes", pdf_data.len());
//! ```

#![cfg_attr(not(feature = "std"), no_std)]

#[cfg(not(feature = "std"))]
extern crate alloc;

#[cfg(not(feature = "std"))]
#[allow(unused_imports)]
use alloc::{
    borrow::ToOwned,
    format,
    string::{String, ToString},
    vec,
    vec::Vec,
};

use core::fmt::Write;

use qrcode_core::Color as ModuleColor;
use qrcode_render::colors::{CmykColor as SharedCmykColor, ColorSpace, RgbColor};
use qrcode_render::{Canvas as RenderCanvas, Pixel, StyledPixel};

/// A PDF color (`[R, G, B]`).
///
/// Each value must be in the range of 0.0 to 1.0.
#[derive(Copy, Clone, Default, PartialEq, PartialOrd)]
pub struct Color(pub [f64; 3]);

/// A PDF CMYK color (`[C, M, Y, K]`).
///
/// Each value is expected to be in the range of 0.0 to 1.0. Values converted
/// from the shared render color space are clamped there before rendering.
#[derive(Copy, Clone, Default, PartialEq, PartialOrd)]
pub struct CmykColor(pub [f64; 4]);

impl Pixel for Color {
    type Canvas = Canvas;
    type Image = Vec<u8>;

    fn default_color(color: ModuleColor) -> Self {
        Self(color.select(Default::default(), [1.0; 3]))
    }
}

impl StyledPixel for Color {
    fn from_hex(hex: &str) -> Self {
        let (r, g, b) = qrcode_render::colors::hex_to_rgb(hex).unwrap_or((0, 0, 0));
        Self([r as f64 / 255.0, g as f64 / 255.0, b as f64 / 255.0])
    }
}

impl From<RgbColor> for Color {
    fn from(color: RgbColor) -> Self {
        Self(color.to_array())
    }
}

impl Pixel for CmykColor {
    type Canvas = CmykCanvas;
    type Image = Vec<u8>;

    fn default_color(color: ModuleColor) -> Self {
        Self(color.select([0.0, 0.0, 0.0, 1.0], [0.0, 0.0, 0.0, 0.0]))
    }
}

impl StyledPixel for CmykColor {
    fn from_hex(hex: &str) -> Self {
        let (r, g, b) = qrcode_render::colors::hex_to_rgb(hex).unwrap_or((0, 0, 0));
        SharedCmykColor::from_rgb(RgbColor::new(r, g, b)).into()
    }
}

impl From<SharedCmykColor> for CmykColor {
    fn from(color: SharedCmykColor) -> Self {
        Self(color.to_array())
    }
}

#[doc(hidden)]
pub struct Canvas {
    stream: String,
    width: u32,
    height: u32,
    fg_r: f64,
    fg_g: f64,
    fg_b: f64,
    pending_left: u32,
    pending_bottom: u32,
    pending_width: u32,
    pending_height: u32,
    has_pending: bool,
}

#[doc(hidden)]
pub struct CmykCanvas {
    stream: String,
    width: u32,
    height: u32,
    fg_c: f64,
    fg_m: f64,
    fg_y: f64,
    fg_k: f64,
    pending_left: u32,
    pending_bottom: u32,
    pending_width: u32,
    pending_height: u32,
    has_pending: bool,
}

impl Canvas {
    fn flush_pending(&mut self) {
        if self.has_pending {
            writeln!(
                self.stream,
                "{} {} {} rg {} {} {} {} re f",
                self.fg_r,
                self.fg_g,
                self.fg_b,
                self.pending_left,
                self.pending_bottom,
                self.pending_width,
                self.pending_height
            )
            .unwrap();
            self.has_pending = false;
        }
    }
}

impl RenderCanvas for Canvas {
    type Pixel = Color;
    type Image = Vec<u8>;

    fn new(width: u32, height: u32, dark_pixel: Color, _light_pixel: Color) -> Self {
        Canvas {
            stream: String::new(),
            width,
            height,
            fg_r: dark_pixel.0[0],
            fg_g: dark_pixel.0[1],
            fg_b: dark_pixel.0[2],
            pending_left: 0,
            pending_bottom: 0,
            pending_width: 0,
            pending_height: 0,
            has_pending: false,
        }
    }

    fn draw_dark_pixel(&mut self, x: u32, y: u32) {
        self.draw_dark_rect(x, y, 1, 1);
    }

    fn draw_dark_rect(&mut self, left: u32, top: u32, width: u32, height: u32) {
        let bottom = self.height - top - height;
        if self.has_pending
            && bottom == self.pending_bottom
            && height == self.pending_height
            && left == self.pending_left + self.pending_width
        {
            self.pending_width += width;
        } else {
            self.flush_pending();
            self.pending_left = left;
            self.pending_bottom = bottom;
            self.pending_width = width;
            self.pending_height = height;
            self.has_pending = true;
        }
    }

    fn into_image(mut self) -> Vec<u8> {
        self.flush_pending();

        let w = self.width;
        let h = self.height;
        let stream_content = &self.stream;
        let stream_len = stream_content.len();

        let mut obj_offsets = Vec::with_capacity(5);
        let mut pos: usize = 0;

        // Header
        let header = "%PDF-1.4\n";
        pos += header.len();

        // Object 1: Catalog
        obj_offsets.push(pos);
        let obj1 = "1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n";
        pos += obj1.len();

        // Object 2: Pages
        obj_offsets.push(pos);
        let obj2 = "2 0 obj\n<< /Type /Pages /Kids [3 0 R] /Count 1 >>\nendobj\n";
        pos += obj2.len();

        // Object 3: Page
        obj_offsets.push(pos);
        let mut obj3 = String::new();
        write!(
            &mut obj3,
            "3 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 {w} {h}] /Contents 4 0 R /Resources << >> >>\nendobj\n",
        )
        .unwrap();
        pos += obj3.len();

        // Object 4: Content stream
        obj_offsets.push(pos);
        let mut obj4_head = String::new();
        write!(&mut obj4_head, "4 0 obj\n<< /Length {stream_len} >>\nstream\n").unwrap();
        pos += obj4_head.len();
        pos += stream_len;
        let obj4_tail = "\nendstream\nendobj\n";
        pos += obj4_tail.len();

        // Cross-reference table
        let xref_pos = pos;
        let mut xref = String::new();
        xref.push_str("xref\n0 5\n");
        xref.push_str("0000000000 65535 f \n");
        for &off in &obj_offsets {
            writeln!(&mut xref, "{off:010} 00000 n ").unwrap();
        }

        // Trailer
        let mut trailer = String::new();
        write!(&mut trailer, "trailer\n<< /Size 5 /Root 1 0 R >>\nstartxref\n{xref_pos}\n%%EOF\n",).unwrap();

        // Assemble PDF
        let total = pos + xref.len() + trailer.len();
        let mut pdf = Vec::with_capacity(total);
        pdf.extend_from_slice(header.as_bytes());
        pdf.extend_from_slice(obj1.as_bytes());
        pdf.extend_from_slice(obj2.as_bytes());
        pdf.extend_from_slice(obj3.as_bytes());
        pdf.extend_from_slice(obj4_head.as_bytes());
        pdf.extend_from_slice(stream_content.as_bytes());
        pdf.extend_from_slice(obj4_tail.as_bytes());
        pdf.extend_from_slice(xref.as_bytes());
        pdf.extend_from_slice(trailer.as_bytes());
        pdf
    }
}

impl CmykCanvas {
    fn flush_pending(&mut self) {
        if self.has_pending {
            writeln!(
                self.stream,
                "{} {} {} {} k {} {} {} {} re f",
                self.fg_c,
                self.fg_m,
                self.fg_y,
                self.fg_k,
                self.pending_left,
                self.pending_bottom,
                self.pending_width,
                self.pending_height
            )
            .unwrap();
            self.has_pending = false;
        }
    }
}

impl RenderCanvas for CmykCanvas {
    type Pixel = CmykColor;
    type Image = Vec<u8>;

    fn new(width: u32, height: u32, dark_pixel: CmykColor, _light_pixel: CmykColor) -> Self {
        CmykCanvas {
            stream: String::new(),
            width,
            height,
            fg_c: dark_pixel.0[0],
            fg_m: dark_pixel.0[1],
            fg_y: dark_pixel.0[2],
            fg_k: dark_pixel.0[3],
            pending_left: 0,
            pending_bottom: 0,
            pending_width: 0,
            pending_height: 0,
            has_pending: false,
        }
    }

    fn draw_dark_pixel(&mut self, x: u32, y: u32) {
        self.draw_dark_rect(x, y, 1, 1);
    }

    fn draw_dark_rect(&mut self, left: u32, top: u32, width: u32, height: u32) {
        let bottom = self.height - top - height;
        if self.has_pending
            && bottom == self.pending_bottom
            && height == self.pending_height
            && left == self.pending_left + self.pending_width
        {
            self.pending_width += width;
        } else {
            self.flush_pending();
            self.pending_left = left;
            self.pending_bottom = bottom;
            self.pending_width = width;
            self.pending_height = height;
            self.has_pending = true;
        }
    }

    fn into_image(mut self) -> Vec<u8> {
        self.flush_pending();

        let w = self.width;
        let h = self.height;
        let stream_content = &self.stream;
        let stream_len = stream_content.len();

        let mut obj_offsets = Vec::with_capacity(5);
        let mut pos: usize = 0;

        let header = "%PDF-1.4\n";
        pos += header.len();

        obj_offsets.push(pos);
        let obj1 = "1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n";
        pos += obj1.len();

        obj_offsets.push(pos);
        let obj2 = "2 0 obj\n<< /Type /Pages /Kids [3 0 R] /Count 1 >>\nendobj\n";
        pos += obj2.len();

        obj_offsets.push(pos);
        let mut obj3 = String::new();
        write!(
            &mut obj3,
            "3 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 {w} {h}] /Contents 4 0 R /Resources << >> >>\nendobj\n",
        )
        .unwrap();
        pos += obj3.len();

        obj_offsets.push(pos);
        let mut obj4_head = String::new();
        write!(&mut obj4_head, "4 0 obj\n<< /Length {stream_len} >>\nstream\n").unwrap();
        pos += obj4_head.len();
        pos += stream_len;
        let obj4_tail = "\nendstream\nendobj\n";
        pos += obj4_tail.len();

        let xref_pos = pos;
        let mut xref = String::new();
        xref.push_str("xref\n0 5\n");
        xref.push_str("0000000000 65535 f \n");
        for &off in &obj_offsets {
            writeln!(&mut xref, "{off:010} 00000 n ").unwrap();
        }

        let mut trailer = String::new();
        write!(&mut trailer, "trailer\n<< /Size 5 /Root 1 0 R >>\nstartxref\n{xref_pos}\n%%EOF\n",).unwrap();

        let total = pos + xref.len() + trailer.len();
        let mut pdf = Vec::with_capacity(total);
        pdf.extend_from_slice(header.as_bytes());
        pdf.extend_from_slice(obj1.as_bytes());
        pdf.extend_from_slice(obj2.as_bytes());
        pdf.extend_from_slice(obj3.as_bytes());
        pdf.extend_from_slice(obj4_head.as_bytes());
        pdf.extend_from_slice(stream_content.as_bytes());
        pdf.extend_from_slice(obj4_tail.as_bytes());
        pdf.extend_from_slice(xref.as_bytes());
        pdf.extend_from_slice(trailer.as_bytes());
        pdf
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use qrcode_core::Color as ModuleColor;
    use qrcode_render::{Renderer, StyledPixel};

    #[test]
    fn test_pdf_header() {
        let colors = vec![ModuleColor::Dark; 4];
        let pdf: Vec<u8> = Renderer::<Color>::new(&colors, 2, 0).module_dimensions(1, 1).build();
        assert!(pdf.starts_with(b"%PDF-1.4\n"));
        assert!(pdf.ends_with(b"%%EOF\n"));
    }

    #[test]
    fn test_pdf_contains_rect() {
        let colors = vec![ModuleColor::Dark; 4];
        let pdf: Vec<u8> = Renderer::<Color>::new(&colors, 2, 0).module_dimensions(1, 1).build();
        let content = String::from_utf8_lossy(&pdf);
        assert!(content.contains(" re f"));
        assert!(content.contains(" rg"));
    }

    #[test]
    fn test_pdf_xref() {
        let colors = vec![ModuleColor::Light, ModuleColor::Dark, ModuleColor::Dark, ModuleColor::Light];
        let pdf: Vec<u8> = Renderer::<Color>::new(&colors, 2, 1).module_dimensions(1, 1).build();
        let content = String::from_utf8_lossy(&pdf);
        assert!(content.contains("xref"));
        assert!(content.contains("trailer"));
        assert!(content.contains("startxref"));
    }

    #[test]
    fn test_pdf_empty_rects() {
        let colors = vec![ModuleColor::Light; 4];
        let pdf: Vec<u8> = Renderer::<Color>::new(&colors, 2, 0).module_dimensions(1, 1).build();
        // All-light produces no dark rects, but PDF is still valid.
        assert!(pdf.starts_with(b"%PDF-1.4"));
        assert!(pdf.ends_with(b"%%EOF\n"));
    }

    #[test]
    fn test_pdf_color_parses_hex_for_templates() {
        let color = Color::from_hex("#336699");

        assert!((color.0[0] - 0.2).abs() < f64::EPSILON);
        assert!((color.0[1] - 0.4).abs() < f64::EPSILON);
        assert!((color.0[2] - 0.6).abs() < f64::EPSILON);
    }

    #[test]
    fn test_pdf_cmyk_renderer_outputs_native_cmyk_operator() {
        let colors = vec![ModuleColor::Dark, ModuleColor::Light, ModuleColor::Light, ModuleColor::Dark];
        let pdf: Vec<u8> = Renderer::<CmykColor>::new(&colors, 2, 0)
            .dark_color(CmykColor([1.0, 0.0, 0.0, 0.25]))
            .module_dimensions(1, 1)
            .build();
        let content = String::from_utf8_lossy(&pdf);

        assert!(content.contains("1 0 0 0.25 k"));
        assert!(!content.contains(" rg"));
    }
}