use std::collections::BTreeMap;
use std::path::Path;
use anyhow::{Context, Result, bail};
use pdfium_render::prelude::*;
use crate::{engine, tags};
pub struct Options {
pub pages: Option<Vec<PdfPageIndex>>,
pub paths: bool,
pub tags: bool,
pub chars: bool,
pub region: Option<Region>,
pub marks: bool,
}
#[derive(Clone, Copy, Debug)]
pub struct Region {
pub x: f32,
pub y: f32,
pub w: f32,
pub h: f32,
}
impl Region {
fn contains(&self, x: f32, y: f32) -> bool {
x >= self.x && x <= self.x + self.w && y >= self.y && y <= self.y + self.h
}
}
pub fn parse_region(spec: Option<&str>) -> Result<Option<Region>> {
let Some(spec) = spec else { return Ok(None) };
let v: Vec<f32> = spec
.split(',')
.map(|p| p.trim().parse::<f32>())
.collect::<Result<_, _>>()
.with_context(|| format!("invalid region {spec:?}: expected x,y,w,h in points"))?;
match v[..] {
[x, y, w, h] if w > 0.0 && h > 0.0 && v.iter().all(|n| n.is_finite()) => {
Ok(Some(Region { x, y, w, h }))
}
_ => bail!("invalid region {spec:?}: expected x,y,w,h with w > 0 and h > 0"),
}
}
pub fn parse_pages(spec: Option<&str>) -> Result<Option<Vec<PdfPageIndex>>> {
let Some(spec) = spec else { return Ok(None) };
let mut out = Vec::new();
for part in spec.split(',') {
let (a, b) = match part.split_once('-') {
Some((a, b)) => (
a.trim().parse::<PdfPageIndex>()?,
b.trim().parse::<PdfPageIndex>()?,
),
None => {
let n = part.trim().parse::<PdfPageIndex>()?;
(n, n)
}
};
if a < 1 || b < a {
bail!("invalid page range: {part}");
}
out.extend((a - 1)..b);
}
Ok(Some(out))
}
pub fn run(file: &Path, opts: &Options) -> Result<()> {
let pdfium = engine::load()?;
let doc = pdfium
.load_pdf_from_file(file, None)
.with_context(|| format!("cannot open {}", file.display()))?;
let raw = tags::RawDoc::open(doc.bindings(), &file.to_string_lossy());
outln!("== document: {}", file.display());
outln!("version: {:?}", doc.version());
outln!("pages: {}", doc.pages().len());
for (label, tag) in [
("title", PdfDocumentMetadataTagType::Title),
("author", PdfDocumentMetadataTagType::Author),
("creator", PdfDocumentMetadataTagType::Creator),
("producer", PdfDocumentMetadataTagType::Producer),
] {
if let Some(t) = doc.metadata().get(tag) {
outln!("{label:<9} {:?}", t.value());
}
}
let tagged = raw.as_ref().map(|r| r.is_tagged());
outln!(
"tagged: {}",
tagged.map_or("unknown".into(), |t| t.to_string())
);
outln!("outline:");
match doc.bookmarks().root() {
Some(root) => print_bookmarks(&root, 1),
None => outln!(" (none)"),
}
let indices: Vec<PdfPageIndex> = match &opts.pages {
Some(p) => p.clone(),
None => (0..doc.pages().len()).collect(),
};
for idx in indices {
let page = match doc.pages().get(idx) {
Ok(p) => p,
Err(_) => {
outln!("\n== page {} does not exist", idx + 1);
continue;
}
};
let raw_page = raw.as_ref().and_then(|r| r.page(idx));
dump_page(&page, idx, raw_page.as_ref(), opts);
}
Ok(())
}
fn print_bookmarks(first: &PdfBookmark, depth: usize) {
for bm in std::iter::once(first.clone()).chain(first.iter_siblings()) {
let page = bm
.destination()
.and_then(|d| d.page_index().ok())
.map_or("?".to_string(), |i| (i + 1).to_string());
outln!(
"{}- {:?} (p{page})",
" ".repeat(depth),
bm.title().unwrap_or_default()
);
if let Some(child) = bm.first_child() {
print_bookmarks(&child, depth + 1);
}
}
}
struct Ctx<'a> {
page_h: f32,
opts: &'a Options,
path_count: usize,
path_area: BTreeMap<&'static str, usize>,
mark_values: BTreeMap<(String, String, String), usize>,
}
fn dump_page(page: &PdfPage, idx: PdfPageIndex, raw: Option<&tags::RawPage>, opts: &Options) {
let (w, h) = (page.width().value, page.height().value);
let rot = page
.rotation()
.map(|r| format!("{r:?}"))
.unwrap_or_default();
outln!("\n== page {} ({w:.0} x {h:.0} pt, rotation {rot})", idx + 1);
let mcids = raw.map(|r| r.object_mcids()).unwrap_or_default();
let marks = if opts.marks {
raw.map(|r| r.object_marks()).unwrap_or_default()
} else {
Vec::new()
};
let mut ctx = Ctx {
mark_values: BTreeMap::new(),
page_h: h,
opts,
path_count: 0,
path_area: BTreeMap::new(),
};
outln!("-- objects (content-stream order; y measured from top)");
for (i, obj) in page.objects().iter().enumerate() {
let mcid = mcids.get(i).copied().filter(|m| *m >= 0);
dump_object(&obj, &format!("{i:>4}"), 0, mcid, marks.get(i), &mut ctx);
}
if !opts.paths && ctx.path_count > 0 {
let sizes: Vec<String> = ctx
.path_area
.iter()
.map(|(k, v)| format!("{v} {k}"))
.collect();
outln!(
" paths: {} total ({}) [use --paths to list]",
ctx.path_count,
sizes.join(", ")
);
}
if opts.marks && !ctx.mark_values.is_empty() {
outln!(
"-- marked-content text params (objects, incl. form children; mark/key = value: count)"
);
for ((name, key, value), n) in &ctx.mark_values {
outln!(" {name}/{key} = {value}: {n}");
}
}
let links: Vec<_> = page.links().iter().collect();
if !links.is_empty() {
outln!("-- links");
for link in links {
let target = link
.action()
.and_then(|a| a.as_uri_action().and_then(|u| u.uri().ok()))
.or_else(|| {
link.destination()
.and_then(|d| d.page_index().ok())
.map(|p| format!("page {}", p + 1))
})
.unwrap_or_else(|| "?".into());
let r = link.rect().map(|r| fmt_rect(&r, h)).unwrap_or_default();
outln!(" {r} -> {target}");
}
}
if opts.chars {
let char_marks = if opts.marks {
raw.map(|r| (r.char_objects(), &marks))
} else {
None
};
dump_chars(page, h, opts.region, char_marks);
}
if opts.tags {
if let Some(raw) = raw {
let tree = raw.structure();
if !tree.is_empty() {
outln!("-- structure tree");
for e in &tree {
print_elem(e, 1);
}
}
}
}
}
fn dump_object(
obj: &PdfPageObject,
id: &str,
depth: usize,
mcid: Option<i32>,
marks: Option<&tags::ObjMarks>,
ctx: &mut Ctx,
) {
let indent = " ".repeat(depth);
let bbox = obj
.bounds()
.map(|q| fmt_rect(&q.to_rect(), ctx.page_h))
.unwrap_or_default();
let mut mc = mcid.map(|m| format!(" mcid={m}")).unwrap_or_default();
if let Some(m) = marks.filter(|m| !m.marks.is_empty()) {
mc.push_str(&format!(" marks=[{}]", fmt_marks(&m.marks)));
for mark in &m.marks {
for key in TEXT_PARAMS {
if let Some(v) = mark.str_param(key) {
*ctx.mark_values
.entry((mark.name.clone(), key.to_string(), format!("{v:?}")))
.or_default() += 1;
}
}
}
}
match obj.object_type() {
PdfPageObjectType::Text => {
let t = obj.as_text_object().unwrap();
let font = t.font();
let weight = font.weight().ok().map(weight_value);
let name = font.name();
let mut flags = Vec::new();
if font.is_bold_reenforced() || name.contains("Bold") {
flags.push("bold");
}
if font.is_italic() || name.contains("Italic") || name.contains("Oblique") {
flags.push("italic");
}
if font.is_fixed_pitch() {
flags.push("mono");
}
let mode = t.render_mode();
let mode = if matches!(mode, PdfPageTextRenderMode::FilledUnstroked) {
String::new()
} else {
format!(" mode={mode:?}")
};
outln!(
"{id} {indent}T {bbox} {:.1}pt w{} {:?}{}{mode}{mc} {:?}",
t.scaled_font_size().value,
weight.map_or("?".into(), |w| w.to_string()),
name,
if flags.is_empty() {
String::new()
} else {
format!(" [{}]", flags.join(","))
},
truncate(&t.text(), 240),
);
}
PdfPageObjectType::Image => {
let img = obj.as_image_object().unwrap();
let px = match (img.width(), img.height()) {
(Ok(w), Ok(h)) => format!("{w}x{h}px"),
_ => "?px".into(),
};
let filters: Vec<String> = img.filters().iter().map(|f| f.name().to_string()).collect();
let cs = img
.color_space()
.map(|c| format!("{c:?}"))
.unwrap_or_default();
let bpp = img
.bits_per_pixel()
.map(|b| b.to_string())
.unwrap_or_default();
outln!(
"{id} {indent}I {bbox} {px} filters=[{}] colorspace={cs} bpp={bpp}{mc}",
filters.join(",")
);
}
PdfPageObjectType::Path => {
ctx.path_count += 1;
if ctx.opts.paths {
outln!("{id} {indent}P {bbox}{mc}");
} else if let Ok(q) = obj.bounds() {
let r = q.to_rect();
let (w, h) = (r.width().value, r.height().value);
let kind = if w < 1.5 || h < 1.5 {
"line-like"
} else if w * h < 400.0 {
"small"
} else {
"large"
};
*ctx.path_area.entry(kind).or_default() += 1;
}
}
PdfPageObjectType::XObjectForm => {
let form = obj.as_x_object_form_object().unwrap();
outln!(
"{id} {indent}F {bbox} form xobject, {} objects{mc}",
form.len()
);
for (j, child) in form.iter().enumerate() {
let child_marks = marks.and_then(|m| m.children.get(j));
dump_object(
&child,
&format!("{id}.{j}"),
depth + 1,
None,
child_marks,
ctx,
);
}
}
other => outln!("{id} {indent}? {bbox} {other:?}{mc}"),
}
}
const SAME_BASELINE_TOL: f32 = 0.1;
struct PrevChar {
baseline: f32,
loose_right: f32,
tight_right: f32,
}
const TEXT_PARAMS: [&str; 3] = ["ActualText", "Alt", "E"];
fn fmt_marks(marks: &[tags::Mark]) -> String {
marks
.iter()
.map(|m| {
if m.params.is_empty() {
return m.name.clone();
}
let ps: Vec<String> = m
.params
.iter()
.map(|(k, v)| match v {
tags::MarkValue::Int(i) => format!("{k}={i}"),
tags::MarkValue::Str(s) => format!("{k}={:?}", truncate(s, 60)),
tags::MarkValue::Name(n) => format!("{k}=/{n}"),
tags::MarkValue::Other(t) => format!("{k}=<{t}>"),
})
.collect();
format!("{}({})", m.name, ps.join(" "))
})
.collect::<Vec<_>>()
.join(" > ")
}
fn marks_at<'m>(marks: &'m [tags::ObjMarks], path: &[usize]) -> Option<&'m tags::ObjMarks> {
let (first, rest) = path.split_first()?;
let mut cur = marks.get(*first)?;
for j in rest {
cur = cur.children.get(*j)?;
}
Some(cur)
}
type CharMarks<'a> = (Vec<Option<Vec<usize>>>, &'a Vec<tags::ObjMarks>);
fn dump_chars(page: &PdfPage, page_h: f32, region: Option<Region>, marks: Option<CharMarks>) {
let text = match page.text() {
Ok(t) => t,
Err(e) => {
outln!("-- chars: text layer unavailable ({e:?})");
return;
}
};
let chars = text.chars();
let total = chars.len();
match region {
Some(r) => outln!(
"-- chars ({total} on page; region x={} y={} w={} h={}, by loose-box center)",
r.x,
r.y,
r.w,
r.h
),
None => outln!("-- chars ({total} on page)"),
}
if let Some((objs, _)) = &marks {
if objs.len() != total {
outln!(
" (warning: raw text page has {} chars, not {total}; obj= may be off)",
objs.len()
);
}
outln!(
" (--marks: obj= is the source object, '-' = none, e.g. generated; text params from its innermost marks)"
);
}
outln!(
" idx char g loose: x y w h | tight x0-x1 | orig x base y | size font | gapL gapT gapL/size"
);
let mut prev: Option<PrevChar> = None;
let mut shown = 0usize;
for i in 0..total {
let Ok(c) = chars.get(i) else {
outln!(" {i:>6} (unreadable)");
continue;
};
let generated = c.is_generated().unwrap_or(false);
let loose = c.loose_bounds().ok();
let tight = c.tight_bounds().ok();
let origin = c.origin().ok();
let size = c.scaled_font_size().value;
let baseline = origin.map(|(_, y)| y.value);
let blank = c.unicode_char().is_none_or(char::is_whitespace);
let mut gap = None;
if !generated && !blank {
if let (Some(l), Some(b)) = (loose, baseline) {
if let Some(p) = &prev {
if (p.baseline - b).abs() <= SAME_BASELINE_TOL * size.max(1.0) {
let gl = l.left().value - p.loose_right;
let gt = tight.map(|t| t.left().value - p.tight_right);
gap = Some((gl, gt));
}
}
prev = Some(PrevChar {
baseline: b,
loose_right: l.right().value,
tight_right: tight.map_or(l.right().value, |t| t.right().value),
});
}
}
if let Some(r) = region {
let inside = loose.is_some_and(|l| {
let cx = (l.left().value + l.right().value) / 2.0;
let cy = page_h - (l.top().value + l.bottom().value) / 2.0;
r.contains(cx, cy)
});
if !inside {
continue;
}
}
shown += 1;
let ch = match c.unicode_char() {
Some(ch) => format!("{ch:?}"),
None => format!("U+{:04X}", c.unicode_value()),
};
let loose_s = loose.map_or("?".into(), |l| {
format!(
"{:>6.2} {:>6.2} {:>5.2} {:>5.2}",
l.left().value,
page_h - l.top().value,
l.width().value,
l.height().value
)
});
let tight_s = tight.map_or("?".into(), |t| {
format!("{:>6.2}-{:>6.2}", t.left().value, t.right().value)
});
let origin_s = origin.map_or("?".into(), |(x, y)| {
format!("{:>6.2} {:>7.2}", x.value, page_h - y.value)
});
let gap_s = match gap {
Some((gl, gt)) => format!(
"{gl:>5.2} {} {:>5.2}",
gt.map_or(" ?".into(), |g| format!("{g:>5.2}")),
if size > 0.0 { gl / size } else { 0.0 }
),
None => String::new(),
};
let mut extra = Vec::new();
if let Ok(a) = c.angle_degrees() {
if a.abs() > 0.01 {
extra.push(format!("angle={a:.1}"));
}
}
if let Some((objs, obj_marks)) = &marks {
match objs.get(i).and_then(|p| p.as_ref()) {
Some(path) => {
let p: Vec<String> = path.iter().map(|n| n.to_string()).collect();
extra.push(format!("obj={}", p.join(".")));
if let Some(m) = marks_at(obj_marks, path) {
for key in TEXT_PARAMS {
if let Some(v) = m.marks.iter().rev().find_map(|mk| mk.str_param(key)) {
extra.push(format!("{key}={:?}", truncate(v, 40)));
}
}
}
}
None => extra.push("obj=-".into()),
}
}
if c.is_hyphen().unwrap_or(false) {
extra.push("hyphen".into());
}
if !c.has_unicode_map_error().unwrap_or(true) {
extra.push("unicode-map-error".into());
}
outln!(
" {i:>6} {ch:<8} {} {loose_s} | {tight_s} | {origin_s} | {size:>4.1} {:<22} | {gap_s}{}",
if generated { "G" } else { "." },
truncate(strip_subset(&c.font_name()), 22),
if extra.is_empty() {
String::new()
} else {
format!(" [{}]", extra.join(","))
},
);
}
if region.is_some() {
outln!(" ({shown} chars in region)");
}
}
fn strip_subset(name: &str) -> &str {
match name.split_once('+') {
Some((p, rest)) if p.len() == 6 && p.bytes().all(|b| b.is_ascii_uppercase()) => rest,
_ => name,
}
}
fn print_elem(e: &tags::Elem, depth: usize) {
let mut line = format!("{}{}", " ".repeat(depth), e.kind);
let ids: Vec<String> = e
.mcids
.iter()
.filter(|m| **m >= 0)
.map(|m| m.to_string())
.collect();
if !ids.is_empty() {
line.push_str(&format!(" mcid={}", ids.join(",")));
}
if let Some(a) = &e.alt {
line.push_str(&format!(" alt={:?}", truncate(a, 60)));
}
if let Some(a) = &e.actual_text {
line.push_str(&format!(" actual={:?}", truncate(a, 60)));
}
if let Some(a) = &e.expansion {
line.push_str(&format!(" e={:?}", truncate(a, 60)));
}
outln!("{line}");
for c in &e.children {
print_elem(c, depth + 1);
}
}
fn fmt_rect(r: &PdfRect, page_h: f32) -> String {
format!(
"x={:>5.1} y={:>5.1} w={:>5.1} h={:>4.1}",
r.left().value,
page_h - r.top().value,
r.width().value,
r.height().value
)
}
fn weight_value(w: PdfFontWeight) -> u32 {
match w {
PdfFontWeight::Weight100 => 100,
PdfFontWeight::Weight200 => 200,
PdfFontWeight::Weight300 => 300,
PdfFontWeight::Weight400Normal => 400,
PdfFontWeight::Weight500 => 500,
PdfFontWeight::Weight600 => 600,
PdfFontWeight::Weight700Bold => 700,
PdfFontWeight::Weight800 => 800,
PdfFontWeight::Weight900 => 900,
PdfFontWeight::Custom(v) => v,
}
}
fn truncate(s: &str, max: usize) -> String {
if s.chars().count() <= max {
s.to_string()
} else {
let mut t: String = s.chars().take(max).collect();
t.push('…');
t
}
}