[repo] Format, clippy clean, FORMATS.md, the full crate table in DEPENDENCIES.md
This commit is contained in:
+1141
-972
File diff suppressed because it is too large
Load Diff
@@ -32,7 +32,9 @@ impl Engine {
|
||||
}
|
||||
|
||||
pub(crate) fn open<'a>(&'a self, bytes: &'a [u8], password: Option<&str>) -> Result<PdfDocument<'a>, PdfError> {
|
||||
self.pdfium.load_pdf_from_byte_slice(bytes, password).map_err(|e| PdfError::from_pdfium_open(e, password.is_some()))
|
||||
self.pdfium
|
||||
.load_pdf_from_byte_slice(bytes, password)
|
||||
.map_err(|e| PdfError::from_pdfium_open(e, password.is_some()))
|
||||
}
|
||||
|
||||
pub(crate) fn new_document(&self) -> Result<PdfDocument<'_>, PdfError> {
|
||||
|
||||
@@ -61,7 +61,7 @@ impl PageFrame {
|
||||
}
|
||||
|
||||
pub(crate) fn normalise_rotate(r: i64) -> u16 {
|
||||
(((r % 360) + 360) % 360 / 90 * 90) as u16
|
||||
(r.rem_euclid(360) / 90 * 90) as u16
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -20,7 +20,7 @@ mod security;
|
||||
pub use edit::*;
|
||||
pub use engine::Engine;
|
||||
pub use error::PdfError;
|
||||
pub use geometry::{ViewRect, ViewPoint};
|
||||
pub use geometry::{ViewPoint, ViewRect};
|
||||
pub use pages::*;
|
||||
pub use reader::*;
|
||||
pub use redact::{RedactOptions, Redacted, Redaction, redact};
|
||||
@@ -28,8 +28,7 @@ pub use security::{is_encrypted, protect, unlock};
|
||||
|
||||
/// lopdf loading with the caps Pictor uses everywhere (a stream may decompress to at most 256 MiB).
|
||||
pub(crate) fn lopdf_load(bytes: &[u8], password: Option<&str>) -> Result<lopdf::Document, PdfError> {
|
||||
let mut opts = lopdf::LoadOptions::default();
|
||||
opts.max_decompressed_size = Some(256 << 20);
|
||||
let mut opts = lopdf::LoadOptions { max_decompressed_size: Some(256 << 20), ..Default::default() };
|
||||
if let Some(p) = password {
|
||||
opts.password = Some(p.to_owned());
|
||||
}
|
||||
|
||||
+304
-299
@@ -1,299 +1,304 @@
|
||||
//! Page operations (reorder, rotate, delete, insert blank, extract, split) with lopdf, in place, so the form,
|
||||
//! bookmarks and everything else of the document stay; merge with pdfium's page import; images → PDF with lopdf
|
||||
//! (a JPEG goes in as it is, without re-encoding); PDF → images with pdfium.
|
||||
use crate::{Engine, PdfError, lopdf_load, lopdf_save, reader::render_doc_page};
|
||||
use image::{DynamicImage, GenericImageView};
|
||||
use lopdf::{Dictionary, Document, Object, ObjectId, Stream, dictionary};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::HashSet;
|
||||
|
||||
/// One page of the new order.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[serde(tag = "kind", rename_all = "snake_case")]
|
||||
pub enum PageSpec {
|
||||
/// Page `index` (0-based) of the document, turned by `rotate` degrees clockwise (a multiple of 90).
|
||||
Existing {
|
||||
index: usize,
|
||||
#[serde(default)]
|
||||
rotate: i32,
|
||||
},
|
||||
/// A blank page of this size in points.
|
||||
Blank { width: f32, height: f32 },
|
||||
}
|
||||
|
||||
const INHERITABLE: [&[u8]; 4] = [b"Resources", b"MediaBox", b"CropBox", b"Rotate"];
|
||||
|
||||
/// Copies inherited attributes down onto each page, so pages can be moved freely.
|
||||
fn materialise_inherited(doc: &mut Document, pages: &[ObjectId]) {
|
||||
for &page in pages {
|
||||
for key in INHERITABLE {
|
||||
if doc.get_dictionary(page).map(|d| d.has(key)).unwrap_or(true) {
|
||||
continue;
|
||||
}
|
||||
let mut current = doc.get_dictionary(page).ok().and_then(|d| d.get(b"Parent").ok()).and_then(|p| p.as_reference().ok());
|
||||
let mut depth = 0;
|
||||
let mut value = None;
|
||||
while let Some(id) = current {
|
||||
depth += 1;
|
||||
if depth > 64 {
|
||||
break;
|
||||
}
|
||||
let Ok(d) = doc.get_dictionary(id) else { break };
|
||||
if let Ok(v) = d.get(key) {
|
||||
value = Some(v.clone());
|
||||
break;
|
||||
}
|
||||
current = d.get(b"Parent").ok().and_then(|p| p.as_reference().ok());
|
||||
}
|
||||
if let (Some(v), Ok(d)) = (value, doc.get_dictionary_mut(page)) {
|
||||
d.set(key, v);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn pages_root(doc: &Document) -> Result<ObjectId, PdfError> {
|
||||
doc.catalog()
|
||||
.ok()
|
||||
.and_then(|c| c.get(b"Pages").ok())
|
||||
.and_then(|p| p.as_reference().ok())
|
||||
.ok_or_else(|| PdfError::Damaged("it has no page tree".into()))
|
||||
}
|
||||
|
||||
/// Builds the new page order. Pages left out are deleted, together with their annotations and the form fields
|
||||
/// that only lived on them.
|
||||
pub fn reorganise(bytes: &[u8], password: Option<&str>, specs: &[PageSpec]) -> Result<Vec<u8>, PdfError> {
|
||||
let mut doc = lopdf_load(bytes, password)?;
|
||||
reorganise_doc(&mut doc, specs)?;
|
||||
doc.prune_objects();
|
||||
lopdf_save(&mut doc)
|
||||
}
|
||||
|
||||
pub(crate) fn reorganise_doc(doc: &mut Document, specs: &[PageSpec]) -> Result<(), PdfError> {
|
||||
if specs.is_empty() {
|
||||
return Err(PdfError::Invalid("A PDF needs at least one page.".into()));
|
||||
}
|
||||
let pages: Vec<ObjectId> = doc.get_pages().values().copied().collect();
|
||||
materialise_inherited(doc, &pages);
|
||||
let root = pages_root(doc)?;
|
||||
let mut used = HashSet::new();
|
||||
let mut kids = Vec::new();
|
||||
for spec in specs {
|
||||
match *spec {
|
||||
PageSpec::Existing { index, rotate } => {
|
||||
let &src = pages.get(index).ok_or(PdfError::NoSuchPage(index + 1))?;
|
||||
if rotate % 90 != 0 {
|
||||
return Err(PdfError::Invalid("Pages turn in steps of 90 degrees.".into()));
|
||||
}
|
||||
// The same page twice: the second is a shallow copy (its content and resources are shared).
|
||||
let id = if used.insert(src) {
|
||||
src
|
||||
} else {
|
||||
let copy = doc.get_dictionary(src).map_err(|e| PdfError::Damaged(e.to_string()))?.clone();
|
||||
let mut copy = copy;
|
||||
copy.remove(b"Annots");
|
||||
doc.add_object(copy)
|
||||
};
|
||||
let d = doc.get_dictionary_mut(id).map_err(|e| PdfError::Damaged(e.to_string()))?;
|
||||
let current = d.get(b"Rotate").and_then(Object::as_i64).unwrap_or(0);
|
||||
d.set("Rotate", crate::geometry::normalise_rotate(current + rotate as i64) as i64);
|
||||
d.set("Parent", root);
|
||||
kids.push(Object::Reference(id));
|
||||
}
|
||||
PageSpec::Blank { width, height } => {
|
||||
if !(width >= 3.0 && height >= 3.0 && width <= 14_400.0 && height <= 14_400.0) {
|
||||
return Err(PdfError::Invalid("A page must be between 3 and 14,400 points on each side.".into()));
|
||||
}
|
||||
let content = doc.add_object(Stream::new(dictionary! {}, Vec::new()));
|
||||
let id = doc.add_object(dictionary! {
|
||||
"Type" => "Page", "Parent" => root, "Contents" => content, "Resources" => dictionary! {},
|
||||
"MediaBox" => vec![0.into(), 0.into(), Object::Real(width), Object::Real(height)],
|
||||
});
|
||||
kids.push(Object::Reference(id));
|
||||
}
|
||||
}
|
||||
}
|
||||
// Annotations of deleted pages, and the fields that only lived there.
|
||||
let mut removed = HashSet::new();
|
||||
for p in pages.iter().filter(|p| !used.contains(*p)) {
|
||||
if let Ok(Object::Array(a)) = doc.get_dictionary(*p).and_then(|d| d.get(b"Annots")) {
|
||||
removed.extend(a.iter().filter_map(|o| o.as_reference().ok()));
|
||||
}
|
||||
}
|
||||
crate::redact::prune_form_pub(doc, &removed);
|
||||
// Deleted pages go even if a bookmark, a link or the struct tree still points at them (those links then lead
|
||||
// nowhere, which every viewer tolerates); so do their annotations.
|
||||
for p in pages.iter().filter(|p| !used.contains(*p)) {
|
||||
doc.objects.remove(p);
|
||||
}
|
||||
for a in &removed {
|
||||
doc.objects.remove(a);
|
||||
}
|
||||
let count = kids.len() as i64;
|
||||
let mut root_dict = doc.get_dictionary(root).map_err(|e| PdfError::Damaged(e.to_string()))?.clone();
|
||||
for key in INHERITABLE {
|
||||
root_dict.remove(key);
|
||||
}
|
||||
root_dict.set("Kids", kids);
|
||||
root_dict.set("Count", count);
|
||||
root_dict.remove(b"Parent");
|
||||
doc.objects.insert(root, Object::Dictionary(root_dict));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// One document per range; `ranges` are 0-based inclusive page index pairs.
|
||||
pub fn split(bytes: &[u8], password: Option<&str>, ranges: &[(usize, usize)]) -> Result<Vec<Vec<u8>>, PdfError> {
|
||||
let mut out = Vec::new();
|
||||
for &(a, b) in ranges {
|
||||
if a > b {
|
||||
return Err(PdfError::Invalid(format!("The range {}–{} runs backwards.", a + 1, b + 1)));
|
||||
}
|
||||
let specs: Vec<PageSpec> = (a..=b).map(|index| PageSpec::Existing { index, rotate: 0 }).collect();
|
||||
out.push(reorganise(bytes, password, &specs)?);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Parses "1-3, 5, 8-" style ranges (1-based, as the user types them) for a document of `pages` pages.
|
||||
pub fn parse_ranges(text: &str, pages: usize) -> Result<Vec<(usize, usize)>, PdfError> {
|
||||
let bad = || PdfError::Invalid(format!("\"{text}\" is not a page range like 1-3, 5, 8-."));
|
||||
let mut out = Vec::new();
|
||||
for part in text.split([',', ';']).map(str::trim).filter(|p| !p.is_empty()) {
|
||||
let (a, b) = match part.split_once(['-', '–']) {
|
||||
Some((a, b)) => {
|
||||
let a: usize = if a.trim().is_empty() { 1 } else { a.trim().parse().map_err(|_| bad())? };
|
||||
let b: usize = if b.trim().is_empty() { pages } else { b.trim().parse().map_err(|_| bad())? };
|
||||
(a, b)
|
||||
}
|
||||
None => {
|
||||
let n: usize = part.parse().map_err(|_| bad())?;
|
||||
(n, n)
|
||||
}
|
||||
};
|
||||
if a == 0 || b == 0 || a > pages || b > pages {
|
||||
return Err(PdfError::Invalid(format!("This PDF has pages 1 to {pages}; \"{part}\" is outside them.")));
|
||||
}
|
||||
if a > b {
|
||||
return Err(bad());
|
||||
}
|
||||
out.push((a - 1, b - 1));
|
||||
}
|
||||
if out.is_empty() {
|
||||
return Err(bad());
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Merges documents in order. Each input is `(bytes, password)`. Form fields of merged documents keep their look
|
||||
/// but are no longer fillable (pdfium imports pages, not forms); bookmarks are not carried over.
|
||||
pub fn merge(engine: &Engine, inputs: &[(&[u8], Option<&str>)]) -> Result<Vec<u8>, PdfError> {
|
||||
if inputs.len() < 2 {
|
||||
return Err(PdfError::Invalid("Choose at least two PDFs to merge.".into()));
|
||||
}
|
||||
let mut target = engine.new_document()?;
|
||||
for (i, (bytes, password)) in inputs.iter().enumerate() {
|
||||
let source = engine.open(bytes, *password).map_err(|e| match e {
|
||||
PdfError::NeedsPassword => PdfError::Invalid(format!("PDF number {} needs its password first.", i + 1)),
|
||||
other => other,
|
||||
})?;
|
||||
target.pages_mut().append(&source).map_err(PdfError::from_pdfium)?;
|
||||
}
|
||||
crate::engine::pdfium_save(&target)
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum PageFit {
|
||||
/// Each page is the image's own size (at 96 dpi, or the image's resolution if it has one).
|
||||
Image,
|
||||
/// A4 portrait or landscape (whichever suits the image), with a margin.
|
||||
A4,
|
||||
Letter,
|
||||
}
|
||||
|
||||
/// One page per image. JPEGs are embedded as they are (no quality loss); other images are stored losslessly.
|
||||
pub fn images_to_pdf(images: &[(Vec<u8>, DynamicImage)], fit: PageFit, margin_pt: f32) -> Result<Vec<u8>, PdfError> {
|
||||
if images.is_empty() {
|
||||
return Err(PdfError::Invalid("Choose at least one image.".into()));
|
||||
}
|
||||
let mut doc = Document::with_version("1.7");
|
||||
let pages_id = doc.new_object_id();
|
||||
let mut kids = Vec::new();
|
||||
for (bytes, img) in images {
|
||||
let (w, h) = img.dimensions();
|
||||
let is_jpeg = bytes.starts_with(&[0xFF, 0xD8, 0xFF]);
|
||||
let image_id = if is_jpeg && matches!(img.color().channel_count(), 1 | 3) {
|
||||
let cs = if img.color().channel_count() == 1 { "DeviceGray" } else { "DeviceRGB" };
|
||||
let mut s = Stream::new(
|
||||
dictionary! {"Type" => "XObject", "Subtype" => "Image", "Width" => w as i64, "Height" => h as i64,
|
||||
"ColorSpace" => cs, "BitsPerComponent" => 8, "Filter" => "DCTDecode"},
|
||||
bytes.clone(),
|
||||
);
|
||||
s.allows_compression = false;
|
||||
doc.add_object(s)
|
||||
} else {
|
||||
let rgba = img.to_rgba8();
|
||||
let has_alpha = rgba.pixels().any(|p| p.0[3] != 255);
|
||||
let rgb: Vec<u8> = rgba.pixels().flat_map(|p| [p.0[0], p.0[1], p.0[2]]).collect();
|
||||
let mut dict = dictionary! {"Type" => "XObject", "Subtype" => "Image", "Width" => w as i64,
|
||||
"Height" => h as i64, "ColorSpace" => "DeviceRGB", "BitsPerComponent" => 8};
|
||||
if has_alpha {
|
||||
let alpha: Vec<u8> = rgba.pixels().map(|p| p.0[3]).collect();
|
||||
let mut smask = Stream::new(
|
||||
dictionary! {"Type" => "XObject", "Subtype" => "Image", "Width" => w as i64, "Height" => h as i64,
|
||||
"ColorSpace" => "DeviceGray", "BitsPerComponent" => 8},
|
||||
alpha,
|
||||
);
|
||||
let _ = smask.compress();
|
||||
dict.set("SMask", doc.add_object(smask));
|
||||
}
|
||||
let mut s = Stream::new(dict, rgb);
|
||||
let _ = s.compress();
|
||||
doc.add_object(s)
|
||||
};
|
||||
let (iw, ih) = (w as f32 * 0.75, h as f32 * 0.75);
|
||||
let (pw, ph) = match fit {
|
||||
PageFit::Image => (iw, ih),
|
||||
PageFit::A4 | PageFit::Letter => {
|
||||
let (a, b) = if fit == PageFit::A4 { (595.28, 841.89) } else { (612.0, 792.0) };
|
||||
if w > h { (b, a) } else { (a, b) }
|
||||
}
|
||||
};
|
||||
let margin = if fit == PageFit::Image { 0.0 } else { margin_pt.clamp(0.0, pw.min(ph) / 3.0) };
|
||||
let scale = ((pw - 2.0 * margin) / iw).min((ph - 2.0 * margin) / ih).min(if fit == PageFit::Image { 1.0 } else { f32::MAX });
|
||||
let (dw, dh) = (iw * scale, ih * scale);
|
||||
let (x, y) = ((pw - dw) / 2.0, (ph - dh) / 2.0);
|
||||
let content = format!("q {dw:.3} 0 0 {dh:.3} {x:.3} {y:.3} cm /Im0 Do Q").into_bytes();
|
||||
let content_id = doc.add_object(Stream::new(dictionary! {}, content));
|
||||
let page = doc.add_object(dictionary! {
|
||||
"Type" => "Page", "Parent" => pages_id, "Contents" => content_id,
|
||||
"MediaBox" => vec![0.into(), 0.into(), Object::Real(pw), Object::Real(ph)],
|
||||
"Resources" => dictionary! {"XObject" => Dictionary::from_iter([(b"Im0".to_vec(), Object::Reference(image_id))])},
|
||||
});
|
||||
kids.push(Object::Reference(page));
|
||||
}
|
||||
let count = kids.len() as i64;
|
||||
doc.objects.insert(pages_id, Object::Dictionary(dictionary! {"Type" => "Pages", "Kids" => kids, "Count" => count}));
|
||||
let catalog = doc.add_object(dictionary! {"Type" => "Catalog", "Pages" => pages_id});
|
||||
doc.trailer.set("Root", catalog);
|
||||
lopdf_save(&mut doc)
|
||||
}
|
||||
|
||||
/// Renders the chosen pages (0-based) at `dpi`.
|
||||
pub fn pages_to_images(
|
||||
engine: &Engine,
|
||||
bytes: &[u8],
|
||||
password: Option<&str>,
|
||||
pages: &[usize],
|
||||
dpi: u32,
|
||||
) -> Result<Vec<DynamicImage>, PdfError> {
|
||||
let doc = engine.open(bytes, password)?;
|
||||
let mut out = Vec::new();
|
||||
for &i in pages {
|
||||
let page = doc.pages().get(i as i32).map_err(|_| PdfError::NoSuchPage(i + 1))?;
|
||||
let width = (page.width().value * dpi.clamp(36, 600) as f32 / 72.0).round().max(1.0) as u32;
|
||||
drop(page);
|
||||
out.push(render_doc_page(&doc, i, width, true)?);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
//! Page operations (reorder, rotate, delete, insert blank, extract, split) with lopdf, in place, so the form,
|
||||
//! bookmarks and everything else of the document stay; merge with pdfium's page import; images → PDF with lopdf
|
||||
//! (a JPEG goes in as it is, without re-encoding); PDF → images with pdfium.
|
||||
use crate::{Engine, PdfError, lopdf_load, lopdf_save, reader::render_doc_page};
|
||||
use image::{DynamicImage, GenericImageView};
|
||||
use lopdf::{Dictionary, Document, Object, ObjectId, Stream, dictionary};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::HashSet;
|
||||
|
||||
/// One page of the new order.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[serde(tag = "kind", rename_all = "snake_case")]
|
||||
pub enum PageSpec {
|
||||
/// Page `index` (0-based) of the document, turned by `rotate` degrees clockwise (a multiple of 90).
|
||||
Existing {
|
||||
index: usize,
|
||||
#[serde(default)]
|
||||
rotate: i32,
|
||||
},
|
||||
/// A blank page of this size in points.
|
||||
Blank { width: f32, height: f32 },
|
||||
}
|
||||
|
||||
const INHERITABLE: [&[u8]; 4] = [b"Resources", b"MediaBox", b"CropBox", b"Rotate"];
|
||||
|
||||
/// Copies inherited attributes down onto each page, so pages can be moved freely.
|
||||
fn materialise_inherited(doc: &mut Document, pages: &[ObjectId]) {
|
||||
for &page in pages {
|
||||
for key in INHERITABLE {
|
||||
if doc.get_dictionary(page).map(|d| d.has(key)).unwrap_or(true) {
|
||||
continue;
|
||||
}
|
||||
let mut current =
|
||||
doc.get_dictionary(page).ok().and_then(|d| d.get(b"Parent").ok()).and_then(|p| p.as_reference().ok());
|
||||
let mut depth = 0;
|
||||
let mut value = None;
|
||||
while let Some(id) = current {
|
||||
depth += 1;
|
||||
if depth > 64 {
|
||||
break;
|
||||
}
|
||||
let Ok(d) = doc.get_dictionary(id) else { break };
|
||||
if let Ok(v) = d.get(key) {
|
||||
value = Some(v.clone());
|
||||
break;
|
||||
}
|
||||
current = d.get(b"Parent").ok().and_then(|p| p.as_reference().ok());
|
||||
}
|
||||
if let (Some(v), Ok(d)) = (value, doc.get_dictionary_mut(page)) {
|
||||
d.set(key, v);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn pages_root(doc: &Document) -> Result<ObjectId, PdfError> {
|
||||
doc.catalog()
|
||||
.ok()
|
||||
.and_then(|c| c.get(b"Pages").ok())
|
||||
.and_then(|p| p.as_reference().ok())
|
||||
.ok_or_else(|| PdfError::Damaged("it has no page tree".into()))
|
||||
}
|
||||
|
||||
/// Builds the new page order. Pages left out are deleted, together with their annotations and the form fields
|
||||
/// that only lived on them.
|
||||
pub fn reorganise(bytes: &[u8], password: Option<&str>, specs: &[PageSpec]) -> Result<Vec<u8>, PdfError> {
|
||||
let mut doc = lopdf_load(bytes, password)?;
|
||||
reorganise_doc(&mut doc, specs)?;
|
||||
doc.prune_objects();
|
||||
lopdf_save(&mut doc)
|
||||
}
|
||||
|
||||
pub(crate) fn reorganise_doc(doc: &mut Document, specs: &[PageSpec]) -> Result<(), PdfError> {
|
||||
if specs.is_empty() {
|
||||
return Err(PdfError::Invalid("A PDF needs at least one page.".into()));
|
||||
}
|
||||
let pages: Vec<ObjectId> = doc.get_pages().values().copied().collect();
|
||||
materialise_inherited(doc, &pages);
|
||||
let root = pages_root(doc)?;
|
||||
let mut used = HashSet::new();
|
||||
let mut kids = Vec::new();
|
||||
for spec in specs {
|
||||
match *spec {
|
||||
PageSpec::Existing { index, rotate } => {
|
||||
let &src = pages.get(index).ok_or(PdfError::NoSuchPage(index + 1))?;
|
||||
if rotate % 90 != 0 {
|
||||
return Err(PdfError::Invalid("Pages turn in steps of 90 degrees.".into()));
|
||||
}
|
||||
// The same page twice: the second is a shallow copy (its content and resources are shared).
|
||||
let id = if used.insert(src) {
|
||||
src
|
||||
} else {
|
||||
let copy = doc.get_dictionary(src).map_err(|e| PdfError::Damaged(e.to_string()))?.clone();
|
||||
let mut copy = copy;
|
||||
copy.remove(b"Annots");
|
||||
doc.add_object(copy)
|
||||
};
|
||||
let d = doc.get_dictionary_mut(id).map_err(|e| PdfError::Damaged(e.to_string()))?;
|
||||
let current = d.get(b"Rotate").and_then(Object::as_i64).unwrap_or(0);
|
||||
d.set("Rotate", crate::geometry::normalise_rotate(current + rotate as i64) as i64);
|
||||
d.set("Parent", root);
|
||||
kids.push(Object::Reference(id));
|
||||
}
|
||||
PageSpec::Blank { width, height } => {
|
||||
if !(width >= 3.0 && height >= 3.0 && width <= 14_400.0 && height <= 14_400.0) {
|
||||
return Err(PdfError::Invalid("A page must be between 3 and 14,400 points on each side.".into()));
|
||||
}
|
||||
let content = doc.add_object(Stream::new(dictionary! {}, Vec::new()));
|
||||
let id = doc.add_object(dictionary! {
|
||||
"Type" => "Page", "Parent" => root, "Contents" => content, "Resources" => dictionary! {},
|
||||
"MediaBox" => vec![0.into(), 0.into(), Object::Real(width), Object::Real(height)],
|
||||
});
|
||||
kids.push(Object::Reference(id));
|
||||
}
|
||||
}
|
||||
}
|
||||
// Annotations of deleted pages, and the fields that only lived there.
|
||||
let mut removed = HashSet::new();
|
||||
for p in pages.iter().filter(|p| !used.contains(*p)) {
|
||||
if let Ok(Object::Array(a)) = doc.get_dictionary(*p).and_then(|d| d.get(b"Annots")) {
|
||||
removed.extend(a.iter().filter_map(|o| o.as_reference().ok()));
|
||||
}
|
||||
}
|
||||
crate::redact::prune_form_pub(doc, &removed);
|
||||
// Deleted pages go even if a bookmark, a link or the struct tree still points at them (those links then lead
|
||||
// nowhere, which every viewer tolerates); so do their annotations.
|
||||
for p in pages.iter().filter(|p| !used.contains(*p)) {
|
||||
doc.objects.remove(p);
|
||||
}
|
||||
for a in &removed {
|
||||
doc.objects.remove(a);
|
||||
}
|
||||
let count = kids.len() as i64;
|
||||
let mut root_dict = doc.get_dictionary(root).map_err(|e| PdfError::Damaged(e.to_string()))?.clone();
|
||||
for key in INHERITABLE {
|
||||
root_dict.remove(key);
|
||||
}
|
||||
root_dict.set("Kids", kids);
|
||||
root_dict.set("Count", count);
|
||||
root_dict.remove(b"Parent");
|
||||
doc.objects.insert(root, Object::Dictionary(root_dict));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// One document per range; `ranges` are 0-based inclusive page index pairs.
|
||||
pub fn split(bytes: &[u8], password: Option<&str>, ranges: &[(usize, usize)]) -> Result<Vec<Vec<u8>>, PdfError> {
|
||||
let mut out = Vec::new();
|
||||
for &(a, b) in ranges {
|
||||
if a > b {
|
||||
return Err(PdfError::Invalid(format!("The range {}–{} runs backwards.", a + 1, b + 1)));
|
||||
}
|
||||
let specs: Vec<PageSpec> = (a..=b).map(|index| PageSpec::Existing { index, rotate: 0 }).collect();
|
||||
out.push(reorganise(bytes, password, &specs)?);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Parses "1-3, 5, 8-" style ranges (1-based, as the user types them) for a document of `pages` pages.
|
||||
pub fn parse_ranges(text: &str, pages: usize) -> Result<Vec<(usize, usize)>, PdfError> {
|
||||
let bad = || PdfError::Invalid(format!("\"{text}\" is not a page range like 1-3, 5, 8-."));
|
||||
let mut out = Vec::new();
|
||||
for part in text.split([',', ';']).map(str::trim).filter(|p| !p.is_empty()) {
|
||||
let (a, b) = match part.split_once(['-', '–']) {
|
||||
Some((a, b)) => {
|
||||
let a: usize = if a.trim().is_empty() { 1 } else { a.trim().parse().map_err(|_| bad())? };
|
||||
let b: usize = if b.trim().is_empty() { pages } else { b.trim().parse().map_err(|_| bad())? };
|
||||
(a, b)
|
||||
}
|
||||
None => {
|
||||
let n: usize = part.parse().map_err(|_| bad())?;
|
||||
(n, n)
|
||||
}
|
||||
};
|
||||
if a == 0 || b == 0 || a > pages || b > pages {
|
||||
return Err(PdfError::Invalid(format!("This PDF has pages 1 to {pages}; \"{part}\" is outside them.")));
|
||||
}
|
||||
if a > b {
|
||||
return Err(bad());
|
||||
}
|
||||
out.push((a - 1, b - 1));
|
||||
}
|
||||
if out.is_empty() {
|
||||
return Err(bad());
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Merges documents in order. Each input is `(bytes, password)`. Form fields of merged documents keep their look
|
||||
/// but are no longer fillable (pdfium imports pages, not forms); bookmarks are not carried over.
|
||||
pub fn merge(engine: &Engine, inputs: &[(&[u8], Option<&str>)]) -> Result<Vec<u8>, PdfError> {
|
||||
if inputs.len() < 2 {
|
||||
return Err(PdfError::Invalid("Choose at least two PDFs to merge.".into()));
|
||||
}
|
||||
let mut target = engine.new_document()?;
|
||||
for (i, (bytes, password)) in inputs.iter().enumerate() {
|
||||
let source = engine.open(bytes, *password).map_err(|e| match e {
|
||||
PdfError::NeedsPassword => PdfError::Invalid(format!("PDF number {} needs its password first.", i + 1)),
|
||||
other => other,
|
||||
})?;
|
||||
target.pages_mut().append(&source).map_err(PdfError::from_pdfium)?;
|
||||
}
|
||||
crate::engine::pdfium_save(&target)
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum PageFit {
|
||||
/// Each page is the image's own size (at 96 dpi, or the image's resolution if it has one).
|
||||
Image,
|
||||
/// A4 portrait or landscape (whichever suits the image), with a margin.
|
||||
A4,
|
||||
Letter,
|
||||
}
|
||||
|
||||
/// One page per image. JPEGs are embedded as they are (no quality loss); other images are stored losslessly.
|
||||
pub fn images_to_pdf(images: &[(Vec<u8>, DynamicImage)], fit: PageFit, margin_pt: f32) -> Result<Vec<u8>, PdfError> {
|
||||
if images.is_empty() {
|
||||
return Err(PdfError::Invalid("Choose at least one image.".into()));
|
||||
}
|
||||
let mut doc = Document::with_version("1.7");
|
||||
let pages_id = doc.new_object_id();
|
||||
let mut kids = Vec::new();
|
||||
for (bytes, img) in images {
|
||||
let (w, h) = img.dimensions();
|
||||
let is_jpeg = bytes.starts_with(&[0xFF, 0xD8, 0xFF]);
|
||||
let image_id = if is_jpeg && matches!(img.color().channel_count(), 1 | 3) {
|
||||
let cs = if img.color().channel_count() == 1 { "DeviceGray" } else { "DeviceRGB" };
|
||||
let mut s = Stream::new(
|
||||
dictionary! {"Type" => "XObject", "Subtype" => "Image", "Width" => w as i64, "Height" => h as i64,
|
||||
"ColorSpace" => cs, "BitsPerComponent" => 8, "Filter" => "DCTDecode"},
|
||||
bytes.clone(),
|
||||
);
|
||||
s.allows_compression = false;
|
||||
doc.add_object(s)
|
||||
} else {
|
||||
let rgba = img.to_rgba8();
|
||||
let has_alpha = rgba.pixels().any(|p| p.0[3] != 255);
|
||||
let rgb: Vec<u8> = rgba.pixels().flat_map(|p| [p.0[0], p.0[1], p.0[2]]).collect();
|
||||
let mut dict = dictionary! {"Type" => "XObject", "Subtype" => "Image", "Width" => w as i64,
|
||||
"Height" => h as i64, "ColorSpace" => "DeviceRGB", "BitsPerComponent" => 8};
|
||||
if has_alpha {
|
||||
let alpha: Vec<u8> = rgba.pixels().map(|p| p.0[3]).collect();
|
||||
let mut smask = Stream::new(
|
||||
dictionary! {"Type" => "XObject", "Subtype" => "Image", "Width" => w as i64, "Height" => h as i64,
|
||||
"ColorSpace" => "DeviceGray", "BitsPerComponent" => 8},
|
||||
alpha,
|
||||
);
|
||||
let _ = smask.compress();
|
||||
dict.set("SMask", doc.add_object(smask));
|
||||
}
|
||||
let mut s = Stream::new(dict, rgb);
|
||||
let _ = s.compress();
|
||||
doc.add_object(s)
|
||||
};
|
||||
let (iw, ih) = (w as f32 * 0.75, h as f32 * 0.75);
|
||||
let (pw, ph) = match fit {
|
||||
PageFit::Image => (iw, ih),
|
||||
PageFit::A4 | PageFit::Letter => {
|
||||
let (a, b) = if fit == PageFit::A4 { (595.28, 841.89) } else { (612.0, 792.0) };
|
||||
if w > h { (b, a) } else { (a, b) }
|
||||
}
|
||||
};
|
||||
let margin = if fit == PageFit::Image { 0.0 } else { margin_pt.clamp(0.0, pw.min(ph) / 3.0) };
|
||||
let scale = ((pw - 2.0 * margin) / iw).min((ph - 2.0 * margin) / ih).min(if fit == PageFit::Image {
|
||||
1.0
|
||||
} else {
|
||||
f32::MAX
|
||||
});
|
||||
let (dw, dh) = (iw * scale, ih * scale);
|
||||
let (x, y) = ((pw - dw) / 2.0, (ph - dh) / 2.0);
|
||||
let content = format!("q {dw:.3} 0 0 {dh:.3} {x:.3} {y:.3} cm /Im0 Do Q").into_bytes();
|
||||
let content_id = doc.add_object(Stream::new(dictionary! {}, content));
|
||||
let page = doc.add_object(dictionary! {
|
||||
"Type" => "Page", "Parent" => pages_id, "Contents" => content_id,
|
||||
"MediaBox" => vec![0.into(), 0.into(), Object::Real(pw), Object::Real(ph)],
|
||||
"Resources" => dictionary! {"XObject" => Dictionary::from_iter([(b"Im0".to_vec(), Object::Reference(image_id))])},
|
||||
});
|
||||
kids.push(Object::Reference(page));
|
||||
}
|
||||
let count = kids.len() as i64;
|
||||
doc.objects.insert(pages_id, Object::Dictionary(dictionary! {"Type" => "Pages", "Kids" => kids, "Count" => count}));
|
||||
let catalog = doc.add_object(dictionary! {"Type" => "Catalog", "Pages" => pages_id});
|
||||
doc.trailer.set("Root", catalog);
|
||||
lopdf_save(&mut doc)
|
||||
}
|
||||
|
||||
/// Renders the chosen pages (0-based) at `dpi`.
|
||||
pub fn pages_to_images(
|
||||
engine: &Engine,
|
||||
bytes: &[u8],
|
||||
password: Option<&str>,
|
||||
pages: &[usize],
|
||||
dpi: u32,
|
||||
) -> Result<Vec<DynamicImage>, PdfError> {
|
||||
let doc = engine.open(bytes, password)?;
|
||||
let mut out = Vec::new();
|
||||
for &i in pages {
|
||||
let page = doc.pages().get(i as i32).map_err(|_| PdfError::NoSuchPage(i + 1))?;
|
||||
let width = (page.width().value * dpi.clamp(36, 600) as f32 / 72.0).round().max(1.0) as u32;
|
||||
drop(page);
|
||||
out.push(render_doc_page(&doc, i, width, true)?);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
+193
-184
@@ -1,184 +1,193 @@
|
||||
//! 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() }
|
||||
}
|
||||
}
|
||||
//! 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() }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -52,7 +52,8 @@ pub fn redact(
|
||||
redactions: &[Redaction],
|
||||
opts: &RedactOptions,
|
||||
) -> Result<Redacted, PdfError> {
|
||||
if redactions.is_empty() || redactions.iter().any(|r| r.rects.is_empty() || r.rects.iter().any(ViewRect::is_empty)) {
|
||||
if redactions.is_empty() || redactions.iter().any(|r| r.rects.is_empty() || r.rects.iter().any(ViewRect::is_empty))
|
||||
{
|
||||
return Err(PdfError::Invalid("Draw at least one box to redact.".into()));
|
||||
}
|
||||
// 1. Render every redacted page with pdfium (annotations and form fields included) and burn the boxes in.
|
||||
@@ -67,7 +68,8 @@ pub fn redact(
|
||||
if !seen.insert(r.page) {
|
||||
continue;
|
||||
}
|
||||
let rects: Vec<ViewRect> = redactions.iter().filter(|x| x.page == r.page).flat_map(|x| x.rects.clone()).collect();
|
||||
let rects: Vec<ViewRect> =
|
||||
redactions.iter().filter(|x| x.page == r.page).flat_map(|x| x.rects.clone()).collect();
|
||||
let page = pdfium_doc.pages().get(r.page as i32).map_err(PdfError::from_pdfium)?;
|
||||
let (vw, vh) = (page.width().value, page.height().value);
|
||||
drop(page);
|
||||
@@ -181,7 +183,8 @@ fn push_down_resources(doc: &mut Document, pages: &[ObjectId], redacted: &HashSe
|
||||
for &page in pages {
|
||||
// The nearest ancestor's /Resources, and every Pages node on the way up.
|
||||
let mut inherited = None;
|
||||
let mut current = doc.get_dictionary(page).ok().and_then(|d| d.get(b"Parent").ok()).and_then(|p| p.as_reference().ok());
|
||||
let mut current =
|
||||
doc.get_dictionary(page).ok().and_then(|d| d.get(b"Parent").ok()).and_then(|p| p.as_reference().ok());
|
||||
let mut depth = 0;
|
||||
while let Some(id) = current {
|
||||
if depth > 64 || !nodes.insert(id) && inherited.is_some() {
|
||||
@@ -272,7 +275,11 @@ fn prune_form(doc: &mut Document, removed: &HashSet<ObjectId>) {
|
||||
if changed {
|
||||
let target = match acroform {
|
||||
Some(id) => doc.get_dictionary_mut(id).ok(),
|
||||
None => doc.get_dictionary_mut(catalog_id).ok().and_then(|c| c.get_mut(b"AcroForm").ok()).and_then(|o| o.as_dict_mut().ok()),
|
||||
None => doc
|
||||
.get_dictionary_mut(catalog_id)
|
||||
.ok()
|
||||
.and_then(|c| c.get_mut(b"AcroForm").ok())
|
||||
.and_then(|o| o.as_dict_mut().ok()),
|
||||
};
|
||||
if let Some(f) = target {
|
||||
f.set("Fields", kept);
|
||||
|
||||
@@ -38,6 +38,7 @@ fn s(text: &str) -> Object {
|
||||
Object::String(text.as_bytes().to_vec(), StringFormat::Literal)
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct Options {
|
||||
pub compress: bool,
|
||||
/// /Rotate on page 1.
|
||||
@@ -46,12 +47,6 @@ pub struct Options {
|
||||
pub inherited: bool,
|
||||
}
|
||||
|
||||
impl Default for Options {
|
||||
fn default() -> Self {
|
||||
Options { compress: false, rotate: 0, inherited: false }
|
||||
}
|
||||
}
|
||||
|
||||
/// Two US-Letter pages. Page 1 holds text, an image, a vector shape, a hidden layer, a note, a form field, all in
|
||||
/// the box; the document holds Info, XMP, an outline, a struct tree and an attachment with secret strings.
|
||||
/// Page 2 holds "PAGE-TWO-KEEP" and must come out byte-equal.
|
||||
@@ -84,7 +79,7 @@ BT /F1 12 Tf 72 300 Td (PUBLIC-LINE) Tj ET\n"
|
||||
let c2 = doc.add_object(Stream::new(dictionary! {}, PAGE_TWO_CONTENT.to_vec()));
|
||||
|
||||
let helv = doc.add_object(dictionary! {"Type" => "Font", "Subtype" => "Type1", "BaseFont" => "Helvetica",
|
||||
"Encoding" => "WinAnsiEncoding"});
|
||||
"Encoding" => "WinAnsiEncoding"});
|
||||
let field_ap = doc.add_object(Stream::new(
|
||||
dictionary! {"Type" => "XObject", "Subtype" => "Form", "BBox" => vec![0.into(), 0.into(), 200.into(), 20.into()],
|
||||
"Resources" => dictionary! {"Font" => dictionary! {"Helv" => helv}}},
|
||||
@@ -160,10 +155,8 @@ BT /F1 12 Tf 72 300 Td (PUBLIC-LINE) Tj ET\n"
|
||||
"Type" => "StructElem", "S" => "P", "P" => struct_root_id, "Pg" => page1_id,
|
||||
"ActualText" => s("STRUCT-SECRET"), "K" => 0,
|
||||
});
|
||||
doc.objects.insert(
|
||||
struct_root_id,
|
||||
Object::Dictionary(dictionary! {"Type" => "StructTreeRoot", "K" => vec![elem.into()]}),
|
||||
);
|
||||
doc.objects
|
||||
.insert(struct_root_id, Object::Dictionary(dictionary! {"Type" => "StructTreeRoot", "K" => vec![elem.into()]}));
|
||||
let attach = doc.add_object(Stream::new(dictionary! {"Type" => "EmbeddedFile"}, b"ATTACH-SECRET inside".to_vec()));
|
||||
let filespec = doc.add_object(dictionary! {
|
||||
"Type" => "Filespec", "F" => s("notes.txt"), "EF" => dictionary! {"F" => attach},
|
||||
@@ -211,7 +204,7 @@ pub fn numbered_pdf(n: usize, label: &str) -> Vec<u8> {
|
||||
doc.objects.insert(
|
||||
pages_id,
|
||||
Object::Dictionary(dictionary! {"Type" => "Pages", "Kids" => kids, "Count" => n as i64,
|
||||
"MediaBox" => vec![0.into(), 0.into(), 595.into(), 842.into()]}),
|
||||
"MediaBox" => vec![0.into(), 0.into(), 595.into(), 842.into()]}),
|
||||
);
|
||||
let catalog = doc.add_object(dictionary! {"Type" => "Catalog", "Pages" => pages_id});
|
||||
doc.trailer.set("Root", catalog);
|
||||
|
||||
+86
-27
@@ -47,7 +47,9 @@ fn form_pdf() -> Vec<u8> {
|
||||
}
|
||||
doc.objects.insert(
|
||||
radio_id,
|
||||
Object::Dictionary(dictionary! {"FT" => "Btn", "Ff" => 49152, "T" => s("size"), "V" => "Off", "Kids" => kids.clone()}),
|
||||
Object::Dictionary(
|
||||
dictionary! {"FT" => "Btn", "Ff" => 49152, "T" => s("size"), "V" => "Off", "Kids" => kids.clone()},
|
||||
),
|
||||
);
|
||||
let city = doc.add_object(dictionary! {
|
||||
"Type" => "Annot", "Subtype" => "Widget", "FT" => "Ch", "Ff" => 131072, "T" => s("city"),
|
||||
@@ -57,17 +59,23 @@ fn form_pdf() -> Vec<u8> {
|
||||
let content = doc.add_object(Stream::new(dictionary! {}, b"BT /F1 12 Tf 72 780 Td (Form) Tj ET".to_vec()));
|
||||
let mut annots = vec![name.into(), agree.into(), city.into()];
|
||||
annots.extend(kids);
|
||||
doc.objects.insert(page_id, Object::Dictionary(dictionary! {
|
||||
"Type" => "Page", "Parent" => pages_id, "Contents" => content, "Annots" => annots,
|
||||
"Resources" => dictionary! {"Font" => dictionary! {"F1" => helv}},
|
||||
}));
|
||||
doc.objects.insert(pages_id, Object::Dictionary(dictionary! {
|
||||
"Type" => "Pages", "Kids" => vec![page_id.into()], "Count" => 1,
|
||||
"MediaBox" => vec![0.into(), 0.into(), 595.into(), 842.into()],
|
||||
}));
|
||||
doc.objects.insert(
|
||||
page_id,
|
||||
Object::Dictionary(dictionary! {
|
||||
"Type" => "Page", "Parent" => pages_id, "Contents" => content, "Annots" => annots,
|
||||
"Resources" => dictionary! {"Font" => dictionary! {"F1" => helv}},
|
||||
}),
|
||||
);
|
||||
doc.objects.insert(
|
||||
pages_id,
|
||||
Object::Dictionary(dictionary! {
|
||||
"Type" => "Pages", "Kids" => vec![page_id.into()], "Count" => 1,
|
||||
"MediaBox" => vec![0.into(), 0.into(), 595.into(), 842.into()],
|
||||
}),
|
||||
);
|
||||
let catalog = doc.add_object(dictionary! {"Type" => "Catalog", "Pages" => pages_id,
|
||||
"AcroForm" => dictionary! {"Fields" => vec![name.into(), agree.into(), radio_id.into(), city.into()],
|
||||
"DA" => s("/Helv 12 Tf 0 g"), "DR" => dictionary! {"Font" => dictionary! {"Helv" => helv, "ZaDb" => zadb}}}});
|
||||
"AcroForm" => dictionary! {"Fields" => vec![name.into(), agree.into(), radio_id.into(), city.into()],
|
||||
"DA" => s("/Helv 12 Tf 0 g"), "DR" => dictionary! {"Font" => dictionary! {"Helv" => helv, "ZaDb" => zadb}}}});
|
||||
doc.trailer.set("Root", catalog);
|
||||
let mut out = Vec::new();
|
||||
doc.save_to(&mut out).unwrap();
|
||||
@@ -89,7 +97,10 @@ fn fill() -> Edits {
|
||||
fn dark_pixels(img: &image::RgbImage, r: ViewRect, scale: f32) -> usize {
|
||||
let (x0, y0) = ((r.x * scale) as u32, (r.y * scale) as u32);
|
||||
let (x1, y1) = (((r.x + r.w) * scale) as u32, ((r.y + r.h) * scale) as u32);
|
||||
(y0..y1.min(img.height())).flat_map(|y| (x0..x1.min(img.width())).map(move |x| (x, y))).filter(|&(x, y)| img.get_pixel(x, y).0.iter().map(|&c| c as u32).sum::<u32>() < 300).count()
|
||||
(y0..y1.min(img.height()))
|
||||
.flat_map(|y| (x0..x1.min(img.width())).map(move |x| (x, y)))
|
||||
.filter(|&(x, y)| img.get_pixel(x, y).0.iter().map(|&c| c as u32).sum::<u32>() < 300)
|
||||
.count()
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -124,7 +135,13 @@ fn a_filled_form_flattens_into_page_text() {
|
||||
let doc = Document::load_mem(&out).unwrap();
|
||||
assert!(doc.catalog().unwrap().get(b"AcroForm").is_err(), "the form survived flattening");
|
||||
let p = page_ids(&doc)[0];
|
||||
assert!(doc.get_dictionary(p).unwrap().get(b"Annots").map(|a| a.as_array().map(|a| a.is_empty()).unwrap_or(false)).unwrap_or(true));
|
||||
assert!(
|
||||
doc.get_dictionary(p)
|
||||
.unwrap()
|
||||
.get(b"Annots")
|
||||
.map(|a| a.as_array().map(|a| a.is_empty()).unwrap_or(false))
|
||||
.unwrap_or(true)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -144,15 +161,36 @@ fn every_annotation() -> Vec<Annotation> {
|
||||
let r = |x, y, w, h| ViewRect { x, y, w, h };
|
||||
let a = |shape| Annotation { page: 0, shape, color: [1.0, 0.0, 0.0], opacity: 1.0, contents: None };
|
||||
vec![
|
||||
Annotation { color: [1.0, 0.9, 0.0], opacity: 0.5, ..a(Shape::Highlight { rects: vec![r(60.0, 100.0, 200.0, 30.0)] }) },
|
||||
Annotation {
|
||||
color: [1.0, 0.9, 0.0],
|
||||
opacity: 0.5,
|
||||
..a(Shape::Highlight { rects: vec![r(60.0, 100.0, 200.0, 30.0)] })
|
||||
},
|
||||
a(Shape::Underline { rects: vec![r(60.0, 150.0, 200.0, 20.0)] }),
|
||||
a(Shape::Strike { rects: vec![r(60.0, 190.0, 200.0, 20.0)] }),
|
||||
Annotation { contents: Some("Zkontrolovat čísla".into()), ..a(Shape::Note { at: ViewPoint { x: 400.0, y: 100.0 } }) },
|
||||
a(Shape::FreeText { rect: r(60.0, 240.0, 400.0, 60.0), text: "Příliš žluťoučký kůň".into(), size: 18.0 }),
|
||||
a(Shape::Ink { strokes: vec![vec![ViewPoint { x: 60.0, y: 330.0 }, ViewPoint { x: 160.0, y: 380.0 }, ViewPoint { x: 260.0, y: 330.0 }]], width: 3.0 }),
|
||||
Annotation {
|
||||
contents: Some("Zkontrolovat čísla".into()),
|
||||
..a(Shape::Note { at: ViewPoint { x: 400.0, y: 100.0 } })
|
||||
},
|
||||
a(Shape::FreeText {
|
||||
rect: r(60.0, 240.0, 400.0, 60.0), text: "Příliš žluťoučký kůň".into(), size: 18.0
|
||||
}),
|
||||
a(Shape::Ink {
|
||||
strokes: vec![vec![
|
||||
ViewPoint { x: 60.0, y: 330.0 },
|
||||
ViewPoint { x: 160.0, y: 380.0 },
|
||||
ViewPoint { x: 260.0, y: 330.0 },
|
||||
]],
|
||||
width: 3.0,
|
||||
}),
|
||||
a(Shape::Rectangle { rect: r(300.0, 330.0, 100.0, 50.0), width: 2.0 }),
|
||||
a(Shape::Ellipse { rect: r(420.0, 330.0, 100.0, 50.0), width: 2.0 }),
|
||||
a(Shape::Line { from: ViewPoint { x: 60.0, y: 420.0 }, to: ViewPoint { x: 300.0, y: 460.0 }, width: 3.0, arrow: true }),
|
||||
a(Shape::Line {
|
||||
from: ViewPoint { x: 60.0, y: 420.0 },
|
||||
to: ViewPoint { x: 300.0, y: 460.0 },
|
||||
width: 3.0,
|
||||
arrow: true,
|
||||
}),
|
||||
]
|
||||
}
|
||||
|
||||
@@ -173,7 +211,10 @@ fn every_annotation_kind_is_written_with_an_appearance_and_shows() {
|
||||
String::from_utf8(d.get(b"Subtype").unwrap().as_name().unwrap().to_vec()).unwrap()
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(subtypes, ["Highlight", "Underline", "StrikeOut", "Text", "FreeText", "Ink", "Square", "Circle", "Line"]);
|
||||
assert_eq!(
|
||||
subtypes,
|
||||
["Highlight", "Underline", "StrikeOut", "Text", "FreeText", "Ink", "Square", "Circle", "Line"]
|
||||
);
|
||||
let after = pictor_pdf::render_page(engine(), &out, None, 0, 595).unwrap().to_rgb8();
|
||||
for a in every_annotation() {
|
||||
let r = match &a.shape {
|
||||
@@ -197,7 +238,9 @@ fn every_annotation_kind_is_written_with_an_appearance_and_shows() {
|
||||
|
||||
#[test]
|
||||
fn a_free_text_on_a_rotated_page_lands_where_it_was_drawn() {
|
||||
let input = pictor_pdf::reorganise(&numbered_pdf(1, "R"), None, &[pictor_pdf::PageSpec::Existing { index: 0, rotate: 90 }]).unwrap();
|
||||
let input =
|
||||
pictor_pdf::reorganise(&numbered_pdf(1, "R"), None, &[pictor_pdf::PageSpec::Existing { index: 0, rotate: 90 }])
|
||||
.unwrap();
|
||||
let rect = ViewRect { x: 100.0, y: 300.0, w: 300.0, h: 40.0 };
|
||||
let edits = Edits {
|
||||
annotations: vec![Annotation {
|
||||
@@ -225,7 +268,9 @@ fn signature_png() -> Vec<u8> {
|
||||
if on { image::Rgba([200, 0, 0, 255]) } else { image::Rgba([0, 0, 0, 0]) }
|
||||
});
|
||||
let mut out = Vec::new();
|
||||
image::DynamicImage::ImageRgba8(img).write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).unwrap();
|
||||
image::DynamicImage::ImageRgba8(img)
|
||||
.write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png)
|
||||
.unwrap();
|
||||
out
|
||||
}
|
||||
|
||||
@@ -236,10 +281,13 @@ fn a_signature_stamp_is_burned_into_the_page() {
|
||||
let edits = Edits { stamps: vec![Stamp { page: 1, rect, image: signature_png() }], ..Default::default() };
|
||||
let out = pictor_pdf::apply(engine(), &input, None, &edits).unwrap().bytes;
|
||||
let img = pictor_pdf::render_page(engine(), &out, None, 1, 595).unwrap().to_rgb8();
|
||||
let red = (700..780).flat_map(|y| (300..500).map(move |x| (x, y))).filter(|&(x, y)| {
|
||||
let p = img.get_pixel(x, y).0;
|
||||
p[0] > 150 && p[1] < 80
|
||||
}).count();
|
||||
let red = (700..780)
|
||||
.flat_map(|y| (300..500).map(move |x| (x, y)))
|
||||
.filter(|&(x, y)| {
|
||||
let p = img.get_pixel(x, y).0;
|
||||
p[0] > 150 && p[1] < 80
|
||||
})
|
||||
.count();
|
||||
assert!(red > 100, "the signature is not visible ({red} red pixels)");
|
||||
// Transparent parts stay transparent: the page is white just above the signature's line.
|
||||
assert_eq!(img.get_pixel(305, 702).0, [255, 255, 255]);
|
||||
@@ -259,14 +307,25 @@ fn a_protected_document_stays_protected_with_its_password() {
|
||||
let out = pictor_pdf::apply(engine(), &locked, Some("pw"), &edits).unwrap().bytes;
|
||||
assert!(pictor_pdf::is_encrypted(&out));
|
||||
assert_eq!(pictor_pdf::extract_text(engine(), &out, Some("pw")).unwrap()[0].trim(), "Secret page 1");
|
||||
let removed = pictor_pdf::apply(engine(), &locked, Some("pw"), &Edits { security: Security::Remove, ..Default::default() }).unwrap().bytes;
|
||||
let removed =
|
||||
pictor_pdf::apply(engine(), &locked, Some("pw"), &Edits { security: Security::Remove, ..Default::default() })
|
||||
.unwrap()
|
||||
.bytes;
|
||||
assert!(!pictor_pdf::is_encrypted(&removed));
|
||||
assert!(pictor_pdf::apply(engine(), &locked, Some("wrong"), &edits).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn edits_serialise_for_the_worker() {
|
||||
let edits = Edits { annotations: every_annotation(), stamps: vec![Stamp { page: 0, rect: ViewRect { x: 1.0, y: 1.0, w: 2.0, h: 2.0 }, image: vec![0, 1, 2, 250, 255] }], ..Default::default() };
|
||||
let edits = Edits {
|
||||
annotations: every_annotation(),
|
||||
stamps: vec![Stamp {
|
||||
page: 0,
|
||||
rect: ViewRect { x: 1.0, y: 1.0, w: 2.0, h: 2.0 },
|
||||
image: vec![0, 1, 2, 250, 255],
|
||||
}],
|
||||
..Default::default()
|
||||
};
|
||||
let json = serde_json::to_string(&edits).unwrap();
|
||||
let back: Edits = serde_json::from_str(&json).unwrap();
|
||||
assert_eq!(back.annotations.len(), 9);
|
||||
|
||||
@@ -25,7 +25,10 @@ fn reorder_rotate_delete_and_insert_blank() {
|
||||
assert_eq!(sizes[2], (842.0, 595.0), "page 1 was not turned");
|
||||
// Deleted pages are gone from the file, not just from the page list.
|
||||
for blob in scan_objects(&out) {
|
||||
assert!(!contains(&blob, "Doc page 2") && !contains(&blob, "Doc page 3"), "a deleted page survived in the file");
|
||||
assert!(
|
||||
!contains(&blob, "Doc page 2") && !contains(&blob, "Doc page 3"),
|
||||
"a deleted page survived in the file"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -120,9 +123,12 @@ fn password_on_and_off() {
|
||||
#[test]
|
||||
fn images_to_pdf_and_back() {
|
||||
let mut jpeg = Vec::new();
|
||||
let photo = image::DynamicImage::ImageRgb8(image::RgbImage::from_fn(400, 300, |x, y| image::Rgb([x as u8, y as u8, 128])));
|
||||
let photo =
|
||||
image::DynamicImage::ImageRgb8(image::RgbImage::from_fn(400, 300, |x, y| image::Rgb([x as u8, y as u8, 128])));
|
||||
photo.write_to(&mut std::io::Cursor::new(&mut jpeg), image::ImageFormat::Jpeg).unwrap();
|
||||
let logo = image::DynamicImage::ImageRgba8(image::RgbaImage::from_fn(100, 200, |x, _| image::Rgba([255, 0, 0, if x < 50 { 255 } else { 0 }])));
|
||||
let logo = image::DynamicImage::ImageRgba8(image::RgbaImage::from_fn(100, 200, |x, _| {
|
||||
image::Rgba([255, 0, 0, if x < 50 { 255 } else { 0 }])
|
||||
}));
|
||||
let mut png = Vec::new();
|
||||
logo.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
|
||||
let pdf = pictor_pdf::images_to_pdf(&[(jpeg.clone(), photo.clone()), (png, logo)], PageFit::A4, 36.0).unwrap();
|
||||
|
||||
@@ -43,7 +43,10 @@ fn assert_page_two_unchanged(input: &[u8], output: &[u8]) {
|
||||
assert_eq!(font(&a, pa), font(&b, pb), "page 2's fonts changed");
|
||||
// The raw stream bytes too (lopdf writes untouched streams as they were).
|
||||
let raw = |d: &Document, p| -> Vec<Vec<u8>> {
|
||||
d.get_page_contents(p).iter().map(|id| d.get_object(*id).unwrap().as_stream().unwrap().content.clone()).collect()
|
||||
d.get_page_contents(p)
|
||||
.iter()
|
||||
.map(|id| d.get_object(*id).unwrap().as_stream().unwrap().content.clone())
|
||||
.collect()
|
||||
};
|
||||
assert_eq!(raw(&a, pa), raw(&b, pb), "page 2's raw content stream bytes changed");
|
||||
}
|
||||
@@ -117,7 +120,10 @@ fn the_box_is_black_and_the_rest_of_the_page_still_shows() {
|
||||
let p = img.get_pixel(300, 100);
|
||||
assert!(p.0.iter().all(|&c| c < 16), "box not black: {p:?}");
|
||||
// "PUBLIC-LINE" at PDF (72, 300) → view y ≈ 492: some dark pixels remain in that band.
|
||||
let dark = (480..500).flat_map(|y| (72..160).map(move |x| (x, y))).filter(|&(x, y)| img.get_pixel(x, y).0[0] < 100).count();
|
||||
let dark = (480..500)
|
||||
.flat_map(|y| (72..160).map(move |x| (x, y)))
|
||||
.filter(|&(x, y)| img.get_pixel(x, y).0[0] < 100)
|
||||
.count();
|
||||
assert!(dark > 20, "the text outside the box disappeared ({dark} dark pixels)");
|
||||
}
|
||||
|
||||
@@ -126,8 +132,14 @@ fn a_redacted_encrypted_document_needs_its_password_and_comes_out_clean() {
|
||||
let input = secret_pdf(&Options::default());
|
||||
let locked = pictor_pdf::protect(&input, None, "open-sesame", None).unwrap();
|
||||
assert!(
|
||||
pictor_pdf::redact(engine(), &locked, None, &[Redaction { page: 0, rects: vec![secret_box()] }], &Default::default())
|
||||
.is_err(),
|
||||
pictor_pdf::redact(
|
||||
engine(),
|
||||
&locked,
|
||||
None,
|
||||
&[Redaction { page: 0, rects: vec![secret_box()] }],
|
||||
&Default::default()
|
||||
)
|
||||
.is_err(),
|
||||
"redacted without the password"
|
||||
);
|
||||
let out = pictor_pdf::redact(
|
||||
@@ -144,10 +156,19 @@ fn a_redacted_encrypted_document_needs_its_password_and_comes_out_clean() {
|
||||
#[test]
|
||||
fn no_redaction_box_is_refused() {
|
||||
let input = secret_pdf(&Options::default());
|
||||
assert!(pictor_pdf::redact(engine(), &input, None, &[Redaction { page: 0, rects: vec![] }], &Default::default()).is_err());
|
||||
assert!(
|
||||
pictor_pdf::redact(engine(), &input, None, &[Redaction { page: 9, rects: vec![secret_box()] }], &Default::default())
|
||||
.is_err(),
|
||||
pictor_pdf::redact(engine(), &input, None, &[Redaction { page: 0, rects: vec![] }], &Default::default())
|
||||
.is_err()
|
||||
);
|
||||
assert!(
|
||||
pictor_pdf::redact(
|
||||
engine(),
|
||||
&input,
|
||||
None,
|
||||
&[Redaction { page: 9, rects: vec![secret_box()] }],
|
||||
&Default::default()
|
||||
)
|
||||
.is_err(),
|
||||
"a page that does not exist was accepted"
|
||||
);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user