lopdf-table 0.5.0

A composable table drawing library for PDFs built on lopdf
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
//! Core table structures

use crate::Result;
use crate::error::TableError;
use crate::font::FontMetrics;
use crate::style::{CellStyle, RowStyle, TableStyle};
use std::sync::Arc;
use tracing::trace;

/// Image fit mode for cell rendering
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub enum ImageFit {
    /// Scale to fit within cell bounds preserving aspect ratio
    #[default]
    Contain,
}

/// Text overlay drawn on top of a cell image (semi-transparent bar with white text).
#[derive(Debug, Clone)]
pub struct ImageOverlay {
    /// Text to display in the overlay bar
    pub text: String,
    /// Font size for the overlay text (default: 8.0)
    pub font_size: f32,
    /// Height of the semi-transparent background bar (default: 16.0)
    pub bar_height: f32,
    /// Horizontal padding inside the bar (default: 4.0)
    pub padding: f32,
}

impl ImageOverlay {
    /// Create a new overlay with the given text and sensible defaults.
    pub fn new(text: impl Into<String>) -> Self {
        Self {
            text: text.into(),
            font_size: 8.0,
            bar_height: 16.0,
            padding: 4.0,
        }
    }
}

/// Image payload for embedding in a table cell.
///
/// Constructed from raw JPEG or PNG bytes. The image is validated and
/// converted to a PDF XObject stream at construction time. Cheap to
/// clone via internal `Arc`.
#[derive(Clone)]
pub struct CellImage {
    /// Pre-built XObject stream ready for PDF embedding
    pub(crate) xobject: Arc<lopdf::Stream>,
    /// Intrinsic width in pixels
    pub(crate) width_px: u32,
    /// Intrinsic height in pixels
    pub(crate) height_px: u32,
    /// Maximum rendered height in points (caps row height contribution)
    pub(crate) max_render_height_pts: Option<f32>,
    /// Fit mode
    pub(crate) fit: ImageFit,
    /// Optional text overlay drawn on top of the image
    pub(crate) overlay: Option<ImageOverlay>,
}

impl std::fmt::Debug for CellImage {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("CellImage")
            .field("width_px", &self.width_px)
            .field("height_px", &self.height_px)
            .field("max_render_height_pts", &self.max_render_height_pts)
            .field("fit", &self.fit)
            .field("overlay", &self.overlay)
            .finish()
    }
}

impl CellImage {
    /// Create a new image from raw JPEG or PNG bytes.
    ///
    /// Validates the image and pre-builds the PDF XObject stream.
    /// Returns an error if the bytes are not a valid/supported image.
    pub fn new(data: Vec<u8>) -> Result<Self> {
        let stream = lopdf::xobject::image_from(data)
            .map_err(|e| TableError::DrawingError(format!("Invalid image data: {e}")))?;

        let width_px = stream
            .dict
            .get(b"Width")
            .ok()
            .and_then(|o| match o {
                lopdf::Object::Integer(v) => Some(*v as u32),
                _ => None,
            })
            .ok_or_else(|| TableError::DrawingError("Missing image Width".into()))?;

        let height_px = stream
            .dict
            .get(b"Height")
            .ok()
            .and_then(|o| match o {
                lopdf::Object::Integer(v) => Some(*v as u32),
                _ => None,
            })
            .ok_or_else(|| TableError::DrawingError("Missing image Height".into()))?;

        Ok(Self {
            xobject: Arc::new(stream),
            width_px,
            height_px,
            max_render_height_pts: None,
            fit: ImageFit::default(),
            overlay: None,
        })
    }

    /// Set maximum rendered height in points.
    pub fn with_max_height(mut self, pts: f32) -> Self {
        self.max_render_height_pts = Some(pts);
        self
    }

    /// Set the image fit mode.
    pub fn with_fit(mut self, fit: ImageFit) -> Self {
        self.fit = fit;
        self
    }

