pdf-docx 1.2.0

PDF to DOCX conversion with text, tables, and images
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
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
//! Spatial grouping of text blocks into lines, paragraphs, and tables.

// Copyright (c) 2026 Innovation Trigger B.V.
//
// PDFluent is available under two licences, at your option: the GNU AGPLv3, or
// the PDFluent Commercial Licence. See the LICENSE file in this repository --
// that file travels with the copy you received, which a URL does not.

use crate::rules::Rule;
use pdf_extract::TextBlock;

/// Tolerance for grouping text blocks into lines (points).
const LINE_Y_TOLERANCE: f64 = 2.0;

/// Vertical gap threshold for paragraph breaks (fraction of font size).
const PARAGRAPH_GAP_FACTOR: f64 = 1.5;

/// A change in font size (points) that starts a new paragraph.
const STYLE_SIZE_STEP: f64 = 1.0;

/// Tolerance for column alignment in table detection (points).
const TABLE_X_TOLERANCE: f64 = 5.0;

/// A run of text with consistent formatting — the smallest unit emitted to
/// the resulting DOCX.
///
/// A [`Paragraph`] is a sequence of one or more runs. A new run is started
/// whenever the layout detector observes a change in font, size, weight, or
/// style on the same line; consecutive characters with the same formatting
/// stay in a single run.
#[derive(Debug, Clone)]
pub struct Run {
    /// The actual text content of this run, in source order. May contain
    /// any UTF-8 characters extracted from the PDF page.
    pub text: String,
    /// PostScript name of the font as it appears in the PDF (e.g.
    /// `Helvetica`, `TimesNewRomanPS-BoldMT`). Mapped to a Word font name
    /// during DOCX writing.
    pub font_name: String,
    /// Font size in PDF user-space points. Persisted to DOCX as half-points
    /// (Word's native unit).
    pub font_size: f64,
    /// Whether the run is rendered bold. Detected from font name suffix
    /// (`-Bold`, `Bd`) or PDF font flags.
    pub bold: bool,
    /// Whether the run is rendered italic. Detected from font name suffix
    /// (`-Italic`, `It`, `Oblique`) or PDF font flags.
    pub italic: bool,
}

/// A paragraph composed of one or more [`Run`]s.
///
/// Produced by the line-grouping pass: lines whose vertical gap is below
/// [`PARAGRAPH_GAP_FACTOR`] times the font size are considered part of the
/// same paragraph; a larger gap ends the paragraph.
#[derive(Debug, Clone)]
pub struct Paragraph {
    /// The runs that make up this paragraph, in reading order. Empty
    /// paragraphs are valid and represent blank lines.
    pub runs: Vec<Run>,
}

/// A table reconstructed from text blocks aligned in columns.
///
/// Detected when consecutive lines share the same column x-coordinates
/// within [`TABLE_X_TOLERANCE`]. Rebuilt into a regular grid where each
/// row has the same number of cells (`col_count`); short rows are
/// right-padded with empty strings.
#[derive(Debug, Clone)]
pub struct Table {
    /// Row-major cell content. `rows[r][c]` is the text in column `c` of
    /// row `r`. All rows have length [`Self::col_count`].
    pub rows: Vec<Vec<String>>,
    /// Number of columns in the table — the maximum column count observed
    /// during column-alignment detection.
    pub col_count: usize,
}

/// An image to embed into the resulting DOCX document.
///
/// Produced when the layout pass identifies an image XObject on the page
/// that should be carried over to the Word document. The bytes are kept
/// verbatim; the DOCX writer wraps them in the appropriate `w:drawing`
/// element with the given dimensions.
#[derive(Debug, Clone)]
pub struct DocxImage {
    /// Raw image bytes in the format described by [`Self::content_type`]
    /// (typically PNG or JPEG).
    pub data: Vec<u8>,
    /// Image width in pixels. Used to compute the on-page rendered size.
    pub width: u32,
    /// Image height in pixels. Used to compute the on-page rendered size.
    pub height: u32,
    /// MIME type of [`Self::data`] — e.g. `image/png`, `image/jpeg`. Drives
    /// the part name and `Override` content-type entry in the DOCX `[Content_Types].xml`.
    pub content_type: String,
    /// Stable identifier used to deduplicate images that appear on multiple
    /// pages and to wire up the relationship reference in the DOCX.
    pub id: String,
}

