Cotton code
107 lines · 3.9 KB · RustRaw
//! A PDF page's text as the reader needs it: lines from top to bottom, each//! line its cells from left to right, a cell a run of words with no column//! gap inside it. Whatever reads the PDF (the Mac's pure-Rust reader, a//! phone's own PDF kit later) hands glyphs here and the same lines come out.use serde::{Deserialize, Serialize};/// One glyph as a PDF reader placed it: `x` from the page's left, `y` from/// its TOP (a reader whose y grows upwards flips it), `width` its advance,/// `size` the font size, all in points.#[derive(Debug, Clone, PartialEq)]pub struct Glyph {    pub x: f32,    pub y: f32,    pub width: f32,    pub size: f32,    pub text: String,}#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]pub struct TextCell {    pub x0: f32,    pub x1: f32,    pub text: String,}#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]pub struct TextLine {    /// The baseline, from the page's top.    pub y: f32,    /// The line's largest font size.    pub size: f32,    pub cells: Vec<TextCell>,}impl TextLine {    /// The line's cells joined by a space.    pub fn text(&self) -> String {        self.cells.iter().map(|cell| cell.text.as_str()).collect::<Vec<_>>().join(" ")    }}#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]pub struct TextPage {    pub lines: Vec<TextLine>,}/// A gap wider than this many font sizes ends a cell.pub const CELL_GAP: f32 = 1.0;/// A gap wider than this many font sizes is a space between words.pub const WORD_GAP: f32 = 0.15;/// Lines and cells from a page's glyphs.pub fn assemble(mut glyphs: Vec<Glyph>) -> TextPage {    glyphs.retain(|glyph| glyph.size > 0.0 && glyph.x.is_finite() && glyph.y.is_finite());    glyphs.sort_by(|a, b| a.y.total_cmp(&b.y).then(a.x.total_cmp(&b.x)));    // Lines: glyphs whose baselines sit within a third of a size of the line's.    let mut rows: Vec<(f32, f32, Vec<Glyph>)> = Vec::new();    for glyph in glyphs {        match rows.last_mut() {            Some((y, size, row)) if (glyph.y - *y).abs() <= 0.35 * size.max(glyph.size) => {                *size = size.max(glyph.size);                row.push(glyph);            }            _ => rows.push((glyph.y, glyph.size, vec![glyph])),        }    }    let mut lines = Vec::new();    for (y, size, mut row) in rows {        row.sort_by(|a, b| a.x.total_cmp(&b.x));        let mut cells: Vec<TextCell> = Vec::new();        let mut word_end: Option<f32> = None;        // A space the PDF draws separates words however narrow its advance.        let mut spaced = false;        for glyph in row {            if glyph.text.trim().is_empty() {                // A space glyph: the gap after it decides a cell; it is a word break at least.                spaced = true;                continue;            }            let start_new_cell = match (cells.last(), word_end) {                (Some(_), Some(end)) => glyph.x - end > CELL_GAP * size,                _ => true,            };            if start_new_cell {                cells.push(TextCell { x0: glyph.x, x1: glyph.x + glyph.width, text: glyph.text.clone() });            } else {                let cell = cells.last_mut().expect("a cell");                if (spaced || glyph.x - word_end.unwrap_or(glyph.x) > WORD_GAP * size) && !cell.text.ends_with(' ') {                    cell.text.push(' ');                }                cell.text.push_str(&glyph.text);                cell.x1 = cell.x1.max(glyph.x + glyph.width);            }            word_end = Some(glyph.x + glyph.width);            spaced = false;        }        for cell in &mut cells {            cell.text = cell.text.split_whitespace().collect::<Vec<_>>().join(" ");        }        cells.retain(|cell| !cell.text.is_empty());        if !cells.is_empty() {            lines.push(TextLine { y, size, cells });        }    }    TextPage { lines }}