pdfsift 0.1.0

PDF to structured Markdown for LLM agents. Heuristics only: no AI model, no network.
//! `pdfsift <file.pdf>`: the PDFium side of the conversion (open the file, read the
//! outline, run the layout pipeline) and the output. The Markdown itself is built by
//! the pure [`crate::markdown::render`].

use std::collections::BTreeSet;
use std::io::{self, Write};
use std::path::{Path, PathBuf};

use anyhow::{Context, Result};
use pdfium_render::prelude::*;

use crate::markdown::{self, HeadingSource, OutlineEntry};
use crate::{engine, layout, tags};

pub struct Options {
    /// 0-based page indices; None = all.
    pub pages: Option<Vec<PdfPageIndex>>,
    pub output: Option<PathBuf>,
    pub page_markers: bool,
    pub quiet: bool,
    pub heading_source: HeadingSource,
}

/// Outline depth guard: a malicious outline can be arbitrarily deep or cyclic.
const MAX_OUTLINE_DEPTH: usize = 16;
const MAX_OUTLINE_ENTRIES: usize = 10_000;

fn outline(doc: &PdfDocument) -> Vec<OutlineEntry> {
    fn walk(first: &PdfBookmark, depth: usize, out: &mut Vec<OutlineEntry>) {
        // iter_siblings() does not include the node itself.
        for bm in std::iter::once(first.clone()).chain(first.iter_siblings()) {
            if out.len() >= MAX_OUTLINE_ENTRIES {
                return;
            }
            let page = bm
                .destination()
                .and_then(|d| d.page_index().ok())
                .and_then(|i| usize::try_from(i).ok());
            if let Some(i) = page {
                out.push(OutlineEntry {
                    title: bm.title().unwrap_or_default(),
                    level: depth,
                    page: i + 1,
                });
            }
            if depth < MAX_OUTLINE_DEPTH
                && let Some(child) = bm.first_child()
            {
                walk(&child, depth + 1, out);
            }
        }
    }
    let mut out = Vec::new();
    if let Some(root) = doc.bookmarks().root() {
        walk(&root, 1, &mut out);
    }
    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 {} (is it a PDF? encrypted PDFs are not supported yet)",
            file.display()
        )
    })?;
    let raw_doc = tags::RawDoc::open(doc.bindings(), &file.to_string_lossy());
    let pages = layout::analyze_document(&doc, raw_doc.as_ref());
    let selected: Option<BTreeSet<usize>> = opts.pages.as_ref().map(|p| {
        p.iter()
            .filter_map(|&i| usize::try_from(i).ok())
            .map(|i| i + 1)
            .collect()
    });
    let mopts = markdown::Options {
        source_name: file
            .file_name()
            .map(|n| n.to_string_lossy().into_owned())
            .unwrap_or_default(),
        pages: selected,
        page_markers: opts.page_markers,
        heading_source: opts.heading_source,
    };
    let out = markdown::render(&pages, &outline(&doc), &mopts);
    if !opts.quiet {
        for w in &out.warnings {
            eprintln!("warning: {w}");
        }
    }
    match &opts.output {
        Some(path) => std::fs::write(path, out.markdown.as_bytes())
            .with_context(|| format!("cannot write {}", path.display())),
        None => write_stdout(out.markdown.as_bytes()),
    }
}

/// One line to stdout for the streaming debug commands (see the `outln!` macro). These
/// write as they go (a `--chars` dump can be large), so instead of threading a `Result`
/// through every printer, a closed pipe exits with status 0 (the reader is gone, which is
/// what `| head` means) and any other write error exits with status 1.
pub fn print_line(args: std::fmt::Arguments) {
    let mut so = io::stdout().lock();
    if let Err(e) = so.write_fmt(args).and_then(|()| {
        so.write_all(
            b"
",
        )
    }) {
        if e.kind() == io::ErrorKind::BrokenPipe {
            std::process::exit(0);
        }
        eprintln!("error: cannot write to stdout: {e}");
        std::process::exit(1);
    }
}

/// Writes to stdout; a closed pipe (`pdfsift x.pdf | head`) is not an error.
pub fn write_stdout(bytes: &[u8]) -> Result<()> {
    let mut so = io::stdout().lock();
    match so.write_all(bytes).and_then(|()| so.flush()) {
        Err(e) if e.kind() == io::ErrorKind::BrokenPipe => Ok(()),
        r => r.context("cannot write to stdout"),
    }
}