pdfrum 0.1.0

A composable PDF library built in Rust
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
//! A page that owns its document: the handle a caller without a lifetime
//! holds.

use std::sync::Arc;

use pdfrum_common::PageIndex;

use crate::{
    Annotation, Document, Page, PageImage, PageLink, Pixmap, RasterBackend, RenderOptions,
    RenderSession, Result, Rotation, TextPage, Word,
};

/// One page of a [`Document`], holding the document rather than borrowing
/// it.
///
/// [`Page`] borrows its document, which is the right shape for a loop over
/// `doc.pages()`. It is the wrong shape for a handle that outlives the scope
/// it was made in — a page stored in a struct beside its document, sent to
/// another thread, or handed across a language boundary where no lifetime
/// can follow it. An `OwnedPage` is that handle: it keeps an
/// `Arc<Document>`, and the document lives as long as any page of it does.
///
/// The read-only surface of [`Page`], under the same names: geometry,
/// [`render`](OwnedPage::render), [`text`](OwnedPage::text),
/// [`words`](OwnedPage::words), [`links`](OwnedPage::links),
/// [`annotations`](OwnedPage::annotations), [`images`](OwnedPage::images),
/// [`structure`](OwnedPage::structure), and `markdown` with the feature of
/// that name. Each is the borrowed method, called
/// through a [`Page`] this handle lends its record to for the length of the
/// call: the dictionary and boxes a `Page` reads at load are read once here
/// too and kept, so nothing is re-derived per call and a render costs what
/// [`Page::render`] costs. `Send + Sync`, like everything else here.
///
/// ```
/// use std::sync::Arc;
/// use pdfrum::{Document, RenderOptions, VelloCpuBackend};
///
/// let doc = Arc::new(Document::open("tests/fixtures/hello_world.pdf")?);
/// let page = doc.page_owned(0)?;
/// drop(doc); // the page keeps the document alive
///
/// let pixmap = page.render(&VelloCpuBackend::new(), &RenderOptions::default())?;
/// assert_eq!((pixmap.width(), pixmap.height()), (200, 200));
/// assert!(page.text().to_string().contains("Hello, world!"));
/// # Ok::<(), pdfrum::Error>(())
/// ```
#[derive(Debug, Clone)]
pub struct OwnedPage {
    doc: Arc<Document>,
    page: PageRecord,
}

/// What a [`Page`] reads at load and keeps — everything but the document it
/// borrows.
#[derive(Debug, Clone)]
struct PageRecord {
    dict: Arc<pdfrum_parser::PageDict>,
    index: PageIndex,
    media_box: kurbo::Rect,
    crop_box: kurbo::Rect,
    rotation: Rotation,
}

impl OwnedPage {
    /// Reads the page once, as [`Document::page`] does, and keeps what it
    /// read beside the document.
    pub(crate) fn load(doc: &Arc<Document>, index: PageIndex) -> Result<OwnedPage> {
        let page = doc.page(index)?;
        Ok(OwnedPage {
            page: PageRecord {
                dict: page.dict,
                index: page.index,
                media_box: page.media_box,
                crop_box: page.crop_box,
                rotation: page.rotation,
            },
            doc: Arc::clone(doc),
        })
    }

