papermint 0.3.0

High-performance, type-safe thermal receipt printing for Rust, Node.js & Mobile
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
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
//! Fluent builder for composing printable receipts.

use crate::charset::InternationalCharset;
use crate::codepage::CodePage;
use crate::command::{
    Alignment, BarcodeData, BarcodeSystem, Command, CutMode, DrawerPin, FontFamily,
    HeatingParameters, ImageData, PrintDensity, QrCorrectionLevel, QrData, UnderlineMode,
};
use crate::layout::column::{
    PaperWidth, TableColumn, format_table_row, format_three_column, format_two_column,
};
use crate::tax::ZatcaInvoice;

/// A fluent receipt document builder that generates a [`Vec<Command>`].
///
/// # Example
///
/// ```rust
/// use papermint::{Receipt, PaperWidth, Alignment};
///
/// let receipt = Receipt::new(PaperWidth::Mm80)
///     .init()
///     .center()
///     .bold(true)
///     .text_ln("MINT BISTRO")
///     .bold(false)
///     .text_ln("123 Main Street")
///     .divider('-')
///     .two_column("Double Cheeseburger", "$12.50")
///     .two_column("Large Truffle Fries", "$5.50")
///     .divider('=')
///     .bold(true)
///     .two_column("TOTAL", "$18.00")
///     .bold(false)
///     .feed(2)
///     .center()
///     .qr("https://example.com/receipt/1042")
///     .feed(3)
///     .cut_full();
///
/// assert!(!receipt.commands().is_empty());
/// ```
#[derive(Debug, Clone, PartialEq)]
pub struct Receipt {
    paper_width: PaperWidth,
    commands: Vec<Command>,
    active_columns: Option<Vec<TableColumn>>,
}

impl Default for Receipt {
    fn default() -> Self {
        Self::new(PaperWidth::Mm80)
    }
}

impl Receipt {
    /// Creates a new empty [`Receipt`] configured with the specified [`PaperWidth`].
    #[must_use]
    pub fn new(paper_width: PaperWidth) -> Self {
        Self {
            paper_width,
            commands: Vec::with_capacity(32),
            active_columns: None,
        }
    }

    /// Returns the configured [`PaperWidth`].
    #[must_use]
    pub const fn paper_width(&self) -> PaperWidth {
        self.paper_width
    }

    /// Returns the character column width for this receipt.
    #[must_use]
    pub const fn columns(&self) -> usize {
        self.paper_width.columns()
    }

    /// Returns a reference to the sequence of accumulated [`Command`]s.
    #[must_use]
    pub fn commands(&self) -> &[Command] {
        &self.commands
    }

    /// Consumes the builder and returns the underlying [`Vec<Command>`].
    #[must_use]
    pub fn into_commands(self) -> Vec<Command> {
        self.commands
    }

    /// Resets the printer hardware to default state.
    #[must_use]
    pub fn init(mut self) -> Self {
        self.commands.push(Command::Init);
        self
    }

    /// Appends raw text without a trailing newline.
    #[must_use]
    pub fn text(mut self, text: impl Into<String>) -> Self {
        self.commands.push(Command::Text(text.into()));
        self
    }

    /// Appends text followed by a newline (`\n`).
    #[must_use]
    pub fn text_ln(mut self, text: impl Into<String>) -> Self {
        let mut s = text.into();
        s.push('\n');
        self.commands.push(Command::Text(s));
        self
    }

    /// Feeds paper by the specified number of lines.
    #[must_use]
    pub fn feed(mut self, lines: u8) -> Self {
        self.commands.push(Command::Feed(lines));
        self
    }

    /// Feeds paper by a single line.
    #[must_use]
    pub fn feed_ln(self) -> Self {
        self.feed(1)
    }

    /// Sets the text alignment.
    #[must_use]
    pub fn align(mut self, alignment: Alignment) -> Self {
        self.commands.push(Command::Align(alignment));
        self
    }

    /// Convenience for `.align(Alignment::Left)`.
    #[must_use]
    pub fn left(self) -> Self {
        self.align(Alignment::Left)
    }

    /// Convenience for `.align(Alignment::Center)`.
    #[must_use]
    pub fn center(self) -> Self {
        self.align(Alignment::Center)
    }

    /// Convenience for `.align(Alignment::Right)`.
    #[must_use]
    pub fn right(self) -> Self {
        self.align(Alignment::Right)
    }

