pdfsink-rs 0.2.4

Native pure-Rust PDF extraction crate inspired by pdfplumber — ~10-50x faster text, word, table, and object extraction from PDFs
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
use crate::types::{BBox, Bounded, Char, Curve, Edge, Line, Page, Point, Word};
use crate::table::{Table, TableFinder, TableSettings};
use crate::Result;
use font8x8::UnicodeFonts;
use image::{ImageBuffer, ImageFormat, Rgba, RgbaImage};
use imageproc::drawing::{
    draw_filled_circle_mut, draw_filled_rect_mut, draw_hollow_circle_mut, draw_hollow_rect_mut,
    draw_line_segment_mut,
};
use imageproc::rect::Rect as ImageRect;
use serde::{Deserialize, Serialize};
use std::path::{Path, PathBuf};
use std::process::Command;
use std::time::{SystemTime, UNIX_EPOCH};

const DEFAULT_RESOLUTION: f64 = 72.0;

#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
pub struct RgbaColor {
    pub r: u8,
    pub g: u8,
    pub b: u8,
    pub a: u8,
}

impl RgbaColor {
    pub const fn new(r: u8, g: u8, b: u8, a: u8) -> Self {
        Self { r, g, b, a }
    }

    pub fn to_rgba(self) -> Rgba<u8> {
        Rgba([self.r, self.g, self.b, self.a])
    }
}

impl Default for RgbaColor {
    fn default() -> Self {
        Self::new(0, 0, 0, 255)
    }
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq)]
pub struct RenderOptions {
    pub resolution: Option<f64>,
    pub width: Option<f64>,
    pub height: Option<f64>,
    pub antialias: bool,
    pub force_mediabox: bool,
}

impl Default for RenderOptions {
    fn default() -> Self {
        Self {
            resolution: Some(DEFAULT_RESOLUTION),
            width: None,
            height: None,
            antialias: false,
            force_mediabox: false,
        }
    }
}

pub trait HasBBox {
    fn bbox(&self) -> BBox;
}

impl<T> HasBBox for T
where
    T: Bounded,
{
    fn bbox(&self) -> BBox {
        Bounded::bbox(self)
    }
}

impl HasBBox for BBox {
    fn bbox(&self) -> BBox {
        *self
    }
}

impl HasBBox for (f64, f64, f64, f64) {
    fn bbox(&self) -> BBox {
        BBox::new(self.0, self.1, self.2, self.3)
    }
}

impl HasBBox for Table {
    fn bbox(&self) -> BBox {
        self.bbox
    }
}

pub trait HasCenter {
    fn center(&self) -> Point;
}

impl<T> HasCenter for T
where
    T: HasBBox,
{
    fn center(&self) -> Point {
        self.bbox().center()
    }
}

pub trait HasLineSegments {
    fn line_segments(&self) -> Vec<(Point, Point)>;
}

impl HasLineSegments for Line {
    fn line_segments(&self) -> Vec<(Point, Point)> {
        self.pts
            .windows(2)
            .map(|pair| (pair[0], pair[1]))
            .collect::<Vec<_>>()
    }
}

impl HasLineSegments for Edge {
    fn line_segments(&self) -> Vec<(Point, Point)> {
        vec![(Point::new(self.x0, self.top), Point::new(self.x1, self.bottom))]
    }
}

impl HasLineSegments for Curve {
    fn line_segments(&self) -> Vec<(Point, Point)> {
        self.pts
            .windows(2)
            .map(|pair| (pair[0], pair[1]))
            .collect::<Vec<_>>()
    }
}

impl HasLineSegments for (Point, Point) {
    fn line_segments(&self) -> Vec<(Point, Point)> {
        vec![*self]
    }
}

impl HasLineSegments for ((f64, f64), (f64, f64)) {
    fn line_segments(&self) -> Vec<(Point, Point)> {
        vec![(Point::new((self.0).0, (self.0).1), Point::new((self.1).0, (self.1).1))]
    }
}

#[derive(Debug, Clone)]
pub struct PageImage {
    pub page: Page,
    pub resolution: f64,
    pub antialias: bool,
    pub force_mediabox: bool,
    pub bbox: BBox,
    pub original: RgbaImage,
    pub annotated: RgbaImage,
}