/// One element in the per-page layout: a paragraph, a table, or an image.
///
/// Produced by the layout analysis pass. Pages emit a `Vec<PageElement>` in
/// reading order; the DOCX writer iterates these and produces matching
/// Word document parts.
#[derive(Debug, Clone)]
pub enum PageElement {
    /// A flowing paragraph of text — see [`Paragraph`].
    Para(Paragraph),
    /// A reconstructed table — see [`Table`].
    Tbl(Table),
    /// An embedded image — see [`DocxImage`].
    Img(DocxImage),
}

/// A line of text (blocks at roughly the same y-coordinate).
#[derive(Debug)]
struct Line {
    y: f64,
    font_size: f64,
    blocks: Vec<TextBlock>,
}

/// Analyze text blocks from a page and group them into paragraphs and tables.
///
/// Without ruling lines this can only find borderless tables by column
/// alignment. [`analyze_page_with_rules`] also uses the page's drawn borders.
pub fn analyze_page(blocks: &[TextBlock]) -> Vec<PageElement> {
    analyze_page_with_rules(blocks, &[])
}

/// Like [`analyze_page`], and additionally reconstructs every ruled grid.
///
/// A ruled grid is a set of connected horizontal and vertical strokes that
/// forms at least two columns and two rows. Its cells are the bands between
/// neighbouring strokes; the text blocks whose centre lies inside a band belong
/// to that cell. Text outside every grid stays ordinary paragraphs, so a
/// paragraph directly above a table is never taken for its first row, and a page
/// can hold several tables with different column counts. Elements come back in
/// reading order (top to bottom).
pub fn analyze_page_with_rules(blocks: &[TextBlock], rules: &[Rule]) -> Vec<PageElement> {
    if blocks.is_empty() {
        return Vec::new();
    }

    let grids = ruled_grids(rules);
    if grids.is_empty() {
        let lines = group_into_lines(blocks);
        if let Some(tbl) = try_detect_table(&lines) {
            return vec![PageElement::Tbl(tbl)];
        }
        return group_into_paragraphs(&lines)
            .into_iter()
            .map(|(_, e)| e)
            .collect();
    }

    let mut inside: Vec<Vec<TextBlock>> = vec![Vec::new(); grids.len()];
    let mut outside: Vec<TextBlock> = Vec::new();
    for block in blocks {
        let cx = (block.bbox[0] + block.bbox[2]) / 2.0;
        let cy = (block.bbox[1] + block.bbox[3]) / 2.0;
        match grids.iter().position(|g| g.contains(cx, cy)) {
            Some(i) => inside[i].push(block.clone()),
            None => outside.push(block.clone()),
        }
    }

    let mut items: Vec<(f64, PageElement)> = Vec::new();
    for (grid, cell_blocks) in grids.iter().zip(&inside) {
        items.push((grid.y1, PageElement::Tbl(grid_table(grid, cell_blocks))));
    }

    // A table ends a paragraph: lines above it and below it never join.
    let lines = group_into_lines(&outside);
    let section = |y: f64| grids.iter().filter(|g| g.y0 > y).count();
    let mut start = 0;
    while start < lines.len() {
        let id = section(lines[start].y);
        let mut end = start + 1;
        while end < lines.len() && section(lines[end].y) == id {
            end += 1;
        }
        items.extend(group_into_paragraphs(&lines[start..end]));
        start = end;
    }

    items.sort_by(|a, b| b.0.partial_cmp(&a.0).unwrap_or(std::cmp::Ordering::Equal));
    items.into_iter().map(|(_, e)| e).collect()
}

/// A table drawn with ruling lines.
#[derive(Debug)]
struct Grid {
    x0: f64,
    y0: f64,
    x1: f64,
    y1: f64,
    /// Column boundaries, left to right.
    xs: Vec<f64>,
    /// Row boundaries, top to bottom.
    ys: Vec<f64>,
}

impl Grid {
    fn contains(&self, x: f64, y: f64) -> bool {
        x >= self.x0 - 1.0 && x <= self.x1 + 1.0 && y >= self.y0 - 1.0 && y <= self.y1 + 1.0
    }
}

