pdfsift 0.1.0

PDF to structured Markdown for LLM agents. Heuristics only: no AI model, no network.
/// `println!` for the streaming debug commands (`dump`, `blocks`): a closed pipe
/// (`pdfsift dump x.pdf | head`) ends the process quietly instead of panicking.
/// Defined before the modules so they can use it (textual macro scope).
macro_rules! outln {
    () => {
        $crate::convert::print_line(format_args!(""))
    };
    ($($arg:tt)*) => {
        $crate::convert::print_line(format_args!($($arg)*))
    };
}

mod blocks;
mod convert;
mod dump;
mod engine;
mod layout;
mod markdown;
mod tags;

use std::path::PathBuf;

use anyhow::{Result, bail};
use clap::{Parser, Subcommand, ValueEnum};

/// PDF to structured Markdown for LLM agents.
///
/// Examples:
///   pdfsift paper.pdf > paper.md
///   pdfsift report.pdf -o report.md
///   pdfsift book.pdf --pages 10-12 | head -50
///   pdfsift book.pdf --no-page-markers
///
/// Running headers, footers and page numbers are removed, columns are read in order,
/// line-end hyphens are undone, and headings come from the outline, the tags or the
/// typography. `<!-- page: N -->` comments mark page starts. Warnings go to stderr.
/// Exit codes: 0 success (maybe with warnings), 1 error, 2 invalid usage.
#[derive(Parser)]
#[command(
    version,
    about,
    verbatim_doc_comment,
    args_conflicts_with_subcommands = true
)]
struct Cli {
    #[command(subcommand)]
    command: Option<Command>,
    /// PDF file to convert to Markdown.
    file: Option<PathBuf>,
    /// Write the Markdown to this file instead of stdout.
    #[arg(short, long)]
    output: Option<PathBuf>,
    /// Pages to convert, 1-based (e.g. "3", "2-4", "1,5-7"). Default: all.
    #[arg(long)]
    pages: Option<String>,
    /// Do not emit the `<!-- page: N -->` comments.
    #[arg(long)]
    no_page_markers: bool,
    /// Suppress warnings on stderr.
    #[arg(short, long)]
    quiet: bool,
    /// Debug: force the heading source (validation of each source on the corpus).
    #[arg(long, value_enum, default_value_t = Headings::Auto, hide = true)]
    heading_source: Headings,
}

#[derive(Clone, Copy, ValueEnum)]
enum Headings {
    Auto,
    Outline,
    Tags,
    Typography,
}

#[derive(Subcommand)]
enum Command {
    /// Debug: print what the PDF engine sees (text objects, fonts, images, paths, links, tags).
    Dump {
        /// PDF file to inspect.
        file: PathBuf,
        /// Pages to dump, 1-based (e.g. "1", "2-4"). Default: all.
        #[arg(long)]
        pages: Option<String>,
        /// List every vector path object instead of a per-page summary.
        #[arg(long)]
        paths: bool,
        /// Skip the structure tree (tagged PDF) section.
        #[arg(long)]
        no_tags: bool,
        /// Also print every character (bounds, origin, font, generated flag, gap to previous).
        #[arg(long)]
        chars: bool,
        /// Restrict --chars to a region "x,y,w,h" in points, y measured from the top.
        #[arg(long, requires = "chars", allow_hyphen_values = true)]
        region: Option<String>,
        /// Show marked-content marks (MCID, ActualText, Alt, E) per object; with --chars,
        /// also the object and ActualText of each char.
        #[arg(long)]
        marks: bool,
    },
    /// Debug: print the layout blocks (characters grouped into words, lines and blocks).
    Blocks {
        /// PDF file to inspect.
        file: PathBuf,
        /// Pages to show, 1-based (e.g. "1", "2-4"). Default: all.
        #[arg(long)]
        pages: Option<String>,
        /// Also print each line with its words, positions and style changes.
        #[arg(long)]
        words: bool,
        /// Print the raw characters (as PDFium reports them) instead of blocks.
        #[arg(long)]
        chars: bool,
    },
}

fn main() -> Result<()> {
    let cli = Cli::parse();
    match cli.command {
        None => {
            let Some(file) = cli.file else {
                bail!("no input file: run `pdfsift <file.pdf>` (see `pdfsift --help`)");
            };
            let opts = convert::Options {
                pages: dump::parse_pages(cli.pages.as_deref())?,
                output: cli.output,
                page_markers: !cli.no_page_markers,
                quiet: cli.quiet,
                heading_source: match cli.heading_source {
                    Headings::Auto => markdown::HeadingSource::Auto,
                    Headings::Outline => markdown::HeadingSource::Outline,
                    Headings::Tags => markdown::HeadingSource::Tags,
                    Headings::Typography => markdown::HeadingSource::Typography,
                },
            };
            convert::run(&file, &opts)
        }
        Some(Command::Dump {
            file,
            pages,
            paths,
            no_tags,
            chars,
            region,
            marks,
        }) => {
            let opts = dump::Options {
                pages: dump::parse_pages(pages.as_deref())?,
                paths,
                tags: !no_tags,
                chars,
                region: dump::parse_region(region.as_deref())?,
                marks,
            };
            dump::run(&file, &opts)
        }
        Some(Command::Blocks {
            file,
            pages,
            words,
            chars,
        }) => {
            let opts = blocks::Options {
                pages: dump::parse_pages(pages.as_deref())?,
                words,
                chars,
            };
            blocks::run(&file, &opts)
        }
    }
}