impl PageImage {
    pub fn new(page: &Page, options: RenderOptions) -> Result<Self> {
        let set_count = [options.resolution.is_some(), options.width.is_some(), options.height.is_some()]
            .into_iter()
            .filter(|item| *item)
            .count();
        if set_count > 1 {
            return Err(crate::Error::Message(
                "pass at most one of resolution, width, or height".to_string(),
            ));
        }

        let bbox = if page.bbox != page.mediabox {
            page.bbox
        } else if options.force_mediabox {
            page.mediabox
        } else {
            page.cropbox
        };

        let resolution = if let Some(resolution) = options.resolution {
            resolution
        } else if let Some(width) = options.width {
            DEFAULT_RESOLUTION * (width / bbox.width())
        } else if let Some(height) = options.height {
            DEFAULT_RESOLUTION * (height / bbox.height())
        } else {
            DEFAULT_RESOLUTION
        };

        let scale = resolution / DEFAULT_RESOLUTION;
        let width_px = ((bbox.width() * scale).round() as i64).max(1) as u32;
        let height_px = ((bbox.height() * scale).round() as i64).max(1) as u32;
        let mut image = ImageBuffer::from_pixel(width_px, height_px, Rgba([255, 255, 255, 255]));

        let mut page_image = Self {
            page: page.clone(),
            resolution,
            antialias: options.antialias,
            force_mediabox: options.force_mediabox,
            bbox,
            original: image.clone(),
            annotated: image.clone(),
        };
        page_image.render_page_content(&mut image);
        page_image.original = image.clone();
        page_image.annotated = image;
        Ok(page_image)
    }

    pub fn width(&self) -> u32 {
        self.annotated.width()
    }

    pub fn height(&self) -> u32 {
        self.annotated.height()
    }

    pub fn reset(&mut self) -> &mut Self {
        self.annotated = self.original.clone();
        self
    }

    pub fn copy(&self) -> Self {
        self.clone()
    }

    pub fn save<P: AsRef<Path>>(
        &self,
        dest: P,
        format: Option<ImageFormat>,
        _quantize: bool,
        _colors: u16,
        _bits: u8,
    ) -> Result<()> {
        if let Some(format) = format {
            self.annotated.save_with_format(dest, format)?;
        } else {
            self.annotated.save(dest)?;
        }
        Ok(())
    }

    pub fn show(&self) -> Result<PathBuf> {
        let millis = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .map_err(|err| crate::Error::Message(err.to_string()))?
            .as_millis();
        let path = std::env::temp_dir().join(format!("pdfsink-rs-page-{millis}.png"));
        self.save(&path, Some(ImageFormat::Png), false, 256, 8)?;

        #[cfg(target_os = "macos")]
        let _ = Command::new("open").arg(&path).spawn();
        #[cfg(target_os = "linux")]
        let _ = Command::new("xdg-open").arg(&path).spawn();
        #[cfg(target_os = "windows")]
        let _ = Command::new("cmd").args(["/C", "start", path.to_string_lossy().as_ref()]).spawn();

        Ok(path)
    }

    pub fn draw_line<T: HasLineSegments>(&mut self, item: &T, stroke: RgbaColor, stroke_width: u32) -> &mut Self {
        let color = stroke.to_rgba();
        for (start, end) in item.line_segments() {
            let (x0, y0) = self.project_point(start);
            let (x1, y1) = self.project_point(end);
            let offset = (stroke_width.max(1) as i32 - 1) / 2;
            for dx in -offset..=offset {
                for dy in -offset..=offset {
                    draw_line_segment_mut(
                        &mut self.annotated,
                        (x0 + dx as f32, y0 + dy as f32),
                        (x1 + dx as f32, y1 + dy as f32),
                        color,
                    );
                }
            }
        }
        self
    }

    pub fn draw_lines<T: HasLineSegments>(&mut self, items: &[T], stroke: RgbaColor, stroke_width: u32) -> &mut Self {
        for item in items {
            self.draw_line(item, stroke, stroke_width);
        }
        self
    }

    pub fn draw_vline(&mut self, location: f64, stroke: RgbaColor, stroke_width: u32) -> &mut Self {
        self.draw_line(
            &(
                Point::new(location, self.bbox.top),
                Point::new(location, self.bbox.bottom),
            ),
            stroke,
            stroke_width,
        )
    }

    pub fn draw_vlines(&mut self, locations: &[f64], stroke: RgbaColor, stroke_width: u32) -> &mut Self {
        for location in locations {
            self.draw_vline(*location, stroke, stroke_width);
        }
        self
    }

    pub fn draw_hline(&mut self, location: f64, stroke: RgbaColor, stroke_width: u32) -> &mut Self {
        self.draw_line(
            &(
                Point::new(self.bbox.x0, location),
                Point::new(self.bbox.x1, location),
            ),
            stroke,
            stroke_width,
        )
    }