/// Strokes closer than this are the same border (also the gap tolerated
/// between two strokes that meet at a corner).
const RULE_TOLERANCE: f64 = 2.0;

fn cluster(mut values: Vec<f64>) -> Vec<f64> {
    values.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
    let mut out: Vec<(f64, usize)> = Vec::new();
    for v in values {
        match out.last_mut() {
            Some((mean, n)) if (v - *mean).abs() <= RULE_TOLERANCE => {
                *mean = (*mean * *n as f64 + v) / (*n as f64 + 1.0);
                *n += 1;
            }
            _ => out.push((v, 1)),
        }
    }
    out.into_iter().map(|(m, _)| m).collect()
}

fn find(parent: &mut [usize], mut i: usize) -> usize {
    while parent[i] != i {
        parent[i] = parent[parent[i]];
        i = parent[i];
    }
    i
}

/// Connected groups of strokes that form at least two columns and two rows.
fn ruled_grids(rules: &[Rule]) -> Vec<Grid> {
    let n = rules.len();
    if n < 4 {
        return Vec::new();
    }
    let mut parent: Vec<usize> = (0..n).collect();
    for i in 0..n {
        for j in (i + 1)..n {
            let (a, b) = (&rules[i], &rules[j]);
            let touch = a.x0 - RULE_TOLERANCE <= b.x1
                && b.x0 - RULE_TOLERANCE <= a.x1
                && a.y0 - RULE_TOLERANCE <= b.y1
                && b.y0 - RULE_TOLERANCE <= a.y1;
            if touch {
                let (ri, rj) = (find(&mut parent, i), find(&mut parent, j));
                parent[ri] = rj;
            }
        }
    }

    let mut groups: std::collections::BTreeMap<usize, Vec<usize>> = Default::default();
    for i in 0..n {
        let root = find(&mut parent, i);
        groups.entry(root).or_default().push(i);
    }

    let mut grids = Vec::new();
    for members in groups.values() {
        let mut xs = Vec::new();
        let mut ys = Vec::new();
        let (mut x0, mut y0, mut x1, mut y1) = (f64::MAX, f64::MAX, f64::MIN, f64::MIN);
        for &m in members {
            let r = &rules[m];
            if r.is_horizontal() {
                ys.push((r.y0 + r.y1) / 2.0);
            } else {
                xs.push((r.x0 + r.x1) / 2.0);
            }
            x0 = x0.min(r.x0);
            y0 = y0.min(r.y0);
            x1 = x1.max(r.x1);
            y1 = y1.max(r.y1);
        }
        let xs = cluster(xs);
        let mut ys = cluster(ys);
        if xs.len() < 3 || ys.len() < 3 {
            continue;
        }
        ys.reverse();
        grids.push(Grid {
            x0,
            y0,
            x1,
            y1,
            xs,
            ys,
        });
    }
    grids
}

/// Index of the band `[bounds[i], bounds[i+1])` that holds `v`, clamped.
fn band(bounds: &[f64], v: f64, descending: bool) -> usize {
    let cells = bounds.len() - 1;
    for i in 0..cells {
        let inside = if descending {
            v <= bounds[i] && v > bounds[i + 1]
        } else {
            v >= bounds[i] && v < bounds[i + 1]
        };
        if inside {
            return i;
        }
    }
    let first = bounds[0];
    let past_start = if descending { v > first } else { v < first };
    if past_start {
        0
    } else {
        cells - 1
    }
}

fn grid_table(grid: &Grid, blocks: &[TextBlock]) -> Table {
    let cols = grid.xs.len() - 1;
    let rows = grid.ys.len() - 1;
    let mut cells: Vec<Vec<Vec<TextBlock>>> = vec![vec![Vec::new(); cols]; rows];
    for block in blocks {
        let cx = (block.bbox[0] + block.bbox[2]) / 2.0;
        let cy = (block.bbox[1] + block.bbox[3]) / 2.0;
        let c = band(&grid.xs, cx, false);
        let r = band(&grid.ys, cy, true);
        cells[r][c].push(block.clone());
    }
    let rows = cells
        .into_iter()
        .map(|row| {
            row.into_iter()
                .map(|cell| {
                    group_into_lines(&cell)
                        .iter()
                        .map(line_text)
                        .collect::<Vec<_>>()
                        .join(" ")
                })
                .collect()
        })
        .collect();
    Table {
        rows,
        col_count: cols,
    }
}

