Files
Pictor-public/crates/pdf/src/reader.rs
T

194 lines
6.9 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//! Reading: page sizes, rendering, text, search, outline. All through pdfium (it is what Chrome and Edge use, so a
//! file Edge opens, Pictor opens).
use crate::{Engine, PdfError, ViewRect};
use image::DynamicImage;
use pdfium_render::prelude::*;
use serde::Serialize;
/// Rendering never makes a bitmap larger than this many pixels (about 200 MB of RGBA).
pub const MAX_RENDER_PIXELS: i64 = 50_000_000;
#[derive(Debug, Clone, Serialize)]
pub struct DocInfo {
pub pages: Vec<PageInfo>,
pub outline: Vec<OutlineItem>,
pub has_form: bool,
pub encrypted: bool,
}
#[derive(Debug, Clone, Serialize)]
pub struct PageInfo {
/// Displayed size in points.
pub width: f32,
pub height: f32,
pub label: Option<String>,
}
#[derive(Debug, Clone, Serialize)]
pub struct OutlineItem {
pub title: String,
pub page: Option<usize>,
pub depth: u32,
}
#[derive(Debug, Clone, Serialize)]
pub struct SearchHit {
pub page: usize,
/// The hit's boxes in view space.
pub rects: Vec<ViewRect>,
}
pub fn info(engine: &Engine, bytes: &[u8], password: Option<&str>) -> Result<DocInfo, PdfError> {
let doc = engine.open(bytes, password)?;
let mut pages = Vec::new();
for page in doc.pages().iter() {
pages.push(PageInfo {
width: page.width().value,
height: page.height().value,
label: page.label().map(Into::into),
});
}
let mut outline = Vec::new();
fn walk(b: PdfBookmark, depth: u32, out: &mut Vec<OutlineItem>, budget: &mut u32) {
if *budget == 0 || depth > 32 {
return;
}
*budget -= 1;
let page = b.destination().and_then(|d| d.page_index().ok()).map(|i| i as usize);
out.push(OutlineItem { title: b.title().unwrap_or_default(), page, depth });
if let Some(child) = b.first_child() {
let mut next = Some(child);
while let Some(c) = next {
next = c.next_sibling();
walk(c, depth + 1, out, budget);
}
}
}
let mut budget = 5000;
let mut next = doc.bookmarks().root();
while let Some(b) = next {
next = b.next_sibling();
walk(b, 0, &mut outline, &mut budget);
}
let has_form = doc.form().is_some();
Ok(DocInfo { pages, outline, has_form, encrypted: password.is_some() })
}
/// The displayed size of every page, in points.
pub fn page_sizes(engine: &Engine, bytes: &[u8], password: Option<&str>) -> Result<Vec<(f32, f32)>, PdfError> {
let doc = engine.open(bytes, password)?;
Ok(doc.pages().iter().map(|p| (p.width().value, p.height().value)).collect())
}
pub(crate) fn render_doc_page(
doc: &PdfDocument,
index: usize,
width_px: u32,
forms: bool,
) -> Result<DynamicImage, PdfError> {
let page = doc.pages().get(index as i32).map_err(|_| PdfError::NoSuchPage(index + 1))?;
let (w, h) = (page.width().value.max(1.0), page.height().value.max(1.0));
let width = width_px.clamp(1, 20_000) as i64;
let height = ((width as f32) * h / w).ceil().max(1.0) as i64;
if width * height > MAX_RENDER_PIXELS {
return Err(PdfError::TooLarge(format!("page {} would render at {width} × {height} pixels", index + 1)));
}
let cfg = PdfRenderConfig::new()
.set_target_size(width as i32, height as i32)
.render_form_data(forms)
.render_annotations(true)
.set_clear_color(PdfColor::WHITE);
page.render_with_config(&cfg).and_then(|b| b.as_image()).map_err(PdfError::from_pdfium)
}
/// Renders page `index` (0-based) `width_px` pixels wide, with annotations and form fields drawn.
pub fn render_page(
engine: &Engine,
bytes: &[u8],
password: Option<&str>,
index: usize,
width_px: u32,
) -> Result<DynamicImage, PdfError> {
let doc = engine.open(bytes, password)?;
render_doc_page(&doc, index, width_px, true)
}
/// The text of every page, in order.
pub fn extract_text(engine: &Engine, bytes: &[u8], password: Option<&str>) -> Result<Vec<String>, PdfError> {
let doc = engine.open(bytes, password)?;
let mut out = Vec::new();
for page in doc.pages().iter() {
out.push(page_text(&page)?);
}
Ok(out)
}
/// Case-insensitive search over every page; at most `limit` hits.
pub fn search(
engine: &Engine,
bytes: &[u8],
password: Option<&str>,
query: &str,
limit: usize,
) -> Result<Vec<SearchHit>, PdfError> {
if query.trim().is_empty() {
return Ok(Vec::new());
}
let doc = engine.open(bytes, password)?;
let mut hits = Vec::new();
for (i, page) in doc.pages().iter().enumerate() {
let frame = page_frame(&page);
let text = page.text().map_err(PdfError::from_pdfium)?;
let search = text.search(query, &PdfSearchOptions::new()).map_err(PdfError::from_pdfium)?;
while let Some(segments) = search.find_next() {
let rects = segments.iter().map(|s| frame.user_to_view(s.bounds())).collect();
hits.push(SearchHit { page: i, rects });
if hits.len() >= limit {
return Ok(hits);
}
}
}
Ok(hits)
}
/// All text of a page. (pdfium-render's `PdfPageText::all` clips to the unrotated page size, so a page with
/// `/Rotate 90` came out empty; this asks for everything inside an unbounded rectangle instead.)
pub(crate) fn page_text(page: &PdfPage) -> Result<String, PdfError> {
let text = page.text().map_err(PdfError::from_pdfium)?;
Ok(text.inside_rect(PdfRect::new_from_values(-1.0e6, -1.0e6, 1.0e6, 1.0e6)))
}
pub(crate) fn page_frame(page: &PdfPage) -> crate::geometry::PageFrame {
// `bounding` is pdfium's effective crop box (inherited boxes included); crop/media only read the page itself.
let crop = page
.boundaries()
.bounding()
.or_else(|_| page.boundaries().crop())
.or_else(|_| page.boundaries().media())
.map(|b| b.bounds)
.unwrap_or(PdfRect::ZERO);
let rotate = match page.rotation() {
Ok(PdfPageRenderRotation::Degrees90) => 90,
Ok(PdfPageRenderRotation::Degrees180) => 180,
Ok(PdfPageRenderRotation::Degrees270) => 270,
_ => 0,
};
let c = [crop.left().value, crop.bottom().value, crop.right().value, crop.top().value];
crate::geometry::PageFrame { crop: [c[0].min(c[2]), c[1].min(c[3]), c[0].max(c[2]), c[1].max(c[3])], rotate }
}
impl crate::geometry::PageFrame {
/// A user-space rectangle → view space.
pub(crate) fn user_to_view(&self, r: PdfRect) -> ViewRect {
let [x0, y0, x1, y1] = self.crop;
let (l, b, rt, t) = (r.left().value, r.bottom().value, r.right().value, r.top().value);
let (vx0, vy0, vx1, vy1) = match self.rotate {
90 => (b - y0, l - x0, t - y0, rt - x0),
180 => (x1 - rt, b - y0, x1 - l, t - y0),
270 => (y1 - t, x1 - rt, y1 - b, x1 - l),
_ => (l - x0, y1 - t, rt - x0, y1 - b),
};
ViewRect { x: vx0.min(vx1), y: vy0.min(vy1), w: (vx1 - vx0).abs(), h: (vy1 - vy0).abs() }
}
}