    pub fn draw_hlines(&mut self, locations: &[f64], stroke: RgbaColor, stroke_width: u32) -> &mut Self {
        for location in locations {
            self.draw_hline(*location, stroke, stroke_width);
        }
        self
    }

    pub fn draw_rect<T: HasBBox>(
        &mut self,
        item: &T,
        fill: Option<RgbaColor>,
        stroke: Option<RgbaColor>,
        stroke_width: u32,
    ) -> &mut Self {
        let bbox = item.bbox();
        let rect = self.project_rect(bbox);
        if rect.width() == 0 || rect.height() == 0 {
            return self;
        }
        if let Some(fill) = fill {
            draw_filled_rect_mut(&mut self.annotated, rect, fill.to_rgba());
        }
        if let Some(stroke) = stroke {
            for inset in 0..stroke_width.max(1) {
                let x = rect.left() + inset as i32;
                let y = rect.top() + inset as i32;
                let w = rect.width().saturating_sub(inset.saturating_mul(2));
                let h = rect.height().saturating_sub(inset.saturating_mul(2));
                if w == 0 || h == 0 {
                    continue;
                }
                let inset_rect = ImageRect::at(x, y).of_size(w, h);
                draw_hollow_rect_mut(&mut self.annotated, inset_rect, stroke.to_rgba());
            }
        }
        self
    }

    pub fn draw_rects<T: HasBBox>(
        &mut self,
        items: &[T],
        fill: Option<RgbaColor>,
        stroke: Option<RgbaColor>,
        stroke_width: u32,
    ) -> &mut Self {
        for item in items {
            self.draw_rect(item, fill, stroke, stroke_width);
        }
        self
    }

    pub fn draw_circle<T: HasCenter>(
        &mut self,
        item: &T,
        radius: i32,
        fill: Option<RgbaColor>,
        stroke: Option<RgbaColor>,
    ) -> &mut Self {
        let center = item.center();
        let (x, y) = self.project_point(center);
        let center = (x.round() as i32, y.round() as i32);
        if let Some(fill) = fill {
            draw_filled_circle_mut(&mut self.annotated, center, radius.max(1), fill.to_rgba());
        }
        if let Some(stroke) = stroke {
            draw_hollow_circle_mut(&mut self.annotated, center, radius.max(1), stroke.to_rgba());
        }
        self
    }

    pub fn draw_circles<T: HasCenter>(
        &mut self,
        items: &[T],
        radius: i32,
        fill: Option<RgbaColor>,
        stroke: Option<RgbaColor>,
    ) -> &mut Self {
        for item in items {
            self.draw_circle(item, radius, fill, stroke);
        }
        self
    }

    pub fn outline_words(&mut self, words: &[Word], stroke: RgbaColor, stroke_width: u32) -> &mut Self {
        self.draw_rects(words, None, Some(stroke), stroke_width)
    }

    pub fn outline_chars(&mut self, chars: &[Char], stroke: RgbaColor, stroke_width: u32) -> &mut Self {
        self.draw_rects(chars, None, Some(stroke), stroke_width)
    }

    pub fn outline_edges(&mut self, edges: &[Edge], stroke: RgbaColor, stroke_width: u32) -> &mut Self {
        self.draw_lines(edges, stroke, stroke_width)
    }

    pub fn outline_tables(&mut self, tables: &[Table], fill: Option<RgbaColor>, stroke: Option<RgbaColor>, stroke_width: u32) -> &mut Self {
        for table in tables {
            for cell in &table.cells {
                self.draw_rect(cell, fill, stroke, stroke_width);
            }
        }
        self
    }

    pub fn debug_tablefinder(&mut self, table_settings: Option<TableSettings>) -> Result<&mut Self> {
        let finder = if let Some(settings) = table_settings {
            self.page.debug_tablefinder(settings)?
        } else {
            self.page.debug_tablefinder(TableSettings::default())?
        };
        self.overlay_tablefinder(&finder);
        Ok(self)
    }

    pub fn overlay_tablefinder(&mut self, finder: &TableFinder) -> &mut Self {
        let red = RgbaColor::new(255, 0, 0, 255);
        let light_blue = RgbaColor::new(173, 216, 230, 96);
        for edge in &finder.edges {
            self.draw_line(edge, red, 1);
        }
        for intersection in finder.intersections.keys() {
            let point = Point::new(intersection.0.into_inner(), intersection.1.into_inner());
            self.draw_circle(&point, 4, Some(red), Some(red));
        }
        for cell in &finder.cells {
            self.draw_rect(cell, Some(light_blue), Some(red), 1);
        }
        self
    }

