use std::collections::HashMap;
use std::ffi::c_void;
use std::os::raw::{c_int, c_ulong};
use pdfium_render::prelude::*;
pub struct Elem {
pub kind: String,
pub alt: Option<String>,
pub actual_text: Option<String>,
pub expansion: Option<String>,
pub mcids: Vec<i32>,
pub children: Vec<Elem>,
}
#[derive(Clone, Debug)]
pub struct Mark {
pub name: String,
pub params: Vec<(String, MarkValue)>,
}
#[derive(Clone, Debug, PartialEq)]
pub enum MarkValue {
Int(i32),
Str(String),
Name(String),
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,
}
}
}
#[derive(Clone, Debug, Default)]
pub struct ObjMarks {
pub marks: Vec<Mark>,
pub children: Vec<ObjMarks>,
}
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<'_> {
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()
}
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()
}
}
pub fn char_objects(&self) -> Vec<Option<Vec<usize>>> {
let b = self.b;
unsafe {
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;
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)
})?;
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")
}
}
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"),
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,
}
}
}
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)
}
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)
}
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()
}
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,
}
}
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() {
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}"
);
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(&[]), "");
}
}