fn line_text(line: &Line) -> String {
    line.blocks
        .iter()
        .map(|b| b.text.as_str())
        .collect::<Vec<_>>()
        .join(" ")
}

/// Group text blocks into lines based on y-coordinate proximity.
fn group_into_lines(blocks: &[TextBlock]) -> Vec<Line> {
    let mut sorted: Vec<&TextBlock> = blocks.iter().collect();
    // Sort by y descending (PDF origin is bottom-left), then x ascending.
    sorted.sort_by(|a, b| {
        let y_cmp = b.bbox[1]
            .partial_cmp(&a.bbox[1])
            .unwrap_or(std::cmp::Ordering::Equal);
        if y_cmp == std::cmp::Ordering::Equal {
            a.bbox[0]
                .partial_cmp(&b.bbox[0])
                .unwrap_or(std::cmp::Ordering::Equal)
        } else {
            y_cmp
        }
    });

    let mut lines: Vec<Line> = Vec::new();

    for block in sorted {
        let y = block.bbox[1];
        let matched = lines
            .iter_mut()
            .find(|line| (line.y - y).abs() < LINE_Y_TOLERANCE);

        if let Some(line) = matched {
            line.blocks.push(block.clone());
        } else {
            lines.push(Line {
                y,
                font_size: block.font_size,
                blocks: vec![block.clone()],
            });
        }
    }

    // Sort each line's blocks by x-coordinate, then fuse glyph runs into words.
    for line in &mut lines {
        line.blocks.sort_by(|a, b| {
            a.bbox[0]
                .partial_cmp(&b.bbox[0])
                .unwrap_or(std::cmp::Ordering::Equal)
        });
        line.blocks = merge_glyph_runs(std::mem::take(&mut line.blocks));
    }

    lines
}

/// Gap between two single-glyph blocks, as a fraction of the font size, below
/// which they are one word. Wider gaps are word spaces.
const GLYPH_JOIN_GAP: f64 = 0.15;

/// Fuse neighbouring single-glyph blocks into words.
///
/// Some producers (design-tool exports in particular) position every glyph with
/// its own text-positioning operator. Each glyph then arrives as a block of its
/// own, and every glyph start looked like a column start: a heading came out as
/// one cell per letter (#408). Only runs of single-glyph blocks are fused;
/// blocks that already hold a word are left as they are.
fn merge_glyph_runs(blocks: Vec<TextBlock>) -> Vec<TextBlock> {
    let mut out: Vec<TextBlock> = Vec::with_capacity(blocks.len());
    let mut prev_was_glyph = false;
    for block in blocks {
        let is_glyph = block.text.chars().count() == 1;
        if let Some(last) = out.last_mut() {
            let gap = block.bbox[0] - last.bbox[2];
            if prev_was_glyph && is_glyph && gap < GLYPH_JOIN_GAP * last.font_size.max(1.0) {
                last.text.push_str(&block.text);
                last.bbox[2] = last.bbox[2].max(block.bbox[2]);
                last.bbox[3] = last.bbox[3].max(block.bbox[3]);
                prev_was_glyph = is_glyph;
                continue;
            }
        }
        prev_was_glyph = is_glyph;
        out.push(block);
    }
    out
}

/// A column is an x-position that recurs on several lines.
///
/// Not every distinct x. That was the bug: `col_count` was the number of
/// distinct x-positions across the whole block set, and in a real PDF almost
/// every word starts at its own x. A line of twenty words therefore produced
/// twenty columns -- roughly one word per cell, which leaves the file valid and
/// unusable. See #161.
///
/// What distinguishes a column from an accidental word position is recurrence:
/// text beginning at (nearly) the same x on several lines. An x that appears on
/// one line only is a word.
///
/// Two lines or 30% was still too little, and the end-to-end test said so: a
/// grid of four rows by two columns came back with six columns. In a real table
/// a cell holds words, and every word starts at its own x. Those word positions
/// shift only a few points from row to row, so within [`TABLE_X_TOLERANCE`] two
/// of them keep landing together -- which already satisfied the old threshold.
///
/// What separates a column from a word is therefore not *that* the x recurs but
/// *how often*: a column start recurs on nearly every line, a word position does
/// not. Hence 75%. Lower lets word positions through; much higher loses tables
/// in which a cell is occasionally empty.
const MIN_COLUMN_LINES: usize = 2;
/// The gap before a column start, as a fraction of the font size. One word
/// space is about a third of an em; a column gap is more than an em.
const MIN_COLUMN_GAP_EM: f64 = 1.0;
const MIN_COLUMN_SUPPORT_PERCENT: usize = 75;

