Skip to main content

pdf/read/
text.rs

1// The text of a page (ISO 32000-1, 9.4): the content stream is interpreted for its text
2// state (fonts, sizes, the text and line matrices, character and word spacing, horizontal
3// scaling, rise, the current transformation matrix with q / Q and cm, form XObjects with their
4// own matrix and resources), and every glyph shown becomes a TextItem with its text, origin and
5// advance in page space.  PageText::text lays them out as Poppler's pdftotext -raw does: in the
6// order the page draws them, a new line where the baseline moves by more than half the font
7// size, a space where a gap is wider than 0.15 of it (0.08 after a space glyph; a space glyph
8// that leaves no gap is no space; a glyph without text leaves a gap), a glyph drawn again on
9// one of the last 64 (fake bold, a word printed twice) once, a run of Hebrew or Arabic drawn
10// left to right in reading order.
11
12use super::content::Ops;
13use super::font::Font;
14use super::object::{Dict, Object, Ref};
15use super::{Document, Error};
16use alloc::collections::BTreeMap;
17use alloc::rc::Rc;
18use alloc::string::String;
19use alloc::vec::Vec;
20
21/// one glyph shown on a page
22#[derive(Clone, Debug, PartialEq)]
23pub struct TextItem {
24    /// the characters the glyph stands for (usually one; empty when the font does not say)
25    pub text: String,
26    /// where the glyph starts on its baseline, in page space (points, y up, before /Rotate)
27    pub x: f64,
28    pub y: f64,
29    /// how far the glyph moves the pen, in page space (along the baseline; with character and
30    /// word spacing)
31    pub dx: f64,
32    pub dy: f64,
33    /// the glyph's own width along the baseline in page space (without the spacing)
34    pub width: f64,
35    /// the font size in page space
36    pub size: f64,
37    /// which of PageText::fonts
38    pub font: u16,
39    /// render mode 3: drawn invisibly (the text layer of a scan)
40    pub invisible: bool,
41}
42
43/// the glyphs of a page and the names of their fonts
44#[derive(Clone, Debug, Default, PartialEq)]
45pub struct PageText {
46    pub items: Vec<TextItem>,
47    pub fonts: Vec<String>,
48}
49
50type M = [f64; 6];
51const ID: M = [1.0, 0.0, 0.0, 1.0, 0.0, 0.0];
52
53/// a × b (a first, then b)
54fn mul(a: &M, b: &M) -> M {
55    [
56        a[0] * b[0] + a[1] * b[2],
57        a[0] * b[1] + a[1] * b[3],
58        a[2] * b[0] + a[3] * b[2],
59        a[2] * b[1] + a[3] * b[3],
60        a[4] * b[0] + a[5] * b[2] + b[4],
61        a[4] * b[1] + a[5] * b[3] + b[5],
62    ]
63}
64
65/// a square root for lengths (no std here): Newton's method from the halved exponent
66fn sqrt(x: f64) -> f64 {
67    if x.is_nan() || x <= 0.0 || x.is_infinite() {
68        return if x.is_infinite() && x > 0.0 { x } else { 0.0 };
69    }
70    let mut r = f64::from_bits((x.to_bits() >> 1) + 0x1FF8_0000_0000_0000);
71    for _ in 0..6 {
72        r = 0.5 * (r + x / r);
73    }
74    r
75}
76
77fn finite(m: M) -> M {
78    if m.iter().all(|v| v.is_finite()) { m } else { ID }
79}
80
81#[derive(Clone)]
82struct GState {
83    ctm: M,
84    font: Option<(Rc<Font>, u16)>,
85    size: f64,
86    tc: f64,
87    tw: f64,
88    th: f64,
89    tl: f64,
90    rise: f64,
91    mode: i64,
92}
93
94/// form XObjects inside each other
95const MAX_FORMS: usize = 12;
96/// q without Q
97const MAX_STACK: usize = 256;
98/// the glyphs of one page
99const MAX_ITEMS: usize = 1 << 22;
100/// the operators run for one page, form XObjects counted each time they are drawn (forms
101/// that draw each other many times would otherwise take time without end)
102const MAX_OPS: u64 = 1 << 23;
103/// a content stream costs an operator for this many of its bytes each time it is read
104const BYTES_PER_OP: usize = 64;
105
106/// the resources a content stream uses here, resolved once
107struct Res {
108    fonts: Dict,
109    xobjects: Dict,
110}
111
112impl Res {
113    fn of(doc: &Document, res: &Dict) -> Res {
114        let get = |k: &str| res.get(k).map(|o| doc.dict(o)).unwrap_or_default();
115        Res { fonts: get("Font"), xobjects: get("XObject") }
116    }
117}
118
119/// a form XObject: its content, resources and matrix, decoded once per page
120struct Form {
121    data: Vec<u8>,
122    res: Option<Rc<Res>>,
123    matrix: Option<M>,
124}
125
126struct Run<'d> {
127    doc: &'d Document,
128    fonts: BTreeMap<Ref, (Rc<Font>, u16)>,
129    out: PageText,
130    forms: Vec<Ref>,
131    /// the form XObjects drawn so far (None: not a form, or not to be decoded)
132    form_cache: BTreeMap<Ref, Option<Rc<Form>>>,
133    ops: u64,
134    codes: Vec<(u32, u8)>,
135}
136
137fn nums(ops: &[Object]) -> Vec<f64> {
138    ops.iter().map(|o| o.as_f64().unwrap_or(0.0)).collect()
139}
140
141impl Run<'_> {
142    fn font(&mut self, fonts: &Dict, name: &[u8]) -> Option<(Rc<Font>, u16)> {
143        let o = fonts.get_bytes(name)?;
144        if let Some(r) = o.as_ref() {
145            if let Some(f) = self.fonts.get(&r) {
146                return Some(f.clone());
147            }
148        }
149        let d = self.doc.dict(o);
150        if d.is_empty() {
151            return None;
152        }
153        let f = Rc::new(Font::load(self.doc, &d));
154        let idx = self.out.fonts.len().min(u16::MAX as usize) as u16;
155        self.out.fonts.push(f.name.clone());
156        let entry = (f, idx);
157        if let Some(r) = o.as_ref() {
158            self.fonts.insert(r, entry.clone());
159        }
160        Some(entry)
161    }
162
163    fn show(&mut self, gs: &GState, tm: &mut M, s: &[u8]) {
164        let Some((font, fi)) = gs.font.clone() else { return };
165        let mut codes = core::mem::take(&mut self.codes);
166        font.codes(s, &mut codes);
167        for &(code, len) in &codes {
168            let w0 = font.width(code);
169            let trm = mul(&[gs.size * gs.th, 0.0, 0.0, gs.size, 0.0, gs.rise], &mul(tm, &gs.ctm));
170            let space = if len == 1 && code == 32 { gs.tw } else { 0.0 };
171            let (tx, ty) = if font.vertical { (0.0, w0 * gs.size + gs.tc + space) } else { ((w0 * gs.size + gs.tc + space) * gs.th, 0.0) };
172            let m = mul(tm, &gs.ctm);
173            let (dx, dy) = (tx * m[0] + ty * m[2], tx * m[1] + ty * m[3]);
174            let own = if font.vertical { w0 * gs.size * sqrt(m[2] * m[2] + m[3] * m[3]) } else { w0 * gs.size * gs.th * sqrt(m[0] * m[0] + m[1] * m[1]) };
175            let size = (gs.size * sqrt(m[2] * m[2] + m[3] * m[3])).abs();
176            if self.out.items.len() < MAX_ITEMS && size.is_finite() {
177                self.out.items.push(TextItem {
178                    text: font.text(code).unwrap_or_default(),
179                    x: trm[4],
180                    y: trm[5],
181                    dx,
182                    dy,
183                    width: own.abs(),
184                    size,
185                    font: fi,
186                    invisible: gs.mode == 3 || gs.mode == 7,
187                });
188            }
189            *tm = finite(mul(&[1.0, 0.0, 0.0, 1.0, tx, ty], tm));
190        }
191        self.codes = codes;
192    }
193
194    /// a form XObject by its reference (or a direct one), from the cache
195    fn form(&mut self, o: &Object) -> Option<Rc<Form>> {
196        let r = o.as_ref();
197        if let Some(f) = r.and_then(|r| self.form_cache.get(&r)) {
198            return f.clone();
199        }
200        let built = match self.doc.resolve(o) {
201            Object::Stream(s) if s.dict.is("Subtype", "Form") => self.doc.decode(&s).ok().map(|data| {
202                let res = s.dict.get("Resources").map(|x| Rc::new(Res::of(self.doc, &self.doc.dict(x))));
203                let matrix = self.doc.key(&s.dict, "Matrix").as_array().map(nums).filter(|n| n.len() >= 6).map(|n| [n[0], n[1], n[2], n[3], n[4], n[5]]);
204                Rc::new(Form { data, res, matrix })
205            }),
206            _ => None,
207        };
208        if let Some(r) = r {
209            self.form_cache.insert(r, built.clone());
210        }
211        built
212    }
213
214    fn run(&mut self, content: &[u8], res: &Rc<Res>, gs0: GState) {
215        // the bytes read count too: a form of a megabyte of white space drawn a million times
216        // has no operators but takes as long to read
217        self.ops += (content.len() / BYTES_PER_OP) as u64;
218        if self.ops > MAX_OPS {
219            return;
220        }
221        let mut gs = gs0;
222        let mut stack: Vec<GState> = Vec::new();
223        let mut extra_q = 0usize;
224        let (mut tm, mut tlm) = (ID, ID);
225        for op in Ops::new(content) {
226            self.ops += 1;
227            if self.ops > MAX_OPS {
228                return;
229            }
230            let a = &op.operands;
231            match op.operator {
232                b"q" => {
233                    if stack.len() < MAX_STACK {
234                        stack.push(gs.clone());
235                    } else {
236                        extra_q += 1;
237                    }
238                }
239                b"Q" => {
240                    if extra_q > 0 {
241                        extra_q -= 1;
242                    } else if let Some(g) = stack.pop() {
243                        gs = g;
244                    }
245                }
246                b"cm" if a.len() >= 6 => {
247                    let n = nums(&a[a.len() - 6..]);
248                    gs.ctm = finite(mul(&[n[0], n[1], n[2], n[3], n[4], n[5]], &gs.ctm));
249                }
250                b"BT" => {
251                    tm = ID;
252                    tlm = ID;
253                }
254                b"Tf" if a.len() >= 2 => {
255                    if let Some(n) = a[a.len() - 2].as_name() {
256                        let n = n.to_vec();
257                        gs.font = self.font(&res.fonts, &n);
258                    }
259                    gs.size = a[a.len() - 1].as_f64().unwrap_or(0.0);
260                }
261                b"Tc" if !a.is_empty() => gs.tc = a[0].as_f64().unwrap_or(0.0),
262                b"Tw" if !a.is_empty() => gs.tw = a[0].as_f64().unwrap_or(0.0),
263                b"Tz" if !a.is_empty() => gs.th = a[0].as_f64().unwrap_or(100.0) / 100.0,
264                b"TL" if !a.is_empty() => gs.tl = a[0].as_f64().unwrap_or(0.0),
265                b"Ts" if !a.is_empty() => gs.rise = a[0].as_f64().unwrap_or(0.0),
266                b"Tr" if !a.is_empty() => gs.mode = a[0].as_int().unwrap_or(0),
267                b"Td" | b"TD" if a.len() >= 2 => {
268                    let (x, y) = (a[0].as_f64().unwrap_or(0.0), a[1].as_f64().unwrap_or(0.0));
269                    if op.operator == b"TD" {
270                        gs.tl = -y;
271                    }
272                    tlm = finite(mul(&[1.0, 0.0, 0.0, 1.0, x, y], &tlm));
273                    tm = tlm;
274                }
275                b"Tm" if a.len() >= 6 => {
276                    let n = nums(&a[a.len() - 6..]);
277                    tlm = finite([n[0], n[1], n[2], n[3], n[4], n[5]]);
278                    tm = tlm;
279                }
280                b"T*" => {
281                    tlm = finite(mul(&[1.0, 0.0, 0.0, 1.0, 0.0, -gs.tl], &tlm));
282                    tm = tlm;
283                }
284                b"Tj" => {
285                    if let Some(s) = a.last().and_then(Object::as_bytes) {
286                        self.show(&gs, &mut tm, s);
287                    }
288                }
289                b"'" | b"\"" => {
290                    if op.operator == b"\"" && a.len() >= 3 {
291                        gs.tw = a[0].as_f64().unwrap_or(0.0);
292                        gs.tc = a[1].as_f64().unwrap_or(0.0);
293                    }
294                    tlm = finite(mul(&[1.0, 0.0, 0.0, 1.0, 0.0, -gs.tl], &tlm));
295                    tm = tlm;
296                    if let Some(s) = a.last().and_then(Object::as_bytes) {
297                        self.show(&gs, &mut tm, s);
298                    }
299                }
300                b"TJ" => {
301                    let Some(arr) = a.last().and_then(Object::as_array) else { continue };
302                    let vertical = gs.font.as_ref().is_some_and(|f| f.0.vertical);
303                    for e in arr {
304                        match e {
305                            Object::String(s) => self.show(&gs, &mut tm, s),
306                            o => {
307                                if let Some(n) = o.as_f64() {
308                                    let adj = -n / 1000.0 * gs.size;
309                                    let t = if vertical { [1.0, 0.0, 0.0, 1.0, 0.0, adj] } else { [1.0, 0.0, 0.0, 1.0, adj * gs.th, 0.0] };
310                                    tm = finite(mul(&t, &tm));
311                                }
312                            }
313                        }
314                    }
315                }
316                b"Do" if !a.is_empty() => {
317                    let Some(o) = a[0].as_name().and_then(|n| res.xobjects.get_bytes(n)).cloned() else { continue };
318                    let r = o.as_ref();
319                    if self.forms.len() >= MAX_FORMS || r.is_some_and(|r| self.forms.contains(&r)) {
320                        continue;
321                    }
322                    let Some(form) = self.form(&o) else { continue };
323                    let mut g = gs.clone();
324                    if let Some(m) = form.matrix {
325                        g.ctm = finite(mul(&m, &g.ctm));
326                    }
327                    let fres = form.res.clone().unwrap_or_else(|| res.clone());
328                    self.forms.push(r.unwrap_or(Ref { num: u32::MAX, generation: 0 }));
329                    self.run(&form.data, &fres, g);
330                    self.forms.pop();
331                }
332                _ => {}
333            }
334        }
335    }
336}
337
338impl Document {
339    /// the glyphs of a page, in the order the page draws them
340    pub fn page_text(&self, page: usize) -> Result<PageText, Error> {
341        let p = self.page(page)?;
342        let content = self.contents(page)?;
343        let res = Rc::new(Res::of(self, &p.resources));
344        let mut run = Run { doc: self, fonts: BTreeMap::new(), out: PageText::default(), forms: Vec::new(), form_cache: BTreeMap::new(), ops: 0, codes: Vec::new() };
345        let gs = GState { ctm: ID, font: None, size: 0.0, tc: 0.0, tw: 0.0, th: 1.0, tl: 0.0, rise: 0.0, mode: 0 };
346        run.run(&content, &res, gs);
347        Ok(run.out)
348    }
349
350    /// the text of a page in reading order (PageText::text)
351    pub fn text(&self, page: usize) -> Result<String, Error> {
352        Ok(self.page_text(page)?.text())
353    }
354}
355
356/// a letter of a right-to-left script (Hebrew, Arabic, Syriac, Thaana, N'Ko and their
357/// presentation forms)
358fn rtl(c: char) -> bool {
359    matches!(c as u32, 0x0590..=0x08FF | 0xFB1D..=0xFDFF | 0xFE70..=0xFEFF | 0x10800..=0x10FFF | 0x1E800..=0x1EFFF)
360}
361
362/// a piece of a line: text and where it starts along the line
363struct Piece {
364    text: String,
365    pos: f64,
366}
367
368fn piece_rtl(p: &Piece) -> bool {
369    p.text.chars().next().is_some_and(rtl)
370}
371
372/// right-to-left runs drawn left to right (the visual order) turned into reading order; a
373/// number or other neutral run inside keeps its own order
374fn reorder(line: &mut [Piece]) {
375    let is_ltr = |p: &Piece| p.text.chars().any(|c| c.is_alphabetic() && !rtl(c));
376    let mut i = 0;
377    while i < line.len() {
378        if !piece_rtl(&line[i]) {
379            i += 1;
380            continue;
381        }
382        // the run: from this RTL piece to the last RTL piece before an LTR letter
383        let start = i;
384        let mut end = i;
385        let mut j = i + 1;
386        while j < line.len() && !is_ltr(&line[j]) {
387            if piece_rtl(&line[j]) {
388                end = j;
389            }
390            j += 1;
391        }
392        let run = &mut line[start..=end];
393        if run.len() > 1 && run[0].pos < run[run.len() - 1].pos {
394            // units: single RTL pieces, and blocks of the others in their own order
395            let mut units: Vec<Vec<Piece>> = Vec::new();
396            for p in run.iter_mut().map(|p| Piece { text: core::mem::take(&mut p.text), pos: p.pos }) {
397                let r = piece_rtl(&p);
398                match units.last_mut() {
399                    Some(u) if !r && !piece_rtl(&u[0]) => u.push(p),
400                    _ => units.push(alloc::vec![p]),
401                }
402            }
403            units.reverse();
404            for (slot, p) in run.iter_mut().zip(units.into_iter().flatten()) {
405                *slot = p;
406            }
407        }
408        i = end + 1;
409    }
410}
411
412impl PageText {
413    /// the text: lines in the order the page draws them, words apart where the glyphs are,
414    /// right-to-left runs in reading order
415    pub fn text(&self) -> String {
416        let mut lines: Vec<Vec<Piece>> = Vec::new();
417        let mut cur: Vec<Piece> = Vec::new();
418        let mut prev: Option<&TextItem> = None;
419        // where the line starts and its direction
420        let mut origin = (0.0, 0.0, 1.0, 0.0);
421        // a space glyph since the last glyph: a word ends if it made a gap at all
422        let mut spaced = false;
423        // the last glyphs with text, for glyphs drawn twice
424        let mut recent: Vec<&TextItem> = Vec::new();
425        for it in &self.items {
426            if it.text.is_empty() {
427                // a glyph the font gives no text for leaves a gap, as in Poppler
428                continue;
429            }
430            if it.text.chars().all(|c| c == ' ' || c == '\u{A0}') {
431                spaced = true;
432                continue;
433            }
434            let tol = 0.1 * it.size.max(1e-6);
435            if recent.iter().any(|r| r.text == it.text && (r.x - it.x).abs() < tol && (r.y - it.y).abs() < tol) {
436                continue;
437            }
438            if recent.len() == 64 {
439                recent.remove(0);
440            }
441            recent.push(it);
442            let mut new_line = prev.is_none();
443            if let Some(p) = prev {
444                let len = sqrt(p.dx * p.dx + p.dy * p.dy);
445                let (ux, uy) = if len > 1e-9 { (p.dx / len, p.dy / len) } else { (1.0, 0.0) };
446                let (rx, ry) = (it.x - (p.x + ux * p.width), it.y - (p.y + uy * p.width));
447                let along = rx * ux + ry * uy;
448                let across = ux * ry - uy * rx;
449                let size = p.size.max(it.size).max(1e-6);
450                let ilen = sqrt(it.dx * it.dx + it.dy * it.dy);
451                let same_dir = ilen < 1e-9 || len < 1e-9 || (it.dx * ux + it.dy * uy) / ilen > 0.9;
452                if !same_dir || across.abs() > 0.5 * size || along < -size * 1.5 {
453                    new_line = true;
454                } else if along > if spaced { 0.08 } else { 0.15 } * size && !cur.last().is_some_and(|l| l.text.ends_with(' ')) && !it.text.starts_with(' ') {
455                    let pos = (it.x - origin.0) * origin.2 + (it.y - origin.1) * origin.3;
456                    cur.push(Piece { text: String::from(" "), pos: pos - 1e-3 });
457                }
458            }
459            if new_line {
460                if !cur.is_empty() {
461                    lines.push(core::mem::take(&mut cur));
462                }
463                let len = sqrt(it.dx * it.dx + it.dy * it.dy);
464                let (ux, uy) = if len > 1e-9 { (it.dx / len, it.dy / len) } else { (1.0, 0.0) };
465                origin = (it.x, it.y, ux, uy);
466            }
467            let pos = (it.x - origin.0) * origin.2 + (it.y - origin.1) * origin.3;
468            cur.push(Piece { text: it.text.clone(), pos });
469            prev = Some(it);
470            spaced = false;
471        }
472        if !cur.is_empty() {
473            lines.push(cur);
474        }
475        let mut out = String::new();
476        for mut l in lines {
477            if l.iter().any(|p| p.text.chars().any(rtl)) {
478                reorder(&mut l);
479            }
480            for p in l {
481                out.push_str(&p.text);
482            }
483            out.push('\n');
484        }
485        out
486    }
487}