    /// Attach a text overlay to this image.
    pub fn with_overlay(mut self, overlay: ImageOverlay) -> Self {
        self.overlay = Some(overlay);
        self
    }

    /// Intrinsic pixel width.
    pub fn width_px(&self) -> u32 {
        self.width_px
    }

    /// Intrinsic pixel height.
    pub fn height_px(&self) -> u32 {
        self.height_px
    }

    /// Aspect ratio (width / height).
    pub fn aspect_ratio(&self) -> f32 {
        self.width_px as f32 / self.height_px as f32
    }
}

/// Column width specification
#[derive(Debug, Clone)]
pub enum ColumnWidth {
    /// Fixed width in points
    Pixels(f32),
    /// Percentage of available table width
    Percentage(f32),
    /// Automatically calculate based on content
    Auto,
}

/// Represents a table with rows and styling
#[derive(Clone)]
pub struct Table {
    pub rows: Vec<Row>,
    pub style: TableStyle,
    /// Column width specifications
    pub column_widths: Option<Vec<ColumnWidth>>,
    /// Total table width (if None, auto-calculate based on content)
    pub total_width: Option<f32>,
    /// Number of header rows to repeat on each page when paginating
    pub header_rows: usize,
    /// Font metrics for accurate text measurement and Unicode encoding.
    /// When set, enables font-aware text wrapping and glyph ID encoding.
    pub font_metrics: Option<Arc<dyn FontMetrics>>,
    /// Bold font metrics for accurate bold text measurement and Unicode encoding.
    /// When set, bold cells can use a dedicated embedded bold font.
    pub bold_font_metrics: Option<Arc<dyn FontMetrics>>,
}

impl std::fmt::Debug for Table {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Table")
            .field("rows", &self.rows)
            .field("style", &self.style)
            .field("column_widths", &self.column_widths)
            .field("total_width", &self.total_width)
            .field("header_rows", &self.header_rows)
            .field("font_metrics", &self.font_metrics.as_ref().map(|_| "..."))
            .field(
                "bold_font_metrics",
                &self.bold_font_metrics.as_ref().map(|_| "..."),
            )
            .finish()
    }
}

impl Table {
    /// Create a new empty table
    pub fn new() -> Self {
        Self {
            rows: Vec::new(),
            style: TableStyle::default(),
            column_widths: None,
            total_width: None,
            header_rows: 0,
            font_metrics: None,
            bold_font_metrics: None,
        }
    }

    /// Add a row to the table
    pub fn add_row(mut self, row: Row) -> Self {
        trace!("Adding row with {} cells", row.cells.len());
        self.rows.push(row);
        self
    }

    /// Set the table style
    pub fn with_style(mut self, style: TableStyle) -> Self {
        self.style = style;
        self
    }

    /// Set column width specifications
    pub fn with_column_widths(mut self, widths: Vec<ColumnWidth>) -> Self {
        self.column_widths = Some(widths);
        self
    }

    /// Set total table width
    pub fn with_total_width(mut self, width: f32) -> Self {
        self.total_width = Some(width);
        self
    }

    /// Convenience method to set pixel widths for all columns
    pub fn with_pixel_widths(mut self, widths: Vec<f32>) -> Self {
        self.column_widths = Some(widths.into_iter().map(ColumnWidth::Pixels).collect());
        self
    }

    /// Set border width for the entire table
    pub fn with_border(mut self, width: f32) -> Self {
        self.style.border_width = width;
        self
    }

    /// Set the number of header rows to repeat on each page
    pub fn with_header_rows(mut self, count: usize) -> Self {
        self.header_rows = count;
        self
    }

    /// Set font metrics for accurate text measurement and Unicode encoding.
    ///
    /// When font metrics are provided along with `embedded_font_resource_name`
    /// on the table style, text will be encoded as glyph IDs and measured
    /// using the actual font data instead of heuristic estimates.
    pub fn with_font_metrics(mut self, metrics: impl FontMetrics + 'static) -> Self {
        self.font_metrics = Some(Arc::new(metrics));
        self
    }

