pdfsift 0.1.0

PDF to structured Markdown for LLM agents. Heuristics only: no AI model, no network.
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
//! Reads the tagged-PDF structure tree and marked content through PDFium's raw C API.
//!
//! `pdfium-render` 0.9.6 exposes `PdfPage::structure_tree()` only as an opaque handle,
//! and does not expose marked-content IDs or content marks of page objects. As a
//! workaround we open a second, raw handle to the same file and call the C functions.

use std::collections::HashMap;
use std::ffi::c_void;
use std::os::raw::{c_int, c_ulong};

use pdfium_render::prelude::*;

/// A node of the structure tree for one page.
pub struct Elem {
    pub kind: String,
    pub alt: Option<String>,
    pub actual_text: Option<String>,
    /// `/E`: expansion of an abbreviation.
    pub expansion: Option<String>,
    pub mcids: Vec<i32>,
    pub children: Vec<Elem>,
}

/// One marked-content mark (`/Tag <<params>> BDC … EMC`, or `/Tag BMC`) enclosing a page
/// object. PDFium resolves `/Tag /Name BDC` through the page's `/Properties` resources, so
/// inline and named property dicts both show up as params.
#[derive(Clone, Debug)]
pub struct Mark {
    pub name: String,
    /// Params in PDFium's order.
    pub params: Vec<(String, MarkValue)>,
}

#[derive(Clone, Debug, PartialEq)]
pub enum MarkValue {
    Int(i32),
    Str(String),
    /// A PDF name, without the slash.
    Name(String),
    /// A value of another PDF type, which we only name (`name`, `dict`, `array`…).
    Other(&'static str),
}

impl Mark {
    pub fn get(&self, key: &str) -> Option<&MarkValue> {
        self.params.iter().find(|(k, _)| k == key).map(|(_, v)| v)
    }

    pub fn str_param(&self, key: &str) -> Option<&str> {
        match self.get(key) {
            Some(MarkValue::Str(s)) => Some(s),
            _ => None,
        }
    }
}

/// Marks of one page object, outermost first, plus those of its children for form XObjects.
#[derive(Clone, Debug, Default)]
pub struct ObjMarks {
    pub marks: Vec<Mark>,
    pub children: Vec<ObjMarks>,
}

/// Raw view of a document, used only for what the high-level API lacks.
pub struct RawDoc<'a> {
    b: &'a dyn PdfiumLibraryBindings,
    doc: FPDF_DOCUMENT,
}

pub struct RawPage<'a> {
    b: &'a dyn PdfiumLibraryBindings,
    page: FPDF_PAGE,
}

impl<'a> RawDoc<'a> {
    pub fn open(b: &'a dyn PdfiumLibraryBindings, path: &str) -> Option<Self> {
        let doc = unsafe { b.FPDF_LoadDocument(path, None) };
        (!doc.is_null()).then_some(RawDoc { b, doc })
    }

    pub fn is_tagged(&self) -> bool {
        unsafe { self.b.FPDFCatalog_IsTagged(self.doc) != 0 }
    }

    pub fn page(&self, index: PdfPageIndex) -> Option<RawPage<'a>> {
        let page = unsafe { self.b.FPDF_LoadPage(self.doc, index as c_int) };
        (!page.is_null()).then_some(RawPage { b: self.b, page })
    }
}

impl Drop for RawDoc<'_> {
    fn drop(&mut self) {
        unsafe { self.b.FPDF_CloseDocument(self.doc) }
    }
}