    /// Enables or disables bold text emphasis.
    #[must_use]
    pub fn bold(mut self, enable: bool) -> Self {
        self.commands.push(Command::Bold(enable));
        self
    }

    /// Sets the underline style.
    #[must_use]
    pub fn underline(mut self, mode: UnderlineMode) -> Self {
        self.commands.push(Command::Underline(mode));
        self
    }

    /// Enables single-line underline.
    #[must_use]
    pub fn underline_on(self) -> Self {
        self.underline(UnderlineMode::Single)
    }

    /// Disables underline.
    #[must_use]
    pub fn underline_off(self) -> Self {
        self.underline(UnderlineMode::Off)
    }

    /// Enables or disables inverse (white-on-black) printing.
    #[must_use]
    pub fn invert(mut self, enable: bool) -> Self {
        self.commands.push(Command::Invert(enable));
        self
    }

    /// Enables or disables double-height characters.
    #[must_use]
    pub fn double_height(mut self, enable: bool) -> Self {
        self.commands.push(Command::DoubleHeight(enable));
        self
    }

    /// Enables or disables double-width characters.
    #[must_use]
    pub fn double_width(mut self, enable: bool) -> Self {
        self.commands.push(Command::DoubleWidth(enable));
        self
    }

    /// Convenience to set both double height and double width.
    #[must_use]
    pub fn double_size(self, enable: bool) -> Self {
        self.double_height(enable).double_width(enable)
    }

    /// Selects the font family (e.g. Font A or Font B).
    #[must_use]
    pub fn font(mut self, font: FontFamily) -> Self {
        self.commands.push(Command::Font(font));
        self
    }

    /// Prints a full horizontal divider rule spanning the entire paper width.
    #[must_use]
    pub fn divider(self, ch: char) -> Self {
        let cols = self.columns();
        let rule: String = std::iter::repeat_n(ch, cols).collect();
        self.text_ln(rule)
    }

    /// Prints a double-line horizontal divider rule (`================`).
    #[must_use]
    pub fn divider_double(self) -> Self {
        self.divider('=')
    }

    /// Prints a dotted horizontal divider rule (`................`).
    #[must_use]
    pub fn divider_dotted(self) -> Self {
        self.divider('.')
    }

    /// Prints a dashed horizontal divider rule (`- - - - - - - - `).
    #[must_use]
    pub fn divider_dashed(self) -> Self {
        self.divider_pattern("- ")
    }

    /// Prints a repeating pattern horizontal divider rule across the entire paper width.
    #[must_use]
    pub fn divider_pattern(self, pattern: &str) -> Self {
        if pattern.is_empty() {
            return self;
        }
        let cols = self.columns();
        let pat_width = crate::layout::column::str_display_width(pattern);
        if pat_width == 0 {
            return self;
        }
        let mut result = String::with_capacity(cols + pattern.len());
        while crate::layout::column::str_display_width(&result) + pat_width <= cols {
            result.push_str(pattern);
        }
        let cur_w = crate::layout::column::str_display_width(&result);
        if cur_w < cols {
            result.push_str(&" ".repeat(cols - cur_w));
        }
        self.text_ln(result)
    }

    /// Prints a 2-column row with left text aligned left and right text aligned right.
    #[must_use]
    pub fn two_column(self, left: impl AsRef<str>, right: impl AsRef<str>) -> Self {
        let cols = self.columns();
        let formatted = format_two_column(left.as_ref(), right.as_ref(), cols);
        self.text_ln(formatted)
    }

    /// Prints a 3-column row (left, center, right).
    #[must_use]
    pub fn three_column(
        self,
        left: impl AsRef<str>,
        center: impl AsRef<str>,
        right: impl AsRef<str>,
    ) -> Self {
        let cols = self.columns();
        let formatted = format_three_column(left.as_ref(), center.as_ref(), right.as_ref(), cols);
        self.text_ln(formatted)
    }

    /// Prints an N-column table row with automatic word-wrapping and synchronized vertical row height.
    ///
    /// Long cell text wraps within its allocated column width while preserving
    /// strict columnar alignment across adjacent columns on the receipt.
    #[must_use]
    pub fn table_row<S: AsRef<str>>(mut self, cells: &[S], columns: &[TableColumn]) -> Self {
        let str_cells: Vec<&str> = cells.iter().map(|s| s.as_ref()).collect();
        let lines = format_table_row(&str_cells, columns, self.columns());
        for line in lines {
            self = self.text_ln(line);
        }
        self
    }