    /// The borrowed page every method delegates to: this handle's record
    /// over a borrow of the document it holds. The one cost above the
    /// borrowed path — one reference count on the shared dictionary.
    fn page(&self) -> Page<'_> {
        Page {
            doc: &self.doc,
            dict: Arc::clone(&self.page.dict),
            index: self.page.index,
            media_box: self.page.media_box,
            crop_box: self.page.crop_box,
            rotation: self.page.rotation,
        }
    }

    /// The document this page belongs to — the one every page from the same
    /// [`Document::page_owned`] call shares.
    ///
    /// ```
    /// use std::sync::Arc;
    /// use pdfrum::Document;
    ///
    /// let doc = Arc::new(Document::open("tests/fixtures/hello_world.pdf")?);
    /// let page = doc.page_owned(0)?;
    /// assert!(Arc::ptr_eq(page.document(), &doc));
    /// # Ok::<(), pdfrum::Error>(())
    /// ```
    #[must_use]
    pub fn document(&self) -> &Arc<Document> {
        &self.doc
    }

    /// The page's zero-based index in the document.
    ///
    /// ```
    /// use std::sync::Arc;
    /// use pdfrum::{Document, PageIndex};
    ///
    /// let doc = Arc::new(Document::open("tests/fixtures/hello_world_2_pages.pdf")?);
    /// assert_eq!(doc.page_owned(1)?.index(), PageIndex::from(1));
    /// # Ok::<(), pdfrum::Error>(())
    /// ```
    #[must_use]
    pub fn index(&self) -> PageIndex {
        self.page.index
    }

    /// The page's displayed width in points, after rotation — as
    /// [`Page::width`].
    ///
    /// ```
    /// use std::sync::Arc;
    /// use pdfrum::Document;
    ///
    /// let doc = Arc::new(Document::open("tests/fixtures/hello_world.pdf")?);
    /// assert_eq!(doc.page_owned(0)?.width().round(), 200.0);
    /// # Ok::<(), pdfrum::Error>(())
    /// ```
    #[must_use]
    pub fn width(&self) -> f64 {
        self.page().width()
    }

    /// The page's displayed height in points, after rotation — as
    /// [`Page::height`].
    ///
    /// ```
    /// use std::sync::Arc;
    /// use pdfrum::Document;
    ///
    /// let doc = Arc::new(Document::open("tests/fixtures/hello_world.pdf")?);
    /// assert_eq!(doc.page_owned(0)?.height().round(), 200.0);
    /// # Ok::<(), pdfrum::Error>(())
    /// ```
    #[must_use]
    pub fn height(&self) -> f64 {
        self.page().height()
    }

    /// The page's `/MediaBox` — as [`Page::media_box`].
    ///
    /// ```
    /// use std::sync::Arc;
    /// use pdfrum::Document;
    ///
    /// let doc = Arc::new(Document::open("tests/fixtures/hello_world.pdf")?);
    /// let page = doc.page_owned(0)?;
    /// assert_eq!(page.media_box(), doc.page(0)?.media_box());
    /// # Ok::<(), pdfrum::Error>(())
    /// ```
    #[must_use]
    pub fn media_box(&self) -> kurbo::Rect {
        self.page.media_box
    }

    /// The page's `/CropBox`, intersected with the media box — as
    /// [`Page::crop_box`].
    ///
    /// ```
    /// use std::sync::Arc;
    /// use pdfrum::Document;
    ///
    /// let doc = Arc::new(Document::open("tests/fixtures/hello_world.pdf")?);
    /// let page = doc.page_owned(0)?;
    /// assert_eq!(page.crop_box(), doc.page(0)?.crop_box());
    /// # Ok::<(), pdfrum::Error>(())
    /// ```
    #[must_use]
    pub fn crop_box(&self) -> kurbo::Rect {
        self.page.crop_box
    }

    /// The page's `/BleedBox`, only when the page sets one — as
    /// [`Page::bleed_box`].
    ///
    /// ```
    /// use std::sync::Arc;
    /// use pdfrum::Document;
    ///
    /// let doc = Arc::new(Document::open("tests/fixtures/hello_world.pdf")?);
    /// assert!(doc.page_owned(0)?.bleed_box().is_none());
    /// # Ok::<(), pdfrum::Error>(())
    /// ```
    #[must_use]
    pub fn bleed_box(&self) -> Option<kurbo::Rect> {
        self.page().bleed_box()
    }

    /// The page's `/TrimBox`, only when the page sets one — as
    /// [`Page::trim_box`].
    ///
    /// ```
    /// use std::sync::Arc;
    /// use pdfrum::Document;
    ///
    /// let doc = Arc::new(Document::open("tests/fixtures/hello_world.pdf")?);
    /// assert!(doc.page_owned(0)?.trim_box().is_none());
    /// # Ok::<(), pdfrum::Error>(())
    /// ```
    #[must_use]
    pub fn trim_box(&self) -> Option<kurbo::Rect> {
        self.page().trim_box()
    }

    /// The page's `/ArtBox`, only when the page sets one — as
    /// [`Page::art_box`].
    ///
    /// ```
    /// use std::sync::Arc;
    /// use pdfrum::Document;
    ///
    /// let doc = Arc::new(Document::open("tests/fixtures/hello_world.pdf")?);
    /// assert!(doc.page_owned(0)?.art_box().is_none());
    /// # Ok::<(), pdfrum::Error>(())
    /// ```
    #[must_use]
    pub fn art_box(&self) -> Option<kurbo::Rect> {
        self.page().art_box()
    }

    /// The page's `/Rotate`, normalized to a quarter turn — as
    /// [`Page::rotation`].
    ///
    /// ```
    /// use std::sync::Arc;
    /// use pdfrum::{Document, Rotation};
    ///
    /// let doc = Arc::new(Document::open("tests/fixtures/hello_world.pdf")?);
    /// assert_eq!(doc.page_owned(0)?.rotation(), Rotation::None);
    /// # Ok::<(), pdfrum::Error>(())
    /// ```
    #[must_use]
    pub fn rotation(&self) -> Rotation {
        self.page.rotation
    }

    /// Renders the page on the rasterizer you name, with caches of its own —
    /// as [`Page::render`], byte for byte.
    ///
    /// # Errors
    ///
    /// As [`Page::render`].
    ///
    /// ```
    /// use std::sync::Arc;
    /// use pdfrum::{Document, RenderOptions, VelloCpuBackend};
    ///
    /// let doc = Arc::new(Document::open("tests/fixtures/hello_world.pdf")?);
    /// let backend = VelloCpuBackend::new();
    /// let owned = doc.page_owned(0)?.render(&backend, &RenderOptions::default())?;
    /// let borrowed = doc.page(0)?.render(&backend, &RenderOptions::default())?;
    /// assert_eq!(owned.data(), borrowed.data());
    /// # Ok::<(), pdfrum::Error>(())
    /// ```
    pub fn render<B: RasterBackend>(&self, backend: &B, options: &RenderOptions) -> Result<Pixmap> {
        self.page().render(backend, options)
    }

    /// [`OwnedPage::render`] reusing a caller-owned [`RenderSession`] — as
    /// [`Page::render_on`].
    ///
    /// # Errors
    ///
    /// As [`Page::render`].
    ///
    /// ```
    /// use std::sync::Arc;
    /// use pdfrum::{Document, RenderOptions, RenderSession, VelloCpuBackend};
    ///
    /// let doc = Arc::new(Document::open("tests/fixtures/hello_world_2_pages.pdf")?);
    /// let backend = VelloCpuBackend::new();
    /// let mut session = RenderSession::new();
    /// for page in doc.pages_owned() {
    ///     let pixmap = page?.render_on(&backend, &RenderOptions::default(), &mut session)?;
    ///     assert!(pixmap.width() > 0);
    /// }
    /// # Ok::<(), pdfrum::Error>(())
    /// ```
    pub fn render_on<B: RasterBackend>(
        &self,
        backend: &B,
        options: &RenderOptions,
        session: &mut RenderSession,
    ) -> Result<Pixmap> {
        self.page().render_on(backend, options, session)
    }

    /// Extracts the page's text — as [`Page::text`].
    ///
    /// ```
    /// use std::sync::Arc;
    /// use pdfrum::Document;
    ///
    /// let doc = Arc::new(Document::open("tests/fixtures/hello_world.pdf")?);
    /// let text = doc.page_owned(0)?.text();
    /// assert!(text.to_string().contains("Hello, world!"));
    /// # Ok::<(), pdfrum::Error>(())
    /// ```
    #[must_use]
    pub fn text(&self) -> TextPage {
        self.page().text()
    }

    /// [`OwnedPage::text`] reusing a caller-owned [`RenderSession`] — as
    /// [`Page::text_on`].
    ///
    /// ```
    /// use std::sync::Arc;
    /// use pdfrum::{Document, RenderSession};
    ///
    /// let doc = Arc::new(Document::open("tests/fixtures/hello_world.pdf")?);
    /// let mut session = RenderSession::new();
    /// let text = doc.page_owned(0)?.text_on(&mut session);
    /// assert!(text.to_string().contains("Hello, world!"));
    /// # Ok::<(), pdfrum::Error>(())
    /// ```
    #[must_use]
    pub fn text_on(&self, session: &mut RenderSession) -> TextPage {
        self.page().text_on(session)
    }

    /// The page's words in reading order, each with its box — as
    /// [`Page::words`].
    ///
    /// ```
    /// use std::sync::Arc;
    /// use pdfrum::Document;
    ///
    /// let doc = Arc::new(Document::open("tests/fixtures/hello_world.pdf")?);
    /// let words = doc.page_owned(0)?.words();
    /// let texts: Vec<&str> = words.iter().map(|w| w.text.as_str()).collect();
    /// assert_eq!(texts, ["Hello,", "world!", "Goodbye,", "world!"]);
    /// # Ok::<(), pdfrum::Error>(())
    /// ```
    #[must_use]
    pub fn words(&self) -> Vec<Word> {
        self.page().words()
    }

    /// The page's annotations, in `/Annots` order — as
    /// [`Page::annotations`]. Each borrows this handle rather than the
    /// document, so they live as long as the page does.
    ///
    /// ```
    /// use std::sync::Arc;
    /// use pdfrum::{Document, Subtype};
    ///
    /// let doc = Arc::new(Document::open("tests/fixtures/text_form.pdf")?);
    /// let page = doc.page_owned(0)?;
    /// let annots = page.annotations();
    /// assert!(annots.iter().any(|a| a.subtype() == Subtype::Widget));
    /// # Ok::<(), pdfrum::Error>(())
    /// ```
    #[must_use]
    pub fn annotations(&self) -> Vec<Annotation<'_>> {
        self.page().annotations()
    }

    /// The page's link annotations with the destination or action each one
    /// carries — as [`Page::links`].
    ///
    /// ```
    /// use std::sync::Arc;
    /// use pdfrum::Document;
    ///
    /// let doc = Arc::new(Document::open("tests/fixtures/hello_world.pdf")?);
    /// assert!(doc.page_owned(0)?.links().is_empty());
    /// # Ok::<(), pdfrum::Error>(())
    /// ```
    #[must_use]
    pub fn links(&self) -> Vec<pdfrum_doc::Link> {
        self.page().links()
    }

    /// The page's links with where each one leads — as
    /// [`Page::page_links`].
    ///
    /// ```
    /// use std::sync::Arc;
    /// use pdfrum::Document;
    ///
    /// let doc = Arc::new(Document::open("tests/fixtures/hello_world.pdf")?);
    /// assert!(doc.page_owned(0)?.page_links().is_empty());
    /// # Ok::<(), pdfrum::Error>(())
    /// ```
    #[must_use]
    pub fn page_links(&self) -> Vec<PageLink> {
        self.page().page_links()
    }

    /// The images the page draws, in drawing order — as [`Page::images`].
    ///
    /// ```
    /// use std::sync::Arc;
    /// use pdfrum::Document;
    ///
    /// let doc = Arc::new(Document::open("tests/fixtures/jpx_two_sizes.pdf")?);
    /// let images = doc.page_owned(0)?.images();
    /// assert_eq!(images.len(), doc.page(0)?.images().len());
    /// # Ok::<(), pdfrum::Error>(())
    /// ```
    #[must_use]
    pub fn images(&self) -> Vec<PageImage> {
        self.page().images()
    }

    /// The page's view of the document's structure tree, or `None` when
    /// the document is not tagged — as [`Page::structure`].
    ///
    /// ```
    /// use std::sync::Arc;
    /// use pdfrum::Document;
    ///
    /// let doc = Arc::new(Document::open("tests/fixtures/hello_world.pdf")?);
    /// assert!(doc.page_owned(0)?.structure().is_none());
    /// # Ok::<(), pdfrum::Error>(())
    /// ```
    #[must_use]
    pub fn structure(&self) -> Option<pdfrum_doc::structure::StructTree> {
        self.page().structure()
    }

    /// The page as GitHub-flavoured Markdown — as [`Page::markdown`].
    ///
    /// ```
    /// use std::sync::Arc;
    /// use pdfrum::Document;
    ///
    /// let doc = Arc::new(Document::open("tests/fixtures/hello_world.pdf")?);
    /// let markdown = doc.page_owned(0)?.markdown();
    /// assert_eq!(markdown, doc.page(0)?.markdown());
    /// # Ok::<(), pdfrum::Error>(())
    /// ```
    #[cfg(feature = "markdown")]
    #[must_use]
    pub fn markdown(&self) -> String {
        self.page().markdown()
    }

    /// The page's content as Markdown blocks — as [`Page::markdown_blocks`].
    ///
    /// ```
    /// use std::sync::Arc;
    /// use pdfrum::Document;
    ///
    /// let doc = Arc::new(Document::open("tests/fixtures/hello_world.pdf")?);
    /// let blocks = doc.page_owned(0)?.markdown_blocks();
    /// assert_eq!(blocks.len(), doc.page(0)?.markdown_blocks().len());
    /// # Ok::<(), pdfrum::Error>(())
    /// ```
    #[cfg(feature = "markdown")]
    #[must_use]
    pub fn markdown_blocks(&self) -> Vec<crate::Block> {
        self.page().markdown_blocks()
    }

    /// The page's text with its layout kept — as [`Page::layout_text`].
    ///
    /// ```
    /// use std::sync::Arc;
    /// use pdfrum::Document;
    ///
    /// let doc = Arc::new(Document::open("tests/fixtures/hello_world.pdf")?);
    /// let text = doc.page_owned(0)?.layout_text();
    /// assert_eq!(text, doc.page(0)?.layout_text());
    /// # Ok::<(), pdfrum::Error>(())
    /// ```
    #[cfg(feature = "markdown")]
    #[must_use]
    pub fn layout_text(&self) -> String {
        self.page().layout_text()
    }
}