/// The x-positions that behave as a column, ordered left to right.
fn column_positions(lines: &[Line]) -> Vec<f64> {
    // Per candidate x: on how many distinct lines does text start there?
    let mut candidates: Vec<(f64, usize)> = Vec::new();
    for line in lines {
        let mut counted: Vec<usize> = Vec::new();
        for (i, block) in line.blocks.iter().enumerate() {
            // A column starts after a gap wider than a word space. Words of
            // running text that happen to share an x on several lines (equal
            // word lengths, a monospace face, glyph-per-block exports) sit one
            // space apart and are not columns; a table's columns are further
            // apart than that.
            if i > 0
                && block.bbox[0] - line.blocks[i - 1].bbox[2] < MIN_COLUMN_GAP_EM * line.font_size
            {
                continue;
            }
            let x = block.bbox[0];
            match candidates
                .iter()
                .position(|&(px, _)| (px - x).abs() < TABLE_X_TOLERANCE)
            {
                Some(i) => {
                    // One line counts at most once for the same column;
                    // otherwise a line with five words at the same x invents a
                    // column that is not there.
                    if !counted.contains(&i) {
                        candidates[i].1 += 1;
                        counted.push(i);
                    }
                }
                None => {
                    candidates.push((x, 1));
                    counted.push(candidates.len() - 1);
                }
            }
        }
    }

    // Rounded up, not down.
    //
    // At three lines `3 * 75 / 100` gave two, so a word position that happened
    // to coincide on two of the three lines still counted as a column. On a
    // small table every line is evidence, and the requirement must not evaporate
    // through integer division.
    let required = (lines.len() * MIN_COLUMN_SUPPORT_PERCENT).div_ceil(100);
    let threshold = std::cmp::max(MIN_COLUMN_LINES, required);
    let mut positions: Vec<f64> = candidates
        .into_iter()
        .filter(|&(_, support)| support >= threshold)
        .map(|(x, _)| x)
        .collect();
    positions.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
    positions
}

/// The column this block belongs to: the nearest column that does not sit to
/// the right of the block.
///
/// Previously everything that did not start exactly on a column fell back to
/// column 0 (`unwrap_or(0)`), which dumped unaligned text from the whole line
/// into the first cell. Text belongs to the column it sits under.
fn column_for(x: f64, positions: &[f64]) -> usize {
    let mut best = 0;
    for (i, &px) in positions.iter().enumerate() {
        if px <= x + TABLE_X_TOLERANCE {
            best = i;
        } else {
            break;
        }
    }
    best
}

/// Try to detect a table from aligned text lines.
///
/// A table is detected when multiple lines share the same column structure
/// (i.e., text blocks start at similar x-positions across lines).
fn try_detect_table(lines: &[Line]) -> Option<Table> {
    if lines.len() < 2 {
        return None;
    }

    let x_positions = column_positions(lines);
    if x_positions.len() < 2 {
        return None;
    }

    // Do most lines carry text in more than one column?
    let multi_col_lines = lines
        .iter()
        .filter(|line| {
            line.blocks
                .iter()
                .map(|b| column_for(b.bbox[0], &x_positions))
                .collect::<std::collections::HashSet<_>>()
                .len()
                >= 2
        })
        .count();

    // At least 60% of lines need multiple columns for table detection.
    if multi_col_lines * 100 / lines.len() < 60 {
        return None;
    }

    let col_count = x_positions.len();
    let mut rows = Vec::new();

    for line in lines {
        let mut row = vec![String::new(); col_count];
        for block in &line.blocks {
            let col_idx = column_for(block.bbox[0], &x_positions);
            if !row[col_idx].is_empty() {
                row[col_idx].push(' ');
            }
            row[col_idx].push_str(&block.text);
        }
        rows.push(row);
    }

    Some(Table { rows, col_count })
}