    /// Prints multiple N-column table rows.
    #[must_use]
    pub fn table<S: AsRef<str>>(mut self, columns: &[TableColumn], rows: &[&[S]]) -> Self {
        for row in rows {
            self = self.table_row(row, columns);
        }
        self
    }

    /// Configures the active table columns for subsequent calls to [`.row(...)`](Self::row)
    /// or [`.header(...)`](Self::header).
    #[must_use]
    pub fn set_columns(mut self, columns: &[TableColumn]) -> Self {
        self.active_columns = Some(columns.to_vec());
        self
    }

    /// Configures the active table columns and prints a bold table header row.
    ///
    /// Subsequent calls to [`.row(...)`](Self::row) will automatically format against
    /// these columns without needing to re-specify the column slice on every row.
    #[must_use]
    pub fn table_header<S: AsRef<str>>(mut self, headers: &[S], columns: &[TableColumn]) -> Self {
        self.active_columns = Some(columns.to_vec());
        self = self.bold(true).table_row(headers, columns).bold(false);
        self
    }

    /// Prints a bold header row using the currently configured active columns.
    #[must_use]
    pub fn header<S: AsRef<str>>(mut self, headers: &[S]) -> Self {
        self = self.bold(true).row(headers).bold(false);
        self
    }

    /// Returns a slice of the active table columns, if configured.
    #[must_use]
    pub fn active_columns(&self) -> Option<&[TableColumn]> {
        self.active_columns.as_deref()
    }

    /// Clears any active table columns configured on this receipt builder.
    #[must_use]
    pub fn clear_columns(mut self) -> Self {
        self.active_columns = None;
        self
    }

    /// Prints an N-column table row using the active table columns configured via
    /// [`.table_header(...)`](Self::table_header) or [`.set_columns(...)`](Self::set_columns).
    ///
    /// Long cell text wraps automatically at word boundaries while synchronizing
    /// multi-line heights across adjacent columns.
    #[must_use]
    pub fn row<S: AsRef<str>>(mut self, cells: &[S]) -> Self {
        if let Some(ref cols) = self.active_columns {
            let str_cells: Vec<&str> = cells.iter().map(|s| s.as_ref()).collect();
            let lines = format_table_row(&str_cells, cols, self.columns());
            for line in lines {
                self = self.text_ln(line);
            }
            self
        } else {
            let joined = cells
                .iter()
                .map(|s| s.as_ref())
                .collect::<Vec<_>>()
                .join("  ");
            self.text_ln(joined)
        }
    }

    /// Prints a barcode with full custom parameters.
    #[must_use]
    pub fn barcode(mut self, barcode: BarcodeData) -> Self {
        self.commands.push(Command::Barcode(barcode));
        self
    }

    /// Convenience to print a Code128 barcode with default dimensions (width 2, height 64).
    #[must_use]
    pub fn barcode_128(self, data: impl Into<String>) -> Self {
        self.barcode(BarcodeData {
            system: BarcodeSystem::Code128,
            data: data.into(),
            width: 2,
            height: 64,
        })
    }

    /// Prints a QR code with full custom parameters.
    #[must_use]
    pub fn qr_code(mut self, qr: QrData) -> Self {
        self.commands.push(Command::QrCode(qr));
        self
    }

    /// Convenience to print a QR code with sensible defaults (Model 2, cell size 4, M correction).
    #[must_use]
    pub fn qr(self, data: impl Into<String>) -> Self {
        self.qr_code(QrData {
            data: data.into(),
            model: 2,
            cell_size: 4,
            correction: QrCorrectionLevel::M,
        })
    }

    /// Appends a ZATCA (Saudi Arabia) & FTA (UAE) compliant E-Invoicing QR code from the given invoice metadata.
    ///
    /// Encodes invoice fields into standard TLV (Tag-Length-Value) bytes and Base64 as mandated
    /// by Middle Eastern tax authorities.
    #[must_use]
    pub fn zatca_qr(self, invoice: &ZatcaInvoice) -> Self {
        let payload = invoice.to_qr_base64();
        self.qr(payload)
    }

    /// Prints a monochrome raster image.
    #[must_use]
    pub fn image(mut self, image: ImageData) -> Self {
        self.commands.push(Command::Image(image));
        self
    }