impl RawPage<'_> {
    /// Marked-content ID of each top-level page object, in content-stream order
    /// (same order as `PdfPage::objects()`). -1 means "not marked".
    pub fn object_mcids(&self) -> Vec<i32> {
        let n = unsafe { self.b.FPDFPage_CountObjects(self.page) };
        (0..n)
            .map(|i| unsafe {
                let obj = self.b.FPDFPage_GetObject(self.page, i);
                if obj.is_null() {
                    -1
                } else {
                    self.b.FPDFPageObj_GetMarkedContentID(obj)
                }
            })
            .collect()
    }

    /// Content marks of every page object, in content-stream order (same order and nesting
    /// as `PdfPage::objects()` and the children of form XObjects).
    pub fn object_marks(&self) -> Vec<ObjMarks> {
        let b = self.b;
        unsafe {
            let n = b.FPDFPage_CountObjects(self.page).max(0);
            (0..n)
                .map(|i| read_obj_marks(b, b.FPDFPage_GetObject(self.page, i), 0))
                .collect()
        }
    }

    /// For each char of the page text layer (same indices as `PdfPageText::chars()`, since
    /// both come from the same PDFium text page builder), the path of the page object it
    /// came from: `[i]` for top-level object `i`, `[i, j]` for child `j` of form XObject `i`.
    /// None when PDFium links the char to no object we can find.
    pub fn char_objects(&self) -> Vec<Option<Vec<usize>>> {
        let b = self.b;
        unsafe {
            // Pointer -> path lookup only; never iterated, so HashMap order is irrelevant.
            let mut index: HashMap<usize, Vec<usize>> = HashMap::new();
            let n = b.FPDFPage_CountObjects(self.page).max(0);
            for i in 0..n {
                let obj = b.FPDFPage_GetObject(self.page, i);
                index_objects(b, obj, vec![i as usize], &mut index, 0);
            }
            let tp = b.FPDFText_LoadPage(self.page);
            if tp.is_null() {
                return Vec::new();
            }
            let count = b.FPDFText_CountChars(tp).max(0);
            let out = (0..count)
                .map(|c| {
                    let obj = b.FPDFText_GetTextObject(tp, c);
                    if obj.is_null() {
                        None
                    } else {
                        index.get(&(obj as usize)).cloned()
                    }
                })
                .collect();
            b.FPDFText_ClosePage(tp);
            out
        }
    }

    pub fn structure(&self) -> Vec<Elem> {
        let b = self.b;
        unsafe {
            let tree = b.FPDF_StructTree_GetForPage(self.page);
            if tree.is_null() {
                return Vec::new();
            }
            let n = b.FPDF_StructTree_CountChildren(tree);
            let out = (0..n)
                .filter_map(|i| {
                    let e = b.FPDF_StructTree_GetChildAtIndex(tree, i);
                    (!e.is_null()).then(|| read_elem(b, e, 0))
                })
                .collect();
            b.FPDF_StructTree_Close(tree);
            out
        }
    }
}

impl Drop for RawPage<'_> {
    fn drop(&mut self) {
        unsafe { self.b.FPDF_ClosePage(self.page) }
    }
}

const MAX_DEPTH: usize = 64;

// Values from PDFium's public headers (fpdf_edit.h / fpdfview.h). pdfium-render 0.9.6 does
// not re-export these constants, and they are part of PDFium's stable C ABI.
const PAGEOBJ_FORM: c_int = 5;
const OBJECT_BOOLEAN: c_int = 1;
const OBJECT_NUMBER: c_int = 2;
const OBJECT_STRING: c_int = 3;
const OBJECT_NAME: c_int = 4;
const OBJECT_ARRAY: c_int = 5;
const OBJECT_DICTIONARY: c_int = 6;
const OBJECT_REFERENCE: c_int = 9;

unsafe fn is_form(b: &dyn PdfiumLibraryBindings, obj: FPDF_PAGEOBJECT) -> bool {
    unsafe { b.FPDFPageObj_GetType(obj) == PAGEOBJ_FORM }
}

unsafe fn index_objects(
    b: &dyn PdfiumLibraryBindings,
    obj: FPDF_PAGEOBJECT,
    path: Vec<usize>,
    index: &mut HashMap<usize, Vec<usize>>,
    depth: usize,
) {
    if obj.is_null() {
        return;
    }
    unsafe {
        if depth < MAX_DEPTH && is_form(b, obj) {
            for j in 0..b.FPDFFormObj_CountObjects(obj).max(0) {
                let child = b.FPDFFormObj_GetObject(obj, j as c_ulong);
                let mut p = path.clone();
                p.push(j as usize);
                index_objects(b, child, p, index, depth + 1);
            }
        }
    }
    index.insert(obj as usize, path);
}

unsafe fn read_obj_marks(
    b: &dyn PdfiumLibraryBindings,
    obj: FPDF_PAGEOBJECT,
    depth: usize,
) -> ObjMarks {
    if obj.is_null() {
        return ObjMarks::default();
    }
    unsafe {
        let marks = (0..b.FPDFPageObj_CountMarks(obj).max(0))
            .filter_map(|i| {
                let m = b.FPDFPageObj_GetMark(obj, i as c_ulong);
                (!m.is_null()).then(|| read_mark(b, m))
            })
            .collect();
        let children = if depth < MAX_DEPTH && is_form(b, obj) {
            (0..b.FPDFFormObj_CountObjects(obj).max(0))
                .map(|j| read_obj_marks(b, b.FPDFFormObj_GetObject(obj, j as c_ulong), depth + 1))
                .collect()
        } else {
            Vec::new()
        };
        ObjMarks { marks, children }
    }
}