/// Group lines into paragraphs based on vertical spacing.
///
/// Returns each paragraph with the y of its first line. A paragraph ends at a
/// large vertical gap and also where the type changes (size or weight): a
/// heading is never glued to the body text under it. Lines inside a paragraph
/// are joined with a space.
fn group_into_paragraphs(lines: &[Line]) -> Vec<(f64, PageElement)> {
    let mut elements = Vec::new();
    let mut current_runs: Vec<Run> = Vec::new();
    let mut current_y = 0.0;
    let mut prev_y: Option<f64> = None;
    let mut prev_font_size: f64 = 12.0;
    let mut prev_bold = false;

    for line in lines {
        let mut line_text = line_text(line);
        if line_text.trim().is_empty() {
            continue;
        }

        let font_name = line
            .blocks
            .first()
            .map(|b| b.font_name.clone())
            .unwrap_or_default();
        let font_size = line.font_size;

        let bold = font_name.contains("Bold")
            || font_name.contains("bold")
            || line.blocks.first().is_some_and(|b| b.is_bold);
        let italic = font_name.contains("Italic")
            || font_name.contains("italic")
            || font_name.contains("Oblique")
            || line.blocks.first().is_some_and(|b| b.is_italic);

        let is_new_paragraph = match prev_y {
            Some(py) => {
                (py - line.y).abs() > prev_font_size * PARAGRAPH_GAP_FACTOR
                    || (font_size - prev_font_size).abs() > STYLE_SIZE_STEP
                    || bold != prev_bold
            }
            None => false,
        };

        if is_new_paragraph && !current_runs.is_empty() {
            elements.push((
                current_y,
                PageElement::Para(Paragraph {
                    runs: std::mem::take(&mut current_runs),
                }),
            ));
        }
        if current_runs.is_empty() {
            current_y = line.y;
        } else {
            line_text.insert(0, ' ');
        }

        current_runs.push(Run {
            text: line_text,
            font_name,
            font_size,
            bold,
            italic,
        });

        prev_y = Some(line.y);
        prev_font_size = font_size;
        prev_bold = bold;
    }

    if !current_runs.is_empty() {
        elements.push((
            current_y,
            PageElement::Para(Paragraph { runs: current_runs }),
        ));
    }

    elements
}

