1
0
mirror of https://gitlab.com/comunic/comunicapiv3 synced 2025-03-14 01:42:37 +00:00
comunicapiv3/src/utils/pdf_utils.rs

36 lines
975 B
Rust
Raw Normal View History

2020-07-08 17:14:55 +02:00
//! # PDF utilities
//!
//! @author Pierre Hubert
2020-07-08 17:34:44 +02:00
use pdf::backend::Backend;
2023-05-31 19:10:05 +02:00
use pdf::file::FileOptions;
2020-07-08 17:34:44 +02:00
2020-07-08 17:14:55 +02:00
use crate::data::error::{ExecError, ResultBoxError};
/// Check out whether a PDF is a valid PDF or not, by trying to open it
2021-02-19 17:08:13 +01:00
pub fn is_valid_pdf(file: &actix_web::web::Bytes) -> ResultBoxError<bool> {
2020-07-08 17:34:44 +02:00
let backend = file.to_vec();
2020-07-08 17:14:55 +02:00
2023-05-31 19:10:05 +02:00
let mut pdf_file = FileOptions::cached().load(backend.as_slice())?;
2021-02-19 17:08:13 +01:00
let start_offset = backend.locate_start_offset()?;
2023-05-31 19:10:05 +02:00
match backend.read_xref_table_and_trailer(start_offset, &mut pdf_file) {
2020-07-08 17:34:44 +02:00
Ok((refs, _)) => {
if refs.is_empty() {
2023-05-31 19:10:05 +02:00
Err(ExecError::boxed_string(format!(
"Detected a PDF with 0 references (file size: {})!",
file.len()
)))
2020-07-08 17:34:44 +02:00
} else {
Ok(true)
}
}
2020-07-08 17:14:55 +02:00
Err(e) => {
2021-02-19 17:08:13 +01:00
println!("Error while parsing PDF: {:?}", e);
2020-07-08 17:14:55 +02:00
Ok(false)
}
}
2023-05-31 19:10:05 +02:00
}