unsafe fn read_mark(b: &dyn PdfiumLibraryBindings, m: FPDF_PAGEOBJECTMARK) -> Mark {
    unsafe {
        let name = utf16_out(|buf, len, out| b.FPDFPageObjMark_GetName(m, buf, len, out))
            .unwrap_or_default();
        let params = (0..b.FPDFPageObjMark_CountParams(m).max(0))
            .filter_map(|i| {
                let key = utf16_out(|buf, len, out| {
                    b.FPDFPageObjMark_GetParamKey(m, i as c_ulong, buf, len, out)
                })?;
                // The crate turns `key` into a CString with unwrap(): a NUL would panic.
                if key.contains('\0') {
                    return None;
                }
                let ty = b.FPDFPageObjMark_GetParamValueType(m, &key);
                let value = match ty {
                    OBJECT_NUMBER => {
                        let mut v: c_int = 0;
                        if b.FPDFPageObjMark_GetParamIntValue(m, &key, &mut v) != 0 {
                            MarkValue::Int(v)
                        } else {
                            MarkValue::Other("number")
                        }
                    }
                    // Not FPDFPageObjMark_GetParamStringValue: PDFium (chromium/8179) decodes
                    // the raw string bytes as UTF-8, which mangles PDF text strings: the
                    // UTF-16BE `<FEFF00AD>` comes back as "\0", `<FEFF006100AD>` as "\0a"
                    // (achado 007). We read the raw bytes and decode them ourselves.
                    OBJECT_STRING => MarkValue::Str(
                        blob(|buf, len, out| {
                            b.FPDFPageObjMark_GetParamBlobValue(m, &key, buf, len, out)
                        })
                        .map(|raw| decode_text_string(&raw))
                        .unwrap_or_default(),
                    ),
                    OBJECT_BOOLEAN => MarkValue::Other("bool"),
                    // Names: the blob call refuses them, and with chromium/8179 the string
                    // call fails too (`/Subtype /Header` comes back as Other("name"),
                    // achados 007 and 009). Tried anyway, for a PDFium that accepts them.
                    // The page content stream itself is not reachable through PDFium's
                    // API, so there is no safe fallback without our own PDF parser.
                    OBJECT_NAME => utf16_out(|buf, len, out| {
                        b.FPDFPageObjMark_GetParamStringValue(m, &key, buf, len, out)
                    })
                    .map_or(MarkValue::Other("name"), MarkValue::Name),
                    OBJECT_ARRAY => MarkValue::Other("array"),
                    OBJECT_DICTIONARY => MarkValue::Other("dict"),
                    OBJECT_REFERENCE => MarkValue::Other("ref"),
                    _ => MarkValue::Other("?"),
                };
                Some((key, value))
            })
            .collect();
        Mark { name, params }
    }
}

unsafe fn read_elem(b: &dyn PdfiumLibraryBindings, e: FPDF_STRUCTELEMENT, depth: usize) -> Elem {
    unsafe {
        let kind = utf16(|buf, len| b.FPDF_StructElement_GetType(e, buf, len)).unwrap_or_default();
        let alt = utf16(|buf, len| b.FPDF_StructElement_GetAltText(e, buf, len));
        let actual_text = utf16(|buf, len| b.FPDF_StructElement_GetActualText(e, buf, len));
        let expansion = utf16(|buf, len| b.FPDF_StructElement_GetExpansion(e, buf, len));
        let mcids = (0..b.FPDF_StructElement_GetMarkedContentIdCount(e).max(0))
            .map(|i| b.FPDF_StructElement_GetMarkedContentIdAtIndex(e, i))
            .collect();
        let children = if depth >= MAX_DEPTH {
            Vec::new()
        } else {
            (0..b.FPDF_StructElement_CountChildren(e).max(0))
                .filter_map(|i| {
                    let c = b.FPDF_StructElement_GetChildAtIndex(e, i);
                    (!c.is_null()).then(|| read_elem(b, c, depth + 1))
                })
                .collect()
        };
        Elem {
            kind,
            alt,
            actual_text,
            expansion,
            mcids,
            children,
        }
    }
}

/// Calls a PDFium "fill a UTF-16LE buffer" function (two-call protocol: size, then data).
fn utf16(f: impl Fn(*mut c_void, c_ulong) -> c_ulong) -> Option<String> {
    let bytes = f(std::ptr::null_mut(), 0) as usize;
    if bytes <= 2 {
        return None;
    }
    let mut buf = vec![0u16; bytes / 2];
    f(buf.as_mut_ptr() as *mut c_void, bytes as c_ulong);
    while buf.last() == Some(&0) {
        buf.pop();
    }
    let s = String::from_utf16_lossy(&buf);
    (!s.is_empty()).then_some(s)
}