    /// Loads an image file from disk, dithers it with Floyd-Steinberg error diffusion,
    /// auto-downscales to fit the paper width if necessary, and appends it to the receipt.
    ///
    /// # Errors
    ///
    /// Returns [`crate::error::PapermintError::Image`] if the file cannot be read or decoded.
    #[cfg(feature = "image")]
    pub fn image_from_path(self, path: impl AsRef<std::path::Path>) -> crate::error::Result<Self> {
        let max_w = self.paper_width.dots();
        self.image_from_path_with_options(
            path,
            Some(max_w),
            crate::image::DitherMode::FloydSteinberg,
        )
    }

    /// Loads an image file from disk with custom `max_width` and [`crate::image::DitherMode`].
    ///
    /// # Errors
    ///
    /// Returns [`crate::error::PapermintError::Image`] if the file cannot be read or decoded.
    #[cfg(feature = "image")]
    pub fn image_from_path_with_options(
        self,
        path: impl AsRef<std::path::Path>,
        max_width: Option<u32>,
        mode: crate::image::DitherMode,
    ) -> crate::error::Result<Self> {
        let img = ImageData::from_path(path, max_width, mode)?;
        Ok(self.image(img))
    }

    /// Decodes an image from in-memory bytes (PNG, JPEG, etc.), dithers it with Floyd-Steinberg error diffusion,
    /// auto-downscales to fit the paper width if necessary, and appends it to the receipt.
    ///
    /// # Errors
    ///
    /// Returns [`crate::error::PapermintError::Image`] if decoding fails.
    #[cfg(feature = "image")]
    pub fn image_from_bytes(self, bytes: &[u8]) -> crate::error::Result<Self> {
        let max_w = self.paper_width.dots();
        self.image_from_bytes_with_options(
            bytes,
            Some(max_w),
            crate::image::DitherMode::FloydSteinberg,
        )
    }

    /// Decodes an image from in-memory bytes with custom `max_width` and [`crate::image::DitherMode`].
    ///
    /// # Errors
    ///
    /// Returns [`crate::error::PapermintError::Image`] if decoding fails.
    #[cfg(feature = "image")]
    pub fn image_from_bytes_with_options(
        self,
        bytes: &[u8],
        max_width: Option<u32>,
        mode: crate::image::DitherMode,
    ) -> crate::error::Result<Self> {
        let img = ImageData::from_bytes(bytes, max_width, mode)?;
        Ok(self.image(img))
    }

    /// Cuts the paper with the specified [`CutMode`].
    #[must_use]
    pub fn cut(mut self, mode: CutMode) -> Self {
        self.commands.push(Command::Cut(mode));
        self
    }

    /// Full paper cut.
    #[must_use]
    pub fn cut_full(self) -> Self {
        self.cut(CutMode::Full)
    }

    /// Partial paper cut (leaves a perforated tag).
    #[must_use]
    pub fn cut_partial(self) -> Self {
        self.cut(CutMode::Partial)
    }

    /// Triggers the cash drawer kick on the specified pin.
    #[must_use]
    pub fn drawer_kick(mut self, pin: DrawerPin) -> Self {
        self.commands.push(Command::DrawerKick(pin));
        self
    }

    /// Opens the cash drawer on Pin 2 (standard RJ12 cash drawer port).
    #[must_use]
    pub fn open_drawer(self) -> Self {
        self.drawer_kick(DrawerPin::Pin2)
    }

    /// Sounds the printer internal buzzer.
    #[must_use]
    pub fn beep(mut self, count: u8, duration: u8) -> Self {
        self.commands.push(Command::Beep { count, duration });
        self
    }

    /// Sets line spacing in vertical motion dots, or resets to default if `None`.
    #[must_use]
    pub fn line_spacing(mut self, spacing: Option<u8>) -> Self {
        self.commands.push(Command::LineSpacing(spacing));
        self
    }

    /// Resets line spacing to the printer hardware default (typically 1/6 inch).
    #[must_use]
    pub fn default_line_spacing(self) -> Self {
        self.line_spacing(None)
    }

    /// Enables or disables upside-down (180° rotated) printing.
    #[must_use]
    pub fn upside_down(mut self, enable: bool) -> Self {
        self.commands.push(Command::UpsideDown(enable));
        self
    }

    /// Selects character code page table (e.g. [`CodePage::Wpc1252`], [`CodePage::Pc850`]).
    /// Also accepts raw `u8` index via `Into<CodePage>` for custom vendor code pages.
    #[must_use]
    pub fn code_page(mut self, page: impl Into<CodePage>) -> Self {
        self.commands.push(Command::CodePage(page.into()));
        self
    }