impl Document {
    /// One page that holds the document rather than borrowing it — see
    /// [`OwnedPage`].
    ///
    /// Takes `&Arc<Document>` because the page keeps a reference count: a
    /// document is made an `Arc` once, by the caller who will hand its pages
    /// around, and every page from it shares that one allocation.
    ///
    /// # Errors
    ///
    /// As [`Document::page`].
    ///
    /// ```
    /// use std::sync::Arc;
    /// use pdfrum::Document;
    ///
    /// let doc = Arc::new(Document::open("tests/fixtures/hello_world.pdf")?);
    /// let page = doc.page_owned(0)?;
    /// assert_eq!(page.width().round(), 200.0);
    /// assert!(doc.page_owned(1).is_err(), "there is only one page");
    /// # Ok::<(), pdfrum::Error>(())
    /// ```
    pub fn page_owned(self: &Arc<Self>, index: impl Into<PageIndex>) -> Result<OwnedPage> {
        OwnedPage::load(self, index.into())
    }

    /// Every page in order as an [`OwnedPage`], read lazily as the iterator
    /// advances.
    ///
    /// Unlike [`Document::pages`], a page that will not load is **yielded as
    /// its error** rather than skipped, so the index of each item is the
    /// page's own and a caller collecting into a `Vec` sees every failure.
    /// The iterator holds its own reference to the document, so it may
    /// outlive the `Arc` it was made from.
    ///
    /// ```
    /// use std::sync::Arc;
    /// use pdfrum::Document;
    ///
    /// let doc = Arc::new(Document::open("tests/fixtures/hello_world_2_pages.pdf")?);
    /// let pages: Vec<_> = doc.pages_owned().collect::<Result<_, _>>()?;
    /// assert_eq!(pages.len(), 2);
    /// assert_eq!(pages[1].index(), 1.into());
    /// # Ok::<(), pdfrum::Error>(())
    /// ```
    pub fn pages_owned(self: &Arc<Self>) -> impl Iterator<Item = Result<OwnedPage>> + 'static {
        let doc = Arc::clone(self);
        (0..self.page_count()).map(move |index| doc.page_owned(index))
    }
}