/// Calls a PDFium "fill a byte buffer, report the needed size through an out pointer"
/// function and returns the raw bytes.
fn blob(f: impl Fn(*mut u8, c_ulong, *mut c_ulong) -> FPDF_BOOL) -> Option<Vec<u8>> {
    let mut needed: c_ulong = 0;
    if f(std::ptr::null_mut(), 0, &mut needed) == 0 {
        return None;
    }
    let mut buf = vec![0u8; needed as usize];
    if needed > 0 {
        let mut got: c_ulong = 0;
        if f(buf.as_mut_ptr(), needed, &mut got) == 0 {
            return None;
        }
        buf.truncate(got.min(needed) as usize);
    }
    Some(buf)
}

/// Decodes a PDF text string (ISO 32000-2 §7.9.2.2): UTF-16BE with a `FE FF` BOM, UTF-8
/// with an `EF BB BF` BOM (PDF 2.0), otherwise PDFDocEncoding.
pub fn decode_text_string(raw: &[u8]) -> String {
    if let Some(rest) = raw.strip_prefix(&[0xFE, 0xFF]) {
        let units: Vec<u16> = rest
            .chunks_exact(2)
            .map(|p| u16::from_be_bytes([p[0], p[1]]))
            .collect();
        return String::from_utf16_lossy(&units);
    }
    if let Some(rest) = raw.strip_prefix(&[0xEF, 0xBB, 0xBF]) {
        return String::from_utf8_lossy(rest).into_owned();
    }
    raw.iter().map(|&c| pdf_doc_char(c)).collect()
}

/// PDFDocEncoding (ISO 32000-2 Annex D.2). It equals Latin-1 except for 0x18–0x1F,
/// 0x80–0xA0 and the undefined 0x7F, 0x9F, 0xAD.
fn pdf_doc_char(c: u8) -> char {
    const LOW: [char; 8] = ['˘', 'ˇ', 'ˆ', '˙', '˝', '˛', '˚', '˜'];
    const HIGH: [char; 33] = [
        '•', '†', '‡', '…', '—', '–', 'ƒ', '⁄', '‹', '›', '−', '‰', '„', '“', '”', '‘', '’', '‚',
        '™', 'fi', 'fl', 'Ł', 'Œ', 'Š', 'Ÿ', 'Ž', 'ı', 'ł', 'œ', 'š', 'ž', '\u{FFFD}', '€',
    ];
    match c {
        0x18..=0x1F => LOW[(c - 0x18) as usize],
        0x80..=0xA0 => HIGH[(c - 0x80) as usize],
        0x7F | 0xAD => '\u{FFFD}',
        _ => c as char,
    }
}

/// Same as [`utf16`] for the `FPDFPageObjMark_*` protocol: the needed size in bytes comes
/// back through an out pointer and the result is an FPDF_BOOL. Unlike [`utf16`], an empty
/// string is returned as `Some("")`: an empty ActualText is meaningful (it hides a glyph).
fn utf16_out(f: impl Fn(*mut u16, c_ulong, *mut c_ulong) -> FPDF_BOOL) -> Option<String> {
    let mut needed: c_ulong = 0;
    if f(std::ptr::null_mut(), 0, &mut needed) == 0 {
        return None;
    }
    if needed < 2 {
        return Some(String::new());
    }
    let mut buf = vec![0u16; needed as usize / 2];
    let mut got: c_ulong = 0;
    if f(buf.as_mut_ptr(), needed, &mut got) == 0 {
        return None;
    }
    while buf.last() == Some(&0) {
        buf.pop();
    }
    Some(String::from_utf16_lossy(&buf))
}

#[cfg(test)]
mod tests {
    use super::decode_text_string;

    #[test]
    fn text_string_utf16be_with_bom() {
        // Chrome's soft hyphen and Typst's "letter + soft hyphen" ActualText (achado 007).
        assert_eq!(decode_text_string(&[0xFE, 0xFF, 0x00, 0xAD]), "\u{AD}");
        assert_eq!(
            decode_text_string(&[0xFE, 0xFF, 0x00, 0x61, 0x00, 0xAD]),
            "a\u{AD}"
        );
        // Surrogate-free BMP pair plus variation selector (Chrome footnote back-link).
        assert_eq!(
            decode_text_string(&[0xFE, 0xFF, 0x21, 0xA9, 0xFE, 0x0E]),
            "\u{21A9}\u{FE0E}"
        );
    }

    #[test]
    fn text_string_pdfdoc_and_utf8() {
        assert_eq!(decode_text_string(b"fi"), "fi");
        assert_eq!(decode_text_string(b"-"), "-");
        assert_eq!(decode_text_string(&[0x93, 0xE1]), "\u{FB01}á");
        assert_eq!(decode_text_string(&[0xEF, 0xBB, 0xBF, 0xC3, 0xA1]), "á");
        assert_eq!(decode_text_string(&[]), "");
    }
}