    /// Set bold font metrics for accurate bold text measurement and Unicode encoding.
    ///
    /// When font metrics are provided along with `embedded_font_resource_name_bold`
    /// on the table style, bold cell text will be encoded as glyph IDs and measured
    /// using the bold font data.
    pub fn with_bold_font_metrics(mut self, metrics: impl FontMetrics + 'static) -> Self {
        self.bold_font_metrics = Some(Arc::new(metrics));
        self
    }

    /// Get the number of columns (based on the first row, accounting for colspan)
    pub fn column_count(&self) -> usize {
        self.rows
            .first()
            .map(|r| r.cells.iter().map(|c| c.colspan.max(1)).sum())
            .unwrap_or(0)
    }

    /// Validate table structure
    pub fn validate(&self) -> Result<()> {
        if self.rows.is_empty() {
            return Err(crate::error::TableError::InvalidTable(
                "Table has no rows".to_string(),
            ));
        }

        let expected_cols = self.column_count();
        for (i, row) in self.rows.iter().enumerate() {
            // Calculate the total column coverage including colspan
            let mut total_coverage = 0;
            for cell in &row.cells {
                total_coverage += cell.colspan.max(1);
            }

            if total_coverage != expected_cols {
                return Err(crate::error::TableError::InvalidTable(format!(
                    "Row {} covers {} columns (with colspan), expected {}",
                    i, total_coverage, expected_cols
                )));
            }
        }

        if let Some(ref widths) = self.column_widths {
            if widths.len() != expected_cols {
                return Err(crate::error::TableError::InvalidTable(format!(
                    "Column widths array has {} elements, but table has {} columns",
                    widths.len(),
                    expected_cols
                )));
            }

            // Check that percentage widths don't exceed 100%
            let total_percentage: f32 = widths
                .iter()
                .filter_map(|w| match w {
                    ColumnWidth::Percentage(p) => Some(*p),
                    _ => None,
                })
                .sum();

            if total_percentage > 100.0 {
                return Err(crate::error::TableError::InvalidTable(format!(
                    "Total percentage widths ({:.1}%) exceed 100%",
                    total_percentage
                )));
            }
        }

        Ok(())
    }
}

impl Default for Table {
    fn default() -> Self {
        Self::new()
    }
}

/// Represents a row in a table
#[derive(Debug, Clone)]
pub struct Row {
    pub cells: Vec<Cell>,
    pub style: Option<RowStyle>,
    /// Explicit height (if None, auto-calculate)
    pub height: Option<f32>,
}

impl Row {
    /// Create a new row with cells
    pub fn new(cells: Vec<Cell>) -> Self {
        Self {
            cells,
            style: None,
            height: None,
        }
    }

    /// Set row style
    pub fn with_style(mut self, style: RowStyle) -> Self {
        self.style = Some(style);
        self
    }

    /// Set explicit row height
    pub fn with_height(mut self, height: f32) -> Self {
        self.height = Some(height);
        self
    }
}

/// Represents a cell in a table
#[derive(Debug, Clone)]
pub struct Cell {
    pub content: String,
    pub style: Option<CellStyle>,
    pub colspan: usize,
    pub rowspan: usize,
    /// Enable text wrapping for this cell
    pub text_wrap: bool,
    /// Image payloads for this cell (rendered side-by-side when multiple).
    pub images: Vec<CellImage>,
}

impl Cell {
    /// Create a new cell with text content
    pub fn new<S: Into<String>>(content: S) -> Self {
        Self {
            content: content.into(),
            style: None,
            colspan: 1,
            rowspan: 1,
            text_wrap: false,
            images: Vec::new(),
        }
    }

    /// Create an empty cell
    pub fn empty() -> Self {
        Self::new("")
    }