/// Detect bold/italic from a PDF font name.
pub fn map_font_name(pdf_font: &str) -> &str {
    // Strip common prefixes like "ABCDEF+" used in subset fonts.
    let name = if let Some(pos) = pdf_font.find('+') {
        &pdf_font[pos + 1..]
    } else {
        pdf_font
    };

    // Map common font families.
    if name.contains("Times") || name.contains("Serif") {
        "Times New Roman"
    } else if name.contains("Arial") || name.contains("Helvetica") || name.contains("Sans") {
        "Arial"
    } else if name.contains("Courier") || name.contains("Mono") {
        "Courier New"
    } else if name.contains("Symbol") {
        "Symbol"
    } else {
        "Calibri"
    }
}

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

    fn make_block(text: &str, x: f64, y: f64, font_size: f64) -> TextBlock {
        TextBlock {
            text: text.to_string(),
            page: 1,
            bbox: [x, y, x + text.len() as f64 * font_size * 0.5, y + font_size],
            font_name: "F1".to_string(),
            font_size,
            actual_text: None,
            base_font: None,
            is_bold: false,
            is_italic: false,
            color: None,
            width_source: Default::default(),
            char_bounds: vec![],
        }
    }

    #[test]
    fn single_line_becomes_paragraph() {
        let blocks = vec![make_block("Hello World", 72.0, 720.0, 12.0)];
        let elements = analyze_page(&blocks);
        assert_eq!(elements.len(), 1);
        assert!(matches!(elements[0], PageElement::Para(_)));
    }

    #[test]
    fn two_close_lines_same_paragraph() {
        let blocks = vec![
            make_block("Line 1", 72.0, 720.0, 12.0),
            make_block("Line 2", 72.0, 706.0, 12.0), // gap = 14, < 12*1.5=18
        ];
        let elements = analyze_page(&blocks);
        assert_eq!(elements.len(), 1);
    }

    #[test]
    fn two_distant_lines_different_paragraphs() {
        let blocks = vec![
            make_block("Para 1", 72.0, 720.0, 12.0),
            make_block("Para 2", 72.0, 680.0, 12.0), // gap = 40, > 18
        ];
        let elements = analyze_page(&blocks);
        assert_eq!(elements.len(), 2);
    }

    #[test]
    fn table_detection() {
        let blocks = vec![
            // Row 1
            make_block("Name", 72.0, 700.0, 12.0),
            make_block("Age", 200.0, 700.0, 12.0),
            // Row 2
            make_block("Alice", 72.0, 684.0, 12.0),
            make_block("30", 200.0, 684.0, 12.0),
            // Row 3
            make_block("Bob", 72.0, 668.0, 12.0),
            make_block("25", 200.0, 668.0, 12.0),
        ];
        let elements = analyze_page(&blocks);
        assert_eq!(elements.len(), 1);
        assert!(matches!(elements[0], PageElement::Tbl(_)));
        if let PageElement::Tbl(ref tbl) = elements[0] {
            assert_eq!(tbl.rows.len(), 3);
            assert_eq!(tbl.col_count, 2);
        }
    }

    #[test]
    fn empty_blocks_returns_empty() {
        let elements = analyze_page(&[]);
        assert!(elements.is_empty());
    }

    // ---- column detection (#161) ----

    #[test]
    fn a_sentence_does_not_become_a_table_with_a_column_per_word() {
        // The symptom from #161, reduced to its core: ordinary lines of text in
        // which every word has its own x. Previously every distinct x became a
        // column, so you got roughly one word per cell -- a valid .docx nobody
        // can use.
        let mut blocks = Vec::new();
        for (row, y) in [(0, 700.0), (1, 684.0), (2, 668.0)] {
            // Words at ever-different x-positions, as in flowing text.
            for w in 0..8 {
                let x = 72.0 + (w as f64) * 37.0 + (row as f64) * 11.0;
                blocks.push(make_block("word", x, y, 12.0));
            }
        }
        let elements = analyze_page(&blocks);
        for el in &elements {
            if let PageElement::Tbl(t) = el {
                assert!(
                    t.col_count <= 4,
                    "flowing text became a table of {} columns; that is the \
                     symptom from #161",
                    t.col_count
                );
            }
        }
    }

    #[test]
    fn a_real_table_keeps_its_columns() {
        // The counter-test. Were the new requirement too strict, tables that do
        // exist would disappear -- a worse failure than too many columns, since
        // then the structure is gone entirely.
        let mut blocks = Vec::new();
        for y in [700.0_f64, 684.0, 668.0, 652.0] {
            blocks.push(make_block("left", 72.0, y, 12.0));
            blocks.push(make_block("middle", 200.0, y, 12.0));
            blocks.push(make_block("right", 340.0, y, 12.0));
        }
        let elements = analyze_page(&blocks);
        let table = elements.iter().find_map(|e| match e {
            PageElement::Tbl(t) => Some(t),
            _ => None,
        });
        let t = table.expect("an aligned three-column table was not detected");
        assert_eq!(t.col_count, 3, "columns: {:?}", t.rows.first());
        assert_eq!(t.rows.len(), 4);
    }

    #[test]
    fn text_without_a_column_of_its_own_does_not_land_in_the_first_cell() {
        // Previously everything that did not start exactly on a column ended up
        // in column 0 (`unwrap_or(0)`), so loose text from the whole line landed
        // in the first cell. Text belongs to the column it sits under.
        let mut blocks = Vec::new();
        for y in [700.0_f64, 684.0, 668.0] {
            blocks.push(make_block("A", 72.0, y, 12.0));
            blocks.push(make_block("B", 300.0, y, 12.0));
        }
        // One block that forms no column anywhere, but does sit on the right.
        blocks.push(make_block("loose", 310.0, 652.0, 12.0));
        blocks.push(make_block("A", 72.0, 652.0, 12.0));

        let elements = analyze_page(&blocks);
        if let Some(PageElement::Tbl(t)) =
            elements.iter().find(|e| matches!(e, PageElement::Tbl(_)))
        {
            let last = t.rows.last().expect("no rows");
            assert!(
                !last[0].contains("loose"),
                "unaligned text was dumped into the first cell: {last:?}"
            );
        }
    }
}