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 {
pub pages: Option<Vec<PdfPageIndex>>,
pub output: Option<PathBuf>,
pub page_markers: bool,
pub quiet: bool,
pub heading_source: HeadingSource,
}
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>) {
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()),
}
}
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);
}
}
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"),
}
}