    /// Create a cell containing a single image (with empty text).
    pub fn from_image(image: CellImage) -> Self {
        Self {
            content: String::new(),
            style: None,
            colspan: 1,
            rowspan: 1,
            text_wrap: false,
            images: vec![image],
        }
    }

    /// Create a cell containing multiple images rendered side-by-side (with empty text).
    pub fn from_images(images: Vec<CellImage>) -> Self {
        Self {
            content: String::new(),
            style: None,
            colspan: 1,
            rowspan: 1,
            text_wrap: false,
            images,
        }
    }

    /// Set a single image payload for this cell (replaces any existing images).
    pub fn with_image(mut self, image: CellImage) -> Self {
        self.images = vec![image];
        self
    }

    /// Append an additional image to this cell.
    pub fn add_image(mut self, image: CellImage) -> Self {
        self.images.push(image);
        self
    }

    /// Enable text wrapping for this cell
    pub fn with_wrap(mut self, wrap: bool) -> Self {
        self.text_wrap = wrap;
        self
    }

    /// Set cell style
    pub fn with_style(mut self, style: CellStyle) -> Self {
        self.style = Some(style);
        self
    }

    /// Set colspan
    pub fn with_colspan(mut self, span: usize) -> Self {
        self.colspan = span.max(1);
        self
    }

    /// Set rowspan
    pub fn with_rowspan(mut self, span: usize) -> Self {
        self.rowspan = span.max(1);
        self
    }

    /// Make text bold
    pub fn bold(mut self) -> Self {
        let mut style = self.style.unwrap_or_default();
        style.bold = true;
        self.style = Some(style);
        self
    }

    /// Make text italic
    pub fn italic(mut self) -> Self {
        let mut style = self.style.unwrap_or_default();
        style.italic = true;
        self.style = Some(style);
        self
    }

    /// Set font size
    pub fn with_font_size(mut self, size: f32) -> Self {
        let mut style = self.style.unwrap_or_default();
        style.font_size = Some(size);
        self.style = Some(style);
        self
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_table_validation() {
        let mut table = Table::new();
        assert!(table.validate().is_err());

        table = table.add_row(Row::new(vec![Cell::new("A"), Cell::new("B")]));
        assert!(table.validate().is_ok());

        table = table.add_row(Row::new(vec![Cell::new("C")]));
        assert!(table.validate().is_err());
    }

    #[test]
    fn test_cell_builder() {
        let cell = Cell::new("Test")
            .bold()
            .italic()
            .with_font_size(14.0)
            .with_colspan(2);

        assert_eq!(cell.content, "Test");
        assert_eq!(cell.colspan, 2);
        let style = cell.style.unwrap();
        assert!(style.bold);
        assert!(style.italic);
        assert_eq!(style.font_size, Some(14.0));
    }

    #[test]
    fn test_cell_font_name() {
        // Test with custom font
        let style = CellStyle {
            font_name: Some("Courier".to_string()),
            ..Default::default()
        };
        let cell = Cell::new("Monospace text").with_style(style);

        assert_eq!(cell.content, "Monospace text");
        let cell_style = cell.style.unwrap();
        assert_eq!(cell_style.font_name, Some("Courier".to_string()));

        // Test with default (no font specified)
        let cell_default = Cell::new("Default font");
        assert!(cell_default.style.is_none());
    }

    #[test]
    fn test_with_bold_font_metrics_builder() {
        struct DummyMetrics;

        impl crate::font::FontMetrics for DummyMetrics {
            fn char_width(&self, _ch: char, _font_size: f32) -> f32 {
                5.0
            }

            fn text_width(&self, text: &str, _font_size: f32) -> f32 {
                text.chars().count() as f32 * 5.0
            }

            fn encode_text(&self, text: &str) -> Vec<u8> {
                vec![0; text.chars().count() * 2]
            }
        }

        let table = Table::new().with_bold_font_metrics(DummyMetrics);
        assert!(table.bold_font_metrics.is_some());
    }
}