use crate::{Diagnostic, Diagnostics, Error, Pdf, PdfOpenOptions};
use std::io::{Read, Seek};
#[derive(Debug, Clone)]
pub struct CheckReport {
pub valid: bool,
pub diagnostics: Diagnostics,
}
pub fn check_reader<R: Read + Seek>(reader: R) -> crate::Result<CheckReport> {
check_reader_inner(reader, true)
}
pub fn check_reader_with_options<R: Read + Seek>(
reader: R,
options: PdfOpenOptions,
) -> crate::Result<CheckReport> {
check_reader_inner_with_options(reader, options)
}
pub fn check_reader_strict<R: Read + Seek>(reader: R) -> crate::Result<CheckReport> {
check_reader_inner(reader, false)
}
fn check_reader_inner<R: Read + Seek>(reader: R, allow_repair: bool) -> crate::Result<CheckReport> {
check_reader_inner_with_options(
reader,
PdfOpenOptions {
repair: allow_repair,
..PdfOpenOptions::default()
},
)
}
fn check_reader_inner_with_options<R: Read + Seek>(
reader: R,
options: PdfOpenOptions,
) -> crate::Result<CheckReport> {
let allow_repair = options.repair;
let mut pdf = if allow_repair {
match Pdf::open_with_options(reader, options) {
Ok(pdf) => pdf,
Err(error @ Error::Encrypted(_)) => return Err(error),
Err(error) => {
let mut diagnostics = Diagnostics::default();
diagnostics.push(Diagnostic::error(error.to_string(), None));
return Ok(CheckReport {
valid: false,
diagnostics,
});
}
}
} else {
Pdf::open_with_options(reader, options)?
};
let mut diagnostics = pdf.repair_diagnostics().clone();
if pdf.uses_weak_crypto() {
diagnostics.push(Diagnostic::warning(
"encrypted PDF uses weak crypto; processing continued",
None,
));
}
if pdf.trailer().get_ref("Root").is_none() {
diagnostics.push(Diagnostic::error("trailer is missing /Root", None));
}
if is_linearized_pdf(&mut pdf)? {
diagnostics.push(Diagnostic::warning(
"linearized PDF detected: rewrite support preserves hint object but does not recompute linearization tables",
None,
));
}
Ok(CheckReport {
valid: !diagnostics.has_errors(),
diagnostics,
})
}
fn is_linearized_pdf<R: Read + Seek>(reader: &mut Pdf<R>) -> crate::Result<bool> {
reader.linearized_hint_ref().map(|hint| hint.is_some())
}