    fn render_page_content(&mut self, image: &mut RgbaImage) {
        for rect in &self.page.rects {
            let fill = if rect.fill {
                Some(RgbaColor::new(235, 235, 235, 255).to_rgba())
            } else {
                None
            };
            let stroke = if rect.stroke {
                Some(RgbaColor::default().to_rgba())
            } else {
                None
            };
            let projected = self.project_rect(Bounded::bbox(rect));
            if let Some(fill) = fill {
                draw_filled_rect_mut(image, projected, fill);
            }
            if let Some(stroke) = stroke {
                draw_hollow_rect_mut(image, projected, stroke);
            }
        }

        for line in &self.page.lines {
            self.render_segment(image, line);
        }
        for curve in &self.page.curves {
            self.render_segment(image, curve);
        }
        for image_obj in &self.page.images {
            let rect = self.project_rect(Bounded::bbox(image_obj));
            draw_hollow_rect_mut(image, rect, RgbaColor::new(120, 120, 120, 255).to_rgba());
        }
        for ch in &self.page.chars {
            self.render_char(image, ch);
        }
    }

    fn render_segment<T: HasLineSegments>(&self, image: &mut RgbaImage, item: &T) {
        for (start, end) in item.line_segments() {
            let (x0, y0) = self.project_point(start);
            let (x1, y1) = self.project_point(end);
            draw_line_segment_mut(image, (x0, y0), (x1, y1), RgbaColor::default().to_rgba());
        }
    }

    fn render_char(&self, image: &mut RgbaImage, ch: &Char) {
        let Some(letter) = ch.text.chars().next() else {
            return;
        };
        if letter.is_whitespace() {
            return;
        }
        let bbox = Bounded::bbox(ch);
        let left = ((bbox.x0 - self.bbox.x0) * self.scale()).floor().max(0.0) as u32;
        let top = ((bbox.top - self.bbox.top) * self.scale()).floor().max(0.0) as u32;
        let width = ((bbox.width() * self.scale()).ceil().max(1.0)) as u32;
        let height = ((bbox.height() * self.scale()).ceil().max(1.0)) as u32;

        if let Some(glyph) = font8x8::BASIC_FONTS.get(letter) {
            for (row_idx, row) in glyph.iter().enumerate() {
                for col_idx in 0..8u32 {
                    if ((*row >> col_idx) & 1) == 1 {
                        let x_start = left + (col_idx * width / 8);
                        let x_end = left + (((col_idx + 1) * width + 7) / 8).max(1);
                        let y_start = top + (row_idx as u32 * height / 8);
                        let y_end = top + ((((row_idx as u32) + 1) * height + 7) / 8).max(1);
                        for y in y_start..y_end.min(image.height()) {
                            for x in x_start..x_end.min(image.width()) {
                                image.put_pixel(x, y, RgbaColor::default().to_rgba());
                            }
                        }
                    }
                }
            }
        } else {
            let rect = self.project_rect(bbox);
            draw_hollow_rect_mut(image, rect, RgbaColor::default().to_rgba());
        }
    }

    fn scale(&self) -> f64 {
        self.resolution / DEFAULT_RESOLUTION
    }

    fn project_point(&self, point: Point) -> (f32, f32) {
        (
            ((point.x - self.bbox.x0) * self.scale()) as f32,
            ((point.y - self.bbox.top) * self.scale()) as f32,
        )
    }

    fn project_rect(&self, bbox: BBox) -> ImageRect {
        let x = ((bbox.x0 - self.bbox.x0) * self.scale()).floor() as i32;
        let y = ((bbox.top - self.bbox.top) * self.scale()).floor() as i32;
        let width = ((bbox.width() * self.scale()).ceil() as i64).max(1) as u32;
        let height = ((bbox.height() * self.scale()).ceil() as i64).max(1) as u32;
        ImageRect::at(x, y).of_size(width, height)
    }
}

impl HasCenter for Point {
    fn center(&self) -> Point {
        *self
    }
}

impl Page {
    pub fn to_image(
        &self,
        resolution: Option<f64>,
        width: Option<f64>,
        height: Option<f64>,
        antialias: bool,
        force_mediabox: bool,
    ) -> Result<PageImage> {
        PageImage::new(
            self,
            RenderOptions {
                resolution,
                width,
                height,
                antialias,
                force_mediabox,
            },
        )
    }
}