1use std::path::Path;
21
22use pdf_extract::{Document, MediaBox, OutputDev, OutputError, Transform};
23
24use crate::detect::{Format, Sniff};
25use crate::error::{Error, Result};
26use crate::extract::{ExtractOpts, Extractor, PageRange};
27use crate::model::{Block, Document as Doc, Inline, Metadata};
28
29pub struct PdfExtractor;
30
31impl Extractor for PdfExtractor {
32 fn name(&self) -> &'static str {
33 "pdf"
34 }
35
36 fn supports(&self, _path: &Path, sniff: &Sniff) -> bool {
37 crate::detect::detect(sniff) == Some(Format::Pdf)
38 }
39
40 fn extract(&self, path: &Path, opts: &ExtractOpts) -> Result<Doc> {
41 let bytes = std::fs::read(path).map_err(|e| Error::io(path, e))?;
42 let parsed = parse(&bytes, opts.pages).map_err(|m| Error::parse(path, m))?;
43
44 let mut meta = parsed.meta;
45 meta.source_format = Some(Format::Pdf);
46 meta.source_path = Some(path.display().to_string());
47
48 Ok(Doc {
49 meta,
50 blocks: parsed.blocks,
51 })
52 }
53}
54
55#[derive(Debug, Default, PartialEq)]
57pub struct Parsed {
58 pub meta: Metadata,
59 pub blocks: Vec<Block>,
60}
61
62pub fn parse(bytes: &[u8], pages: Option<PageRange>) -> std::result::Result<Parsed, String> {
64 let document = Document::load_mem(bytes).map_err(|e| e.to_string())?;
65
66 let numbers: Vec<u32> = document
67 .get_pages()
68 .keys()
69 .copied()
70 .filter(|number| pages.is_none_or(|range| range.contains(*number)))
71 .collect();
72
73 let mut collector = Collector::default();
74 for number in &numbers {
75 let _ = pdf_extract::output_doc_page(&document, &mut collector, *number);
77 }
78
79 let mut blocks = Vec::new();
80 for page in collector.pages {
81 if page.number != numbers.first().copied().unwrap_or(1) {
82 blocks.push(Block::PageBreak { page: page.number });
83 }
84 blocks.extend(page_blocks(&page.characters));
85 }
86
87 Ok(Parsed {
88 meta: metadata(&document),
89 blocks,
90 })
91}
92
93#[derive(Debug, Clone)]
97struct Glyph {
98 x: f64,
99 y: f64,
101 size: f64,
102 end: f64,
104 text: String,
105}
106
107struct PageGlyphs {
108 number: u32,
109 characters: Vec<Glyph>,
110}
111
112#[derive(Default)]
113struct Collector {
114 pages: Vec<PageGlyphs>,
115 current: Vec<Glyph>,
116 number: u32,
117 flip: Transform,
118}
119
120impl OutputDev for Collector {
121 fn begin_page(
122 &mut self,
123 page_num: u32,
124 media_box: &MediaBox,
125 _art_box: Option<(f64, f64, f64, f64)>,
126 ) -> std::result::Result<(), OutputError> {
127 self.number = page_num;
128 self.current = Vec::new();
129 self.flip = Transform::row_major(1., 0., 0., -1., 0., media_box.ury - media_box.lly);
132 Ok(())
133 }
134
135 fn end_page(&mut self) -> std::result::Result<(), OutputError> {
136 self.pages.push(PageGlyphs {
137 number: self.number,
138 characters: std::mem::take(&mut self.current),
139 });
140 Ok(())
141 }
142
143 fn output_character(
144 &mut self,
145 trm: &Transform,
146 width: f64,
147 _spacing: f64,
148 font_size: f64,
149 char: &str,
150 ) -> std::result::Result<(), OutputError> {
151 let position = trm.post_transform(&self.flip);
152
153 let width_vector = font_size * (trm.m11 + trm.m21);
159 let height_vector = font_size * (trm.m12 + trm.m22);
160 let size = (width_vector * height_vector).abs().sqrt();
161
162 let x = position.m31;
163 self.current.push(Glyph {
164 x,
165 y: position.m32,
166 size,
167 end: x + width * size,
168 text: char.to_string(),
169 });
170 Ok(())
171 }
172
173 fn begin_word(&mut self) -> std::result::Result<(), OutputError> {
174 Ok(())
175 }
176
177 fn end_word(&mut self) -> std::result::Result<(), OutputError> {
178 Ok(())
179 }
180
181 fn end_line(&mut self) -> std::result::Result<(), OutputError> {
182 Ok(())
183 }
184}
185
186#[derive(Debug, Clone, PartialEq)]
190pub struct Line {
191 pub text: String,
192 pub x: f64,
193 pub right: f64,
194 pub y: f64,
195 pub size: f64,
196}
197
198fn page_blocks(characters: &[Glyph]) -> Vec<Block> {
203 let body = glyph_size(characters);
204
205 let regions: Vec<Vec<Line>> = segment(characters, body, 0)
206 .iter()
207 .map(|glyphs| lines(glyphs))
208 .filter(|lines| !lines.is_empty())
209 .collect();
210
211 let all: Vec<Line> = regions.iter().flatten().cloned().collect();
212 if all.is_empty() {
213 return Vec::new();
214 }
215 let body_size = body_size(&all);
216
217 regions
218 .iter()
219 .flat_map(|region| paragraphs(region, body_size))
220 .collect()
221}
222
223fn segment(characters: &[Glyph], body: f64, depth: usize) -> Vec<Vec<Glyph>> {
230 let single = || vec![characters.to_vec()];
231 if depth >= 6 || characters.len() < 40 {
233 return single();
234 }
235
236 if let Some((top, bottom)) = split_horizontally(characters, body) {
237 let mut regions = segment(&top, body, depth + 1);
238 regions.extend(segment(&bottom, body, depth + 1));
239 return regions;
240 }
241
242 match split_vertically(characters, body) {
243 Some(columns) => columns
244 .iter()
245 .flat_map(|column| segment(column, body, depth + 1))
246 .collect(),
247 None => single(),
248 }
249}
250
251fn split_horizontally(characters: &[Glyph], body: f64) -> Option<(Vec<Glyph>, Vec<Glyph>)> {
253 let mut baselines: Vec<f64> = characters.iter().map(|glyph| glyph.y).collect();
254 baselines.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
255 baselines.dedup_by(|a, b| (*a - *b).abs() < body * 0.5);
256
257 let threshold = body * 2.5;
259 let cut = baselines
260 .windows(2)
261 .find(|pair| pair[1] - pair[0] > threshold)
262 .map(|pair| (pair[0] + pair[1]) / 2.0)?;
263
264 let (top, bottom): (Vec<Glyph>, Vec<Glyph>) =
265 characters.iter().cloned().partition(|glyph| glyph.y < cut);
266 (!top.is_empty() && !bottom.is_empty()).then_some((top, bottom))
267}
268
269fn split_vertically(characters: &[Glyph], body: f64) -> Option<Vec<Vec<Glyph>>> {
271 let spans: Vec<(f64, f64)> = characters.iter().map(|g| (g.x, g.end)).collect();
272 let bounds = column_bounds(&spans, body);
273 if bounds.len() < 2 {
274 return None;
275 }
276
277 let mut columns: Vec<Vec<Glyph>> = vec![Vec::new(); bounds.len()];
278 for glyph in characters {
279 let index = bounds
280 .iter()
281 .position(|(start, end)| glyph.x >= *start && glyph.x <= *end)
282 .unwrap_or(0);
283 columns[index].push(glyph.clone());
284 }
285
286 let minimum = (characters.len() / 10).max(20);
288 columns
289 .iter()
290 .all(|column| column.len() >= minimum)
291 .then_some(columns)
292}
293
294fn glyph_size(characters: &[Glyph]) -> f64 {
297 if characters.is_empty() {
298 return 0.0;
299 }
300 let mut sizes: Vec<f64> = characters.iter().map(|glyph| glyph.size).collect();
301 sizes.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
302 sizes[sizes.len() / 2]
303}
304
305fn lines(characters: &[Glyph]) -> Vec<Line> {
307 if characters.is_empty() {
308 return Vec::new();
309 }
310
311 let mut sorted = characters.to_vec();
312 sorted.sort_by(|a, b| {
313 a.y.partial_cmp(&b.y)
314 .unwrap_or(std::cmp::Ordering::Equal)
315 .then(a.x.partial_cmp(&b.x).unwrap_or(std::cmp::Ordering::Equal))
316 });
317
318 let mut lines: Vec<Vec<Glyph>> = Vec::new();
319 for glyph in sorted {
320 let same_line = lines.last().is_some_and(|line| {
323 line.last()
324 .is_some_and(|last| (glyph.y - last.y).abs() <= last.size.max(glyph.size) * 0.5)
325 });
326 if same_line {
327 lines.last_mut().expect("checked").push(glyph);
328 } else {
329 lines.push(vec![glyph]);
330 }
331 }
332
333 lines.iter().filter_map(|line| assemble(line)).collect()
334}
335
336fn assemble(characters: &[Glyph]) -> Option<Line> {
338 let mut sorted = characters.to_vec();
339 sorted.sort_by(|a, b| a.x.partial_cmp(&b.x).unwrap_or(std::cmp::Ordering::Equal));
340
341 let mut text = String::new();
342 let mut previous_end: Option<f64> = None;
343 for glyph in &sorted {
344 if let Some(end) = previous_end
345 && glyph.x > end + glyph.size * 0.2
346 && !text.ends_with(' ')
347 && !glyph.text.starts_with(' ')
348 {
349 text.push(' ');
350 }
351 text.push_str(&glyph.text);
352 previous_end = Some(glyph.end);
353 }
354
355 let text = text.trim().to_string();
356 if text.is_empty() {
357 return None;
358 }
359
360 let size = sorted
363 .iter()
364 .map(|glyph| glyph.size)
365 .fold(0.0f64, f64::max)
366 .max(1.0);
367
368 Some(Line {
369 text,
370 x: sorted.first()?.x,
371 right: sorted.iter().map(|g| g.end).fold(f64::MIN, f64::max),
372 y: sorted.first()?.y,
373 size,
374 })
375}
376
377pub fn column_bounds(spans: &[(f64, f64)], body_size: f64) -> Vec<(f64, f64)> {
382 if spans.is_empty() {
383 return Vec::new();
384 }
385
386 let mut spans = spans.to_vec();
387 spans.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap_or(std::cmp::Ordering::Equal));
388
389 let mut merged: Vec<(f64, f64)> = Vec::new();
390 for (start, end) in spans {
391 match merged.last_mut() {
392 Some(last) if start <= last.1 => last.1 = last.1.max(end),
393 _ => merged.push((start, end)),
394 }
395 }
396
397 let width = merged.last().map(|span| span.1).unwrap_or_default() - merged[0].0;
398 let gutter = (width * 0.04).max(body_size * 2.0);
399
400 let mut bounds: Vec<(f64, f64)> = vec![merged[0]];
401 for span in &merged[1..] {
402 let last = bounds.last_mut().expect("seeded above");
403 if span.0 - last.1 >= gutter {
404 bounds.push(*span);
405 } else {
406 last.1 = last.1.max(span.1);
407 }
408 }
409 bounds
410}
411
412fn paragraphs(lines: &[Line], body_size: f64) -> Vec<Block> {
414 let column_right = lines.iter().map(|line| line.right).fold(f64::MIN, f64::max);
415
416 let mut blocks = Vec::new();
417 let mut current: Vec<&Line> = Vec::new();
418
419 for line in lines {
420 let starts_new = match current.last() {
421 None => true,
422 Some(previous) => {
423 let gap = line.y - previous.y;
424 gap > previous.size * 1.8
427 || previous.right < column_right - previous.size * 2.0
428 || (line.size - previous.size).abs() > previous.size * 0.2
429 }
430 };
431
432 if starts_new && !current.is_empty() {
433 blocks.push(block(¤t, body_size));
434 current.clear();
435 }
436 current.push(line);
437 }
438 if !current.is_empty() {
439 blocks.push(block(¤t, body_size));
440 }
441
442 blocks
443}
444
445fn block(lines: &[&Line], body_size: f64) -> Block {
447 let mut text = String::new();
448 for line in lines {
449 if text.is_empty() {
450 text.push_str(&line.text);
451 continue;
452 }
453 if let Some(stem) = text.strip_suffix('-')
455 && stem.ends_with(char::is_alphabetic)
456 && line.text.starts_with(char::is_lowercase)
457 {
458 text = stem.to_string();
459 text.push_str(&line.text);
460 } else {
461 text.push(' ');
462 text.push_str(&line.text);
463 }
464 }
465
466 let size = lines.iter().map(|line| line.size).fold(0.0f64, f64::max);
467 match heading_level(size, body_size, lines.len(), &text) {
468 Some(level) => Block::Heading {
469 level,
470 text: Inline::text(text),
471 },
472 None => Block::Paragraph {
473 text: Inline::text(text),
474 },
475 }
476}
477
478fn heading_level(size: f64, body_size: f64, line_count: usize, text: &str) -> Option<u8> {
481 if body_size <= 0.0 || line_count > 2 || text.chars().count() > 120 {
482 return None;
483 }
484 let ratio = size / body_size;
485 match ratio {
486 r if r >= 1.7 => Some(1),
487 r if r >= 1.35 => Some(2),
488 r if r >= 1.15 => Some(3),
489 _ => None,
490 }
491}
492
493fn body_size(lines: &[Line]) -> f64 {
498 let mut buckets: Vec<(f64, usize)> = Vec::new();
499
500 for line in lines {
501 let key = (line.size * 2.0).round() / 2.0;
503 let characters = line.text.chars().count();
504 match buckets.iter_mut().find(|(size, _)| *size == key) {
505 Some(bucket) => bucket.1 += characters,
506 None => buckets.push((key, characters)),
507 }
508 }
509
510 buckets
511 .into_iter()
512 .max_by_key(|(_, characters)| *characters)
513 .map(|(size, _)| size)
514 .unwrap_or(0.0)
515}
516
517fn metadata(document: &Document) -> Metadata {
521 let mut meta = Metadata {
522 page_count: Some(document.get_pages().len() as u32),
523 ..Metadata::default()
524 };
525
526 let Some(info) = document
527 .trailer
528 .get(b"Info")
529 .ok()
530 .and_then(|object| document.dereference(object).ok())
531 .and_then(|(_, object)| object.as_dict().ok())
532 else {
533 return meta;
534 };
535
536 let text_of = |key: &[u8]| {
537 info.get(key)
538 .ok()
539 .and_then(|object| object.as_str().ok())
540 .map(decode_text_string)
541 .map(|text| text.trim().to_string())
542 .filter(|text| !text.is_empty())
543 };
544
545 meta.title = text_of(b"Title");
546 meta.author = text_of(b"Author");
547 meta.created = text_of(b"CreationDate").as_deref().and_then(pdf_date);
548 meta
549}
550
551fn decode_text_string(bytes: &[u8]) -> String {
554 if bytes.starts_with(&[0xfe, 0xff]) {
555 let units: Vec<u16> = bytes[2..]
556 .chunks_exact(2)
557 .map(|pair| u16::from_be_bytes([pair[0], pair[1]]))
558 .collect();
559 return String::from_utf16_lossy(&units);
560 }
561 bytes.iter().map(|byte| char::from(*byte)).collect()
562}
563
564fn pdf_date(value: &str) -> Option<String> {
566 let digits: String = value
567 .trim_start_matches("D:")
568 .chars()
569 .take_while(char::is_ascii_digit)
570 .collect();
571 if digits.len() < 8 {
572 return None;
573 }
574 Some(format!(
575 "{}-{}-{}",
576 &digits[0..4],
577 &digits[4..6],
578 &digits[6..8]
579 ))
580}
581
582#[cfg(test)]
583mod tests {
584 use super::*;
585
586 fn line(text: &str, x: f64, right: f64, y: f64, size: f64) -> Line {
587 Line {
588 text: text.to_string(),
589 x,
590 right,
591 y,
592 size,
593 }
594 }
595
596 #[test]
597 fn lines_join_into_a_paragraph_until_the_gap_widens() {
598 let lines = [
599 line(
600 "Revenue grew twelve per cent quarter",
601 72.0,
602 500.0,
603 100.0,
604 10.0,
605 ),
606 line("over quarter, driven by cloud.", 72.0, 300.0, 112.0, 10.0),
607 line("A separate thought entirely.", 72.0, 320.0, 160.0, 10.0),
608 ];
609
610 assert_eq!(
611 paragraphs(&lines, 10.0),
612 vec![
613 Block::paragraph(
614 "Revenue grew twelve per cent quarter over quarter, driven by cloud."
615 ),
616 Block::paragraph("A separate thought entirely."),
617 ]
618 );
619 }
620
621 #[test]
622 fn a_word_broken_across_lines_is_rejoined() {
623 let lines = [
624 line("The extraordinary quarterly per-", 72.0, 500.0, 100.0, 10.0),
625 line("formance continued.", 72.0, 300.0, 112.0, 10.0),
626 ];
627 assert_eq!(
628 paragraphs(&lines, 10.0),
629 vec![Block::paragraph(
630 "The extraordinary quarterly performance continued."
631 )]
632 );
633 }
634
635 #[test]
636 fn larger_type_becomes_a_heading() {
637 let lines = [
638 line("Quarterly Report", 72.0, 300.0, 60.0, 24.0),
639 line("Summary", 72.0, 200.0, 90.0, 14.0),
640 line("Revenue grew.", 72.0, 400.0, 120.0, 10.0),
641 line("Cash flow held.", 72.0, 400.0, 132.0, 10.0),
642 ];
643
644 assert_eq!(
645 paragraphs(&lines, 10.0),
646 vec![
647 Block::Heading {
648 level: 1,
649 text: Inline::text("Quarterly Report")
650 },
651 Block::Heading {
652 level: 2,
653 text: Inline::text("Summary")
654 },
655 Block::paragraph("Revenue grew. Cash flow held."),
656 ]
657 );
658 }
659
660 #[test]
661 fn headings_stay_conservative() {
662 assert_eq!(heading_level(10.0, 10.0, 1, "Short"), None);
664 let long = "x".repeat(200);
666 assert_eq!(heading_level(24.0, 10.0, 1, &long), None);
667 assert_eq!(heading_level(24.0, 10.0, 1, "Short"), Some(1));
669 }
670
671 #[test]
672 fn a_gutter_splits_the_page_into_columns() {
673 let mut spans: Vec<(f64, f64)> = (0..6).map(|_| (72.0, 280.0)).collect();
675 spans.extend((0..6).map(|_| (330.0, 530.0)));
676
677 let bounds = column_bounds(&spans, 10.0);
678 assert_eq!(bounds.len(), 2, "expected two columns: {bounds:?}");
679 assert!(bounds[0].1 < bounds[1].0);
680 }
681
682 #[test]
683 fn a_single_column_page_stays_one_flow() {
684 let spans: Vec<(f64, f64)> = (0..8).map(|_| (72.0, 530.0)).collect();
685 assert_eq!(column_bounds(&spans, 10.0).len(), 1);
686 }
687
688 #[test]
689 fn an_ordinary_word_space_is_not_a_gutter() {
690 let spans = [(72.0, 200.0), (205.0, 330.0), (336.0, 530.0)];
692 assert_eq!(column_bounds(&spans, 10.0).len(), 1);
693 }
694
695 fn glyph(x: f64, y: f64, size: f64) -> Glyph {
696 Glyph {
697 x,
698 y,
699 size,
700 end: x + size * 0.5,
701 text: "x".to_string(),
702 }
703 }
704
705 #[test]
706 fn a_wide_vertical_gap_starts_a_new_band() {
707 let mut characters: Vec<Glyph> = Vec::new();
709 for row in 0..3 {
710 for column in 0..10 {
711 characters.push(glyph(
712 72.0 + column as f64 * 6.0,
713 100.0 + row as f64 * 12.0,
714 10.0,
715 ));
716 }
717 }
718 for row in 0..3 {
719 for column in 0..10 {
720 characters.push(glyph(
721 72.0 + column as f64 * 6.0,
722 300.0 + row as f64 * 12.0,
723 10.0,
724 ));
725 }
726 }
727
728 let (top, bottom) = split_horizontally(&characters, 10.0).expect("a band boundary");
729 assert_eq!(top.len(), 30);
730 assert_eq!(bottom.len(), 30);
731 }
732
733 #[test]
734 fn ordinary_line_spacing_is_not_a_band_boundary() {
735 let characters: Vec<Glyph> = (0..6)
736 .flat_map(|row| {
737 (0..10).map(move |column| {
738 glyph(72.0 + column as f64 * 6.0, 100.0 + row as f64 * 12.0, 10.0)
739 })
740 })
741 .collect();
742 assert!(split_horizontally(&characters, 10.0).is_none());
743 }
744
745 #[test]
746 fn decodes_pdf_text_strings() {
747 assert_eq!(decode_text_string(b"Plain"), "Plain");
748 let utf16: Vec<u8> = [0xfe, 0xff, 0x00, 0x48, 0x00, 0x69].to_vec();
749 assert_eq!(decode_text_string(&utf16), "Hi");
750 }
751
752 #[test]
753 fn parses_pdf_dates() {
754 assert_eq!(
755 pdf_date("D:20260724103000+02'00'").as_deref(),
756 Some("2026-07-24")
757 );
758 assert_eq!(pdf_date("20260724").as_deref(), Some("2026-07-24"));
759 assert_eq!(pdf_date("D:2026").as_deref(), None);
760 }
761}