    /// Selects an international character set (e.g. [`InternationalCharset::Uk`], [`InternationalCharset::France`]).
    ///
    /// Modifies 12 standard ASCII punctuation positions (`#`, `$`, `@`, `[`, `\`, `]`, `^`, `` ` ``, `{`, `|`, `}`, `~`)
    /// to provide localized national currency and accented character symbols.
    #[must_use]
    pub fn international_charset(mut self, charset: impl Into<InternationalCharset>) -> Self {
        self.commands
            .push(Command::InternationalCharset(charset.into()));
        self
    }

    /// Convenience for `.international_charset(InternationalCharset::Usa)`.
    #[must_use]
    pub fn charset_usa(self) -> Self {
        self.international_charset(InternationalCharset::Usa)
    }

    /// Convenience for `.international_charset(InternationalCharset::Uk)`.
    #[must_use]
    pub fn charset_uk(self) -> Self {
        self.international_charset(InternationalCharset::Uk)
    }

    /// Convenience for `.international_charset(InternationalCharset::France)`.
    #[must_use]
    pub fn charset_france(self) -> Self {
        self.international_charset(InternationalCharset::France)
    }

    /// Convenience for `.international_charset(InternationalCharset::Germany)`.
    #[must_use]
    pub fn charset_germany(self) -> Self {
        self.international_charset(InternationalCharset::Germany)
    }

    /// Convenience for `.international_charset(InternationalCharset::SpainI)`.
    #[must_use]
    pub fn charset_spain(self) -> Self {
        self.international_charset(InternationalCharset::SpainI)
    }

    /// Convenience for `.international_charset(InternationalCharset::Italy)`.
    #[must_use]
    pub fn charset_italy(self) -> Self {
        self.international_charset(InternationalCharset::Italy)
    }

    /// Convenience for `.international_charset(InternationalCharset::Japan)`.
    #[must_use]
    pub fn charset_japan(self) -> Self {
        self.international_charset(InternationalCharset::Japan)
    }

    /// Convenience for `.international_charset(InternationalCharset::Arabia)`.
    #[must_use]
    pub fn charset_arabia(self) -> Self {
        self.international_charset(InternationalCharset::Arabia)
    }

    /// Sets the thermal printhead dot density.
    #[must_use]
    pub fn print_density(mut self, density: PrintDensity) -> Self {
        self.commands.push(Command::PrintDensity(density));
        self
    }

    /// Convenience for setting density to [`PrintDensity::Light`].
    #[must_use]
    pub fn density_light(self) -> Self {
        self.print_density(PrintDensity::Light)
    }

    /// Convenience for setting density to [`PrintDensity::Normal`].
    #[must_use]
    pub fn density_normal(self) -> Self {
        self.print_density(PrintDensity::Normal)
    }

    /// Convenience for setting density to [`PrintDensity::Dark`].
    #[must_use]
    pub fn density_dark(self) -> Self {
        self.print_density(PrintDensity::Dark)
    }

    /// Convenience for setting density to [`PrintDensity::HighContrast`].
    #[must_use]
    pub fn density_high_contrast(self) -> Self {
        self.print_density(PrintDensity::HighContrast)
    }

    /// Sets the thermal printhead heating strobe and interval parameters.
    #[must_use]
    pub fn heating_parameters(mut self, params: HeatingParameters) -> Self {
        self.commands.push(Command::HeatingParameters(params));
        self
    }

    /// Appends raw bytes directly to the printer command stream.
    #[must_use]
    pub fn raw(mut self, bytes: impl Into<Vec<u8>>) -> Self {
        self.commands.push(Command::Raw(bytes.into()));
        self
    }

    /// Renders a virtual SVG vector graphic preview of the receipt.
    ///
    /// Simulates realistic thermal receipt paper with monospace font styling,
    /// column alignments, vector barcodes, and jagged paper cut edges.
    #[must_use]
    pub fn render_svg(&self) -> String {
        crate::layout::preview::render_svg(self)
    }

    /// Renders a responsive, styled HTML snippet preview of the receipt.
    ///
    /// Ready for embedding in React, Next.js, Vue, or web checkout screens.
    #[must_use]
    pub fn render_html(&self) -> String {
        crate::layout::preview::render_html(self)
    }
}