use crate::json::JsonValue;
use crate::object::{Dictionary, Object, Stream};
use crate::reader::Pdf;
use std::io::{Read, Seek};
#[derive(Debug, Clone, PartialEq)]
pub enum ConvertError {
NonFiniteFloat,
PdfError(String),
}
impl std::fmt::Display for ConvertError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
ConvertError::NonFiniteFloat => {
write!(f, "non-finite float cannot be serialized as JSON")
}
ConvertError::PdfError(msg) => write!(f, "PDF error: {msg}"),
}
}
}
impl std::error::Error for ConvertError {}
impl From<crate::Error> for ConvertError {
fn from(err: crate::Error) -> Self {
ConvertError::PdfError(err.to_string())
}
}
const PDFDOC_ENCODING: [Option<char>; 256] = build_pdfdoc_table();
const fn build_pdfdoc_table() -> [Option<char>; 256] {
let mut table: [Option<char>; 256] = [None; 256];
table[0x08] = Some('\u{0008}');
table[0x09] = Some('\t');
table[0x0A] = Some('\n');
table[0x0B] = Some('\u{000B}');
table[0x0C] = Some('\u{000C}');
table[0x0D] = Some('\r');
table[0x18] = Some('\u{02D8}'); table[0x19] = Some('\u{02C7}'); table[0x1A] = Some('\u{02C6}'); table[0x1B] = Some('\u{02D9}'); table[0x1C] = Some('\u{02DD}'); table[0x1D] = Some('\u{02DB}'); table[0x1E] = Some('\u{02DA}'); table[0x1F] = Some('\u{02DC}'); let mut b = 0x20u8;
while b <= 0x7E {
table[b as usize] = Some(b as char);
b += 1;
}
table[0x80] = Some('\u{2022}'); table[0x81] = Some('\u{2020}'); table[0x82] = Some('\u{2021}'); table[0x83] = Some('\u{2026}'); table[0x84] = Some('\u{2014}'); table[0x85] = Some('\u{2013}'); table[0x86] = Some('\u{0192}'); table[0x87] = Some('\u{2044}'); table[0x88] = Some('\u{2039}'); table[0x89] = Some('\u{203A}'); table[0x8A] = Some('\u{2212}'); table[0x8B] = Some('\u{2030}'); table[0x8C] = Some('\u{201E}'); table[0x8D] = Some('\u{201C}'); table[0x8E] = Some('\u{201D}'); table[0x8F] = Some('\u{2018}'); table[0x90] = Some('\u{2019}'); table[0x91] = Some('\u{201A}'); table[0x92] = Some('\u{2122}'); table[0x93] = Some('\u{FB01}'); table[0x94] = Some('\u{FB02}'); table[0x95] = Some('\u{0141}'); table[0x96] = Some('\u{0152}'); table[0x97] = Some('\u{0160}'); table[0x98] = Some('\u{0178}'); table[0x99] = Some('\u{017D}'); table[0x9A] = Some('\u{0131}'); table[0x9B] = Some('\u{0142}'); table[0x9C] = Some('\u{0153}'); table[0x9D] = Some('\u{0161}'); table[0x9E] = Some('\u{017E}'); table[0xA0] = Some('\u{20AC}'); let mut b = 0xA1u8;
loop {
table[b as usize] = Some(b as char);
if b == 0xFF {
break;
}
b += 1;
}
table
}
fn decode_pdf_text_string(bytes: &[u8]) -> Option<String> {
if let Some(rest) = bytes.strip_prefix(&[0xFE, 0xFF]) {
if rest.len() % 2 != 0 {
return None;
}
let units = rest
.chunks_exact(2)
.map(|c| u16::from_be_bytes([c[0], c[1]]));
return char::decode_utf16(units)
.collect::<Result<String, _>>()
.ok();
}
if let Some(rest) = bytes.strip_prefix(&[0xFF, 0xFE]) {
if rest.len() % 2 != 0 {
return None;
}
let units = rest
.chunks_exact(2)
.map(|c| u16::from_le_bytes([c[0], c[1]]));
return char::decode_utf16(units)
.collect::<Result<String, _>>()
.ok();
}
let mut out = String::with_capacity(bytes.len());
for &b in bytes {
out.push(PDFDOC_ENCODING[b as usize]?);
}
Some(out)
}
fn pdf_string_to_json_string(bytes: &[u8]) -> String {
if let Some(text) = decode_pdf_text_string(bytes) {
format!("u:{text}")
} else {
let hex: String = bytes.iter().map(|b| format!("{b:02x}")).collect::<String>();
format!("b:{hex}")
}
}
fn encode_pdf_name_bytes(bytes: &[u8]) -> String {
fn is_safe(b: u8) -> bool {
if !(0x21..=0x7E).contains(&b) {
return false;
}
!matches!(
b,
b'(' | b')' | b'<' | b'>' | b'[' | b']' | b'{' | b'}' | b'/' | b'%' | b'#'
)
}
let mut out = String::with_capacity(bytes.len() + 1);
out.push('/');
for &b in bytes {
if is_safe(b) {
out.push(b as char);
} else {
use std::fmt::Write as _;
let _ = write!(out, "#{b:02x}");
}
}
out
}
fn dict_to_json(dict: &Dictionary) -> Result<JsonValue, ConvertError> {
let mut pairs = Vec::new();
for (raw_key, value) in dict.iter() {
let key_str = encode_pdf_name_bytes(raw_key);
let json_val = pdf_object_to_json(value)?;
pairs.push((key_str, json_val));
}
pairs.sort_by(|a, b| a.0.cmp(&b.0));
Ok(JsonValue::Object(pairs))
}
fn stream_to_json(stream: &Stream) -> Result<JsonValue, ConvertError> {
let dict_json = dict_to_json(&stream.dict)?;
Ok(JsonValue::Object(vec![(
"stream".to_string(),
JsonValue::Object(vec![("dict".to_string(), dict_json)]),
)]))
}
pub fn pdf_object_to_json(obj: &Object) -> Result<JsonValue, ConvertError> {
match obj {
Object::Null => Ok(JsonValue::Null),
Object::Boolean(b) => Ok(JsonValue::Bool(*b)),
Object::Integer(n) => Ok(JsonValue::Integer(*n)),
Object::Real(f) => {
if !f.is_finite() {
return Err(ConvertError::NonFiniteFloat);
}
Ok(JsonValue::Float(*f))
}
Object::Name(bytes) => Ok(JsonValue::String(encode_pdf_name_bytes(bytes))),
Object::String(bytes) => Ok(JsonValue::String(pdf_string_to_json_string(bytes))),
Object::Reference(r) => Ok(JsonValue::String(format!(
"{} {} R",
r.number, r.generation
))),
Object::Array(elems) => {
let values: Result<Vec<JsonValue>, ConvertError> =
elems.iter().map(pdf_object_to_json).collect();
Ok(JsonValue::Array(values?))
}
Object::Dictionary(dict) => dict_to_json(dict),
Object::Stream(stream) => stream_to_json(stream),
}
}
pub struct QpdfMetadata {
pub pdf_version: String,
pub max_object_id: u32,
pub pushed_inherited_page_resources: bool,
pub called_get_all_pages: bool,
}
#[derive(Debug, Clone, Default)]
pub enum StreamDataMode {
#[default]
None,
Inline,
File { prefix: String },
}
fn base64_encode(bytes: &[u8]) -> String {
const ALPHABET: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
let mut out = String::with_capacity(bytes.len().div_ceil(3) * 4);
for chunk in bytes.chunks(3) {
let b0 = chunk[0] as u32;
let b1 = if chunk.len() > 1 { chunk[1] as u32 } else { 0 };
let b2 = if chunk.len() > 2 { chunk[2] as u32 } else { 0 };
let combined = (b0 << 16) | (b1 << 8) | b2;
out.push(ALPHABET[((combined >> 18) & 0x3F) as usize] as char);
out.push(ALPHABET[((combined >> 12) & 0x3F) as usize] as char);
out.push(if chunk.len() > 1 {
ALPHABET[((combined >> 6) & 0x3F) as usize] as char
} else {
'='
});
out.push(if chunk.len() > 2 {
ALPHABET[(combined & 0x3F) as usize] as char
} else {
'='
});
}
out
}
pub fn build_qpdf_key<R: Read + Seek>(
pdf: &mut Pdf<R>,
metadata: QpdfMetadata,
) -> Result<JsonValue, ConvertError> {
build_qpdf_key_with_stream_mode(pdf, metadata, &StreamDataMode::None)
}
pub fn build_qpdf_key_with_stream_mode<R: Read + Seek>(
pdf: &mut Pdf<R>,
metadata: QpdfMetadata,
stream_mode: &StreamDataMode,
) -> Result<JsonValue, ConvertError> {
let meta = JsonValue::Object(vec![
("jsonversion".to_string(), JsonValue::Integer(2)),
(
"pdfversion".to_string(),
JsonValue::String(metadata.pdf_version.clone()),
),
(
"pushedinheritedpageresources".to_string(),
JsonValue::Bool(metadata.pushed_inherited_page_resources),
),
(
"calledgetallpages".to_string(),
JsonValue::Bool(metadata.called_get_all_pages),
),
(
"maxobjectid".to_string(),
JsonValue::Integer(i64::from(metadata.max_object_id)),
),
]);
let all_refs: Vec<crate::ObjectRef> = pdf.live_object_refs();
let mut map_pairs: Vec<(String, JsonValue)> = Vec::new();
for oref in all_refs {
let key = format!("obj:{} {} R", oref.number, oref.generation);
let obj = pdf.resolve(oref)?;
let json_val = match &obj {
Object::Stream(stream) => {
let dict_json = dict_to_json(&stream.dict)?;
let stream_inner = match stream_mode {
StreamDataMode::None => {
JsonValue::Object(vec![("dict".to_string(), dict_json)])
}
StreamDataMode::Inline => {
let data_str = base64_encode(&stream.data);
JsonValue::Object(vec![
("data".to_string(), JsonValue::String(data_str)),
("dict".to_string(), dict_json),
])
}
StreamDataMode::File { prefix } => {
let datafile = format!("{prefix}-{:03}", oref.number);
JsonValue::Object(vec![
("datafile".to_string(), JsonValue::String(datafile)),
("dict".to_string(), dict_json),
])
}
};
JsonValue::Object(vec![("stream".to_string(), stream_inner)])
}
other => {
let val = pdf_object_to_json(other)?;
JsonValue::Object(vec![("value".to_string(), val)])
}
};
map_pairs.push((key, json_val));
}
{
let trailer_dict = pdf.trailer().clone();
let trailer_json = dict_to_json(&trailer_dict)?;
let trailer_val = JsonValue::Object(vec![("value".to_string(), trailer_json)]);
map_pairs.push(("trailer".to_string(), trailer_val));
}
map_pairs.sort_by(|a, b| a.0.cmp(&b.0));
let objects_map = JsonValue::Object(map_pairs);
Ok(JsonValue::Array(vec![meta, objects_map]))
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum DecodeLevel {
None,
#[default]
Generalized,
Specialized,
All,
}
impl DecodeLevel {
pub fn as_qpdf_str(&self) -> &'static str {
match self {
DecodeLevel::None => "none",
DecodeLevel::Generalized => "generalized",
DecodeLevel::Specialized => "specialized",
DecodeLevel::All => "all",
}
}
}
pub fn build_envelope(decode_level: DecodeLevel) -> JsonValue {
let parameters = JsonValue::Object(vec![(
"decodelevel".to_string(),
JsonValue::String(decode_level.as_qpdf_str().to_string()),
)]);
JsonValue::Object(vec![
("version".to_string(), JsonValue::Integer(2)),
("parameters".to_string(), parameters),
])
}
fn collect_content_refs<R: Read + Seek>(
pdf: &mut Pdf<R>,
content_obj: &Object,
) -> Result<Vec<String>, ConvertError> {
fn ref_string(r: &crate::ObjectRef) -> String {
format!("{} {} R", r.number, r.generation)
}
match content_obj {
Object::Reference(r) => {
let resolved = pdf.resolve(*r).map_err(ConvertError::from)?;
match resolved {
Object::Stream(_) => Ok(vec![ref_string(r)]),
Object::Array(_) => {
collect_content_refs(pdf, &resolved)
}
_ => Ok(vec![]),
}
}
Object::Array(elems) => {
let mut refs = Vec::with_capacity(elems.len());
for e in elems {
if let Object::Reference(r) = e {
refs.push(ref_string(r));
}
}
Ok(refs)
}
_ => Ok(vec![]),
}
}
fn collect_image_refs<R: Read + Seek>(
pdf: &mut Pdf<R>,
page_ref: crate::ObjectRef,
) -> Result<Vec<String>, ConvertError> {
let resources = match crate::pages::resolve_inherited_resources(pdf, page_ref) {
Ok(Some(d)) => d,
Ok(None) => return Ok(vec![]),
Err(e) => return Err(ConvertError::PdfError(e.to_string())),
};
let xobject_dict = match resources.get("XObject") {
Some(Object::Dictionary(d)) => d.clone(),
Some(Object::Reference(r)) => {
let resolved = pdf.resolve(*r).map_err(ConvertError::from)?;
match resolved {
Object::Dictionary(d) => d,
_ => return Ok(vec![]),
}
}
_ => return Ok(vec![]),
};
let mut image_refs: Vec<String> = Vec::new();
for (_name, value) in xobject_dict.iter() {
let xobj_ref = match value {
Object::Reference(r) => *r,
_ => continue,
};
let resolved = pdf.resolve(xobj_ref).map_err(ConvertError::from)?;
if let Object::Stream(stream) = &resolved {
if let Some(Object::Name(subtype)) = stream.dict.get("Subtype") {
if subtype.as_slice() == b"Image" {
image_refs.push(format!("{} {} R", xobj_ref.number, xobj_ref.generation));
}
}
}
}
Ok(image_refs)
}
pub fn build_pages_section<R: Read + Seek>(pdf: &mut Pdf<R>) -> Result<JsonValue, ConvertError> {
let page_refs =
crate::pages::page_refs(pdf).map_err(|e| ConvertError::PdfError(e.to_string()))?;
let mut entries: Vec<JsonValue> = Vec::with_capacity(page_refs.len());
for (idx, page_ref) in page_refs.into_iter().enumerate() {
let pageposfrom1 = (idx as i64) + 1;
let object_str = format!("{} {} R", page_ref.number, page_ref.generation);
let page_obj = pdf.resolve(page_ref).map_err(ConvertError::from)?;
let contents_obj = match &page_obj {
Object::Dictionary(d) => d.get("Contents").cloned(),
_ => None,
};
let contents: Vec<JsonValue> = match &contents_obj {
Some(c) => collect_content_refs(pdf, c)?
.into_iter()
.map(JsonValue::String)
.collect(),
None => vec![],
};
let images: Vec<JsonValue> = collect_image_refs(pdf, page_ref)?
.into_iter()
.map(JsonValue::String)
.collect();
let entry = JsonValue::Object(vec![
("contents".to_string(), JsonValue::Array(contents)),
("images".to_string(), JsonValue::Array(images)),
("label".to_string(), JsonValue::Null),
("object".to_string(), JsonValue::String(object_str)),
("outlines".to_string(), JsonValue::Array(vec![])),
("pageposfrom1".to_string(), JsonValue::Integer(pageposfrom1)),
]);
entries.push(entry);
}
Ok(JsonValue::Array(entries))
}
fn label_dict_to_json(dict: &Dictionary) -> JsonValue {
let first = match dict.get("St") {
Some(Object::Integer(n)) => *n,
_ => 1,
};
let prefix = match dict.get("P") {
Some(Object::String(bytes)) => decode_pdf_text_string(bytes)
.unwrap_or_else(|| String::from_utf8_lossy(bytes).into_owned()),
_ => String::new(),
};
let style = match dict.get("S") {
Some(Object::Name(bytes)) => {
let s = match bytes.as_slice() {
b"D" => "D",
b"R" => "R",
b"r" => "r",
b"A" => "A",
b"a" => "a",
_ => "",
};
if s.is_empty() {
JsonValue::Null
} else {
JsonValue::String(s.to_string())
}
}
_ => JsonValue::Null,
};
JsonValue::Object(vec![
("first".to_string(), JsonValue::Integer(first)),
("prefix".to_string(), JsonValue::String(prefix)),
("style".to_string(), style),
])
}
fn walk_pagelabels<R: Read + Seek>(
pdf: &mut Pdf<R>,
node: Object,
entries: &mut Vec<(i64, Dictionary)>,
seen: &mut std::collections::BTreeSet<crate::ObjectRef>,
depth: usize,
max_depth: usize,
) -> Result<(), ConvertError> {
if depth > max_depth {
return Ok(()); }
let dict = match node {
Object::Dictionary(d) => d,
_ => return Ok(()), };
if let Some(Object::Array(nums)) = dict.get("Nums") {
let nums = nums.clone();
let mut iter = nums.into_iter();
while let (Some(idx_obj), Some(label_obj)) = (iter.next(), iter.next()) {
let idx = match idx_obj {
Object::Integer(n) => n,
_ => continue, };
let label_dict = match label_obj {
Object::Dictionary(d) => d,
Object::Reference(r) => match pdf.resolve(r).map_err(ConvertError::from)? {
Object::Dictionary(d) => d,
_ => continue,
},
_ => continue,
};
entries.push((idx, label_dict));
}
return Ok(());
}
if let Some(Object::Array(kids)) = dict.get("Kids") {
let kids = kids.clone();
for kid in kids {
let kid_ref = match kid {
Object::Reference(r) => r,
_ => continue,
};
if !seen.insert(kid_ref) {
continue; }
let child = pdf.resolve(kid_ref).map_err(ConvertError::from)?;
walk_pagelabels(pdf, child, entries, seen, depth + 1, max_depth)?;
}
}
Ok(())
}
pub fn build_pagelabels_section<R: Read + Seek>(
pdf: &mut Pdf<R>,
) -> Result<JsonValue, ConvertError> {
use crate::pages::DEFAULT_MAX_PAGE_TREE_DEPTH;
let catalog_ref = match pdf.root_ref() {
Some(r) => r,
None => return Ok(JsonValue::Array(vec![])),
};
let catalog = pdf.resolve(catalog_ref).map_err(ConvertError::from)?;
let catalog_dict = match catalog {
Object::Dictionary(d) => d,
_ => return Ok(JsonValue::Array(vec![])),
};
let pagelabels_val = match catalog_dict.get("PageLabels") {
Some(v) => v.clone(),
None => return Ok(JsonValue::Array(vec![])),
};
let root_node = match pagelabels_val {
Object::Reference(r) => pdf.resolve(r).map_err(ConvertError::from)?,
other => other,
};
let mut entries: Vec<(i64, Dictionary)> = Vec::new();
let mut seen = std::collections::BTreeSet::new();
walk_pagelabels(
pdf,
root_node,
&mut entries,
&mut seen,
0,
DEFAULT_MAX_PAGE_TREE_DEPTH,
)?;
entries.sort_by_key(|(idx, _)| *idx);
let result: Vec<JsonValue> = entries
.into_iter()
.map(|(idx, label_dict)| {
let label_json = label_dict_to_json(&label_dict);
JsonValue::Object(vec![
("index".to_string(), JsonValue::Integer(idx)),
("label".to_string(), label_json),
])
})
.collect();
Ok(JsonValue::Array(result))
}
fn outline_entry_to_json<R: Read + Seek>(
pdf: &mut Pdf<R>,
item_ref: crate::ObjectRef,
seen: &mut std::collections::BTreeSet<crate::ObjectRef>,
depth: usize,
max_depth: usize,
) -> Result<JsonValue, ConvertError> {
let item_obj = pdf.resolve(item_ref).map_err(ConvertError::from)?;
let item_dict = match item_obj {
Object::Dictionary(d) => d,
_ => {
let object_str = format!("{} {} R", item_ref.number, item_ref.generation);
return Ok(JsonValue::Object(vec![
("action".to_string(), JsonValue::Null),
("count".to_string(), JsonValue::Null),
("dest".to_string(), JsonValue::Null),
("flags".to_string(), JsonValue::Null),
("kids".to_string(), JsonValue::Array(vec![])),
("object".to_string(), JsonValue::String(object_str)),
("structureelement".to_string(), JsonValue::Null),
("title".to_string(), JsonValue::Null),
]));
}
};
let object_str = format!("{} {} R", item_ref.number, item_ref.generation);
let action = match item_dict.get("A") {
Some(v) => pdf_object_to_json(v)?,
None => JsonValue::Null,
};
let count = match item_dict.get("Count") {
Some(Object::Integer(n)) => JsonValue::Integer(*n),
_ => JsonValue::Null,
};
let dest = match item_dict.get("Dest") {
Some(v) => pdf_object_to_json(v)?,
None => JsonValue::Null,
};
let flags = match item_dict.get("F") {
Some(Object::Integer(n)) => JsonValue::Integer(*n),
_ => JsonValue::Null,
};
let structureelement = match item_dict.get("SE") {
Some(Object::Reference(r)) => JsonValue::String(format!("{} {} R", r.number, r.generation)),
_ => JsonValue::Null,
};
let title = match item_dict.get("Title") {
Some(Object::String(bytes)) => match decode_pdf_text_string(bytes) {
Some(s) => JsonValue::String(s),
None => JsonValue::Null,
},
_ => JsonValue::Null,
};
let kids = if depth >= max_depth {
vec![]
} else {
let first_ref = match item_dict.get("First") {
Some(Object::Reference(r)) => Some(*r),
_ => None,
};
collect_outline_chain(pdf, first_ref, seen, depth + 1, max_depth)?
};
Ok(JsonValue::Object(vec![
("action".to_string(), action),
("count".to_string(), count),
("dest".to_string(), dest),
("flags".to_string(), flags),
("kids".to_string(), JsonValue::Array(kids)),
("object".to_string(), JsonValue::String(object_str)),
("structureelement".to_string(), structureelement),
("title".to_string(), title),
]))
}
fn collect_outline_chain<R: Read + Seek>(
pdf: &mut Pdf<R>,
first_ref: Option<crate::ObjectRef>,
seen: &mut std::collections::BTreeSet<crate::ObjectRef>,
depth: usize,
max_depth: usize,
) -> Result<Vec<JsonValue>, ConvertError> {
let mut entries = Vec::new();
let mut current = first_ref;
while let Some(item_ref) = current {
if !seen.insert(item_ref) {
break;
}
let entry = outline_entry_to_json(pdf, item_ref, seen, depth, max_depth)?;
entries.push(entry);
let item_obj = pdf.resolve(item_ref).map_err(ConvertError::from)?;
current = match &item_obj {
Object::Dictionary(d) => match d.get("Next") {
Some(Object::Reference(r)) => Some(*r),
_ => None,
},
_ => None,
};
}
Ok(entries)
}
pub fn build_outlines_section<R: Read + Seek>(pdf: &mut Pdf<R>) -> Result<JsonValue, ConvertError> {
use crate::pages::DEFAULT_MAX_PAGE_TREE_DEPTH;
let catalog_ref = match pdf.root_ref() {
Some(r) => r,
None => return Ok(JsonValue::Array(vec![])),
};
let catalog = pdf.resolve(catalog_ref).map_err(ConvertError::from)?;
let catalog_dict = match catalog {
Object::Dictionary(d) => d,
_ => return Ok(JsonValue::Array(vec![])),
};
let outlines_val = match catalog_dict.get("Outlines") {
Some(v) => v.clone(),
None => return Ok(JsonValue::Array(vec![])),
};
let outlines_dict = match outlines_val {
Object::Reference(r) => match pdf.resolve(r).map_err(ConvertError::from)? {
Object::Dictionary(d) => d,
_ => return Ok(JsonValue::Array(vec![])),
},
Object::Dictionary(d) => d,
_ => return Ok(JsonValue::Array(vec![])),
};
let first_ref = match outlines_dict.get("First") {
Some(Object::Reference(r)) => Some(*r),
_ => return Ok(JsonValue::Array(vec![])),
};
let mut seen = std::collections::BTreeSet::new();
let entries = collect_outline_chain(pdf, first_ref, &mut seen, 0, DEFAULT_MAX_PAGE_TREE_DEPTH)?;
Ok(JsonValue::Array(entries))
}
#[allow(clippy::too_many_arguments)]
fn walk_acroform_fields<R: Read + Seek>(
pdf: &mut Pdf<R>,
field_ref: crate::ObjectRef,
parent_fullname: &str,
parent_ref: Option<crate::ObjectRef>,
output: &mut Vec<JsonValue>,
seen: &mut std::collections::BTreeSet<crate::ObjectRef>,
depth: usize,
max_depth: usize,
) -> Result<(), ConvertError> {
if depth > max_depth {
return Ok(());
}
if !seen.insert(field_ref) {
return Ok(()); }
let field_obj = pdf.resolve(field_ref).map_err(ConvertError::from)?;
let field_dict = match field_obj {
Object::Dictionary(d) => d,
_ => return Ok(()), };
let t_string = match field_dict.get("T") {
Some(Object::String(bytes)) => decode_pdf_text_string(bytes)
.unwrap_or_else(|| String::from_utf8_lossy(bytes).into_owned()),
_ => String::new(),
};
let fullname = if parent_fullname.is_empty() {
t_string.clone()
} else if t_string.is_empty() {
parent_fullname.to_string()
} else {
format!("{parent_fullname}.{t_string}")
};
let object_str = format!("{} {} R", field_ref.number, field_ref.generation);
let parent_json = match parent_ref {
Some(r) => JsonValue::String(format!("{} {} R", r.number, r.generation)),
None => JsonValue::Null,
};
let ft_obj = inherited_field_value(pdf, &field_dict, "FT")?;
let fieldtype = match ft_obj {
Some(Object::Name(bytes)) => {
JsonValue::String(String::from_utf8_lossy(&bytes).into_owned())
}
_ => JsonValue::Null,
};
let value = match inherited_field_value(pdf, &field_dict, "V")? {
Some(v) => pdf_object_to_json(&v)?,
None => JsonValue::Null,
};
let defaultvalue = match inherited_field_value(pdf, &field_dict, "DV")? {
Some(v) => pdf_object_to_json(&v)?,
None => JsonValue::Null,
};
let fieldflags = match inherited_field_value(pdf, &field_dict, "Ff")? {
Some(Object::Integer(n)) => JsonValue::Integer(n),
_ => JsonValue::Null,
};
let alternatename = match field_dict.get("TU") {
Some(Object::String(bytes)) => {
let s = decode_pdf_text_string(bytes)
.unwrap_or_else(|| String::from_utf8_lossy(bytes).into_owned());
JsonValue::String(s)
}
_ => JsonValue::Null,
};
let mappingname = match field_dict.get("TM") {
Some(Object::String(bytes)) => {
let s = decode_pdf_text_string(bytes)
.unwrap_or_else(|| String::from_utf8_lossy(bytes).into_owned());
JsonValue::String(s)
}
_ => JsonValue::Null,
};
let is_widget = field_dict
.get("Subtype")
.map(|v| matches!(v, Object::Name(n) if n.as_slice() == b"Widget"))
.unwrap_or(false);
let kids = match field_dict.get("Kids").cloned() {
Some(Object::Array(arr)) => arr,
Some(Object::Reference(r)) => match pdf.resolve(r).map_err(ConvertError::from)? {
Object::Array(arr) => arr,
_ => vec![],
},
_ => vec![],
};
let mut annotations: Vec<JsonValue> = Vec::new();
let mut has_subfield_kids = false;
let mut subfield_refs: Vec<crate::ObjectRef> = Vec::new();
for kid in &kids {
let kid_ref = match kid {
Object::Reference(r) => *r,
_ => continue,
};
let kid_obj = pdf.resolve(kid_ref).map_err(ConvertError::from)?;
let Object::Dictionary(d) = &kid_obj else {
continue;
};
let is_widget_subtype = matches!(
d.get("Subtype"),
Some(Object::Name(n)) if n.as_slice() == b"Widget"
);
let has_field_entries = d.get("T").is_some()
|| d.get("FT").is_some()
|| d.get("Kids").is_some()
|| d.get("V").is_some()
|| d.get("DV").is_some()
|| d.get("Ff").is_some()
|| d.get("TU").is_some()
|| d.get("TM").is_some();
if is_widget_subtype && !has_field_entries {
annotations.push(JsonValue::String(format!(
"{} {} R",
kid_ref.number, kid_ref.generation
)));
} else {
subfield_refs.push(kid_ref);
has_subfield_kids = true;
}
}
if is_widget && !has_subfield_kids {
annotations.insert(0, JsonValue::String(object_str.clone()));
}
let entry = JsonValue::Object(vec![
("alternatename".to_string(), alternatename),
("annotations".to_string(), JsonValue::Array(annotations)),
("defaultvalue".to_string(), defaultvalue),
("fieldflags".to_string(), fieldflags),
("fieldtype".to_string(), fieldtype),
("fullname".to_string(), JsonValue::String(fullname.clone())),
("mappingname".to_string(), mappingname),
("object".to_string(), JsonValue::String(object_str)),
("parent".to_string(), parent_json),
("value".to_string(), value),
]);
output.push(entry);
if depth < max_depth {
for kid_ref in subfield_refs {
walk_acroform_fields(
pdf,
kid_ref,
&fullname,
Some(field_ref),
output,
seen,
depth + 1,
max_depth,
)?;
}
}
Ok(())
}
fn inherited_field_value<R: Read + Seek>(
pdf: &mut Pdf<R>,
field_dict: &Dictionary,
key: &str,
) -> Result<Option<Object>, ConvertError> {
if let Some(local) = field_dict.get(key).cloned() {
return Ok(Some(local));
}
let mut parent = field_dict.get("Parent").cloned();
let mut seen: std::collections::BTreeSet<crate::ObjectRef> = std::collections::BTreeSet::new();
while let Some(Object::Reference(pr)) = parent {
if !seen.insert(pr) {
break;
}
match pdf.resolve(pr).map_err(ConvertError::from)? {
Object::Dictionary(pd) => {
if let Some(v) = pd.get(key).cloned() {
return Ok(Some(v));
}
parent = pd.get("Parent").cloned();
}
_ => break,
}
}
Ok(None)
}
pub fn build_acroform_section<R: Read + Seek>(pdf: &mut Pdf<R>) -> Result<JsonValue, ConvertError> {
use crate::pages::DEFAULT_MAX_PAGE_TREE_DEPTH;
let catalog_ref = match pdf.root_ref() {
Some(r) => r,
None => {
return Ok(JsonValue::Object(vec![
("fields".to_string(), JsonValue::Array(vec![])),
("hasacroform".to_string(), JsonValue::Bool(false)),
("needappearances".to_string(), JsonValue::Bool(false)),
]))
}
};
let catalog = pdf.resolve(catalog_ref).map_err(ConvertError::from)?;
let catalog_dict = match catalog {
Object::Dictionary(d) => d,
_ => {
return Ok(JsonValue::Object(vec![
("fields".to_string(), JsonValue::Array(vec![])),
("hasacroform".to_string(), JsonValue::Bool(false)),
("needappearances".to_string(), JsonValue::Bool(false)),
]))
}
};
let acroform_val = match catalog_dict.get("AcroForm") {
Some(v) => v.clone(),
None => {
return Ok(JsonValue::Object(vec![
("fields".to_string(), JsonValue::Array(vec![])),
("hasacroform".to_string(), JsonValue::Bool(false)),
("needappearances".to_string(), JsonValue::Bool(false)),
]))
}
};
let acroform_dict = match acroform_val {
Object::Reference(r) => match pdf.resolve(r).map_err(ConvertError::from)? {
Object::Dictionary(d) => d,
_ => {
return Ok(JsonValue::Object(vec![
("fields".to_string(), JsonValue::Array(vec![])),
("hasacroform".to_string(), JsonValue::Bool(true)),
("needappearances".to_string(), JsonValue::Bool(false)),
]))
}
},
Object::Dictionary(d) => d,
_ => {
return Ok(JsonValue::Object(vec![
("fields".to_string(), JsonValue::Array(vec![])),
("hasacroform".to_string(), JsonValue::Bool(true)),
("needappearances".to_string(), JsonValue::Bool(false)),
]))
}
};
let need_appearances = match acroform_dict.get("NeedAppearances") {
Some(Object::Boolean(b)) => *b,
_ => false,
};
let fields_array = match acroform_dict.get("Fields").cloned() {
Some(Object::Array(arr)) => arr,
Some(Object::Reference(r)) => match pdf.resolve(r).map_err(ConvertError::from)? {
Object::Array(arr) => arr,
_ => vec![],
},
_ => vec![],
};
let mut output: Vec<JsonValue> = Vec::new();
let mut seen = std::collections::BTreeSet::new();
for field_obj in &fields_array {
let field_ref = match field_obj {
Object::Reference(r) => *r,
_ => continue,
};
walk_acroform_fields(
pdf,
field_ref,
"",
None,
&mut output,
&mut seen,
0,
DEFAULT_MAX_PAGE_TREE_DEPTH,
)?;
}
Ok(JsonValue::Object(vec![
("fields".to_string(), JsonValue::Array(output)),
("hasacroform".to_string(), JsonValue::Bool(true)),
(
"needappearances".to_string(),
JsonValue::Bool(need_appearances),
),
]))
}
fn parse_pdf_date(bytes: &[u8]) -> Option<String> {
if !bytes.is_ascii() {
return None;
}
let s = std::str::from_utf8(bytes).ok()?;
let s = s.strip_prefix("D:").unwrap_or(s);
if s.len() < 4 {
return None;
}
let is_digits = |slice: &str| !slice.is_empty() && slice.bytes().all(|b| b.is_ascii_digit());
let year = &s[0..4];
if !is_digits(year) {
return None;
}
let prefix_len = s.len().min(14);
if !matches!(prefix_len, 4 | 6 | 8 | 10 | 12 | 14) {
return None;
}
let month_default = "01";
let day_default = "01";
let zero_default = "00";
let take = |start: usize, end: usize, fallback: &'static str| -> Option<&str> {
if s.len() >= end {
let slice = &s[start..end];
if is_digits(slice) {
Some(slice)
} else {
None
}
} else {
Some(fallback)
}
};
let month = take(4, 6, month_default)?;
let day = take(6, 8, day_default)?;
let hour = take(8, 10, zero_default)?;
let minute = take(10, 12, zero_default)?;
let second = take(12, 14, zero_default)?;
let in_range = |s: &str, lo: u8, hi: u8| -> bool {
s.parse::<u8>().map(|n| n >= lo && n <= hi).unwrap_or(false)
};
if !in_range(month, 1, 12)
|| !in_range(day, 1, 31)
|| !in_range(hour, 0, 23)
|| !in_range(minute, 0, 59)
|| !in_range(second, 0, 59)
{
return None;
}
let tz_str = if s.len() > 14 { &s[14..] } else { "" };
let tz = if tz_str.is_empty() || tz_str == "Z" || tz_str == "z" {
"Z".to_string()
} else if let Some(rest) = tz_str.strip_prefix('+') {
parse_tz_offset('+', rest)?
} else if let Some(rest) = tz_str.strip_prefix('-') {
parse_tz_offset('-', rest)?
} else {
return None;
};
Some(format!("{year}-{month}-{day}T{hour}:{minute}:{second}{tz}"))
}
fn parse_tz_offset(sign: char, rest: &str) -> Option<String> {
let rest = rest.strip_suffix('\'').unwrap_or(rest);
let (hh, mm) = if rest.len() == 5 && rest.as_bytes().get(2) == Some(&b'\'') {
(&rest[0..2], &rest[3..5])
} else if rest.len() == 4 {
(&rest[0..2], &rest[2..4])
} else if rest.len() == 2 {
(rest, "00")
} else {
return None;
};
if !hh.chars().all(|c| c.is_ascii_digit()) || !mm.chars().all(|c| c.is_ascii_digit()) {
return None;
}
let hh_n = hh.parse::<u8>().ok()?;
let mm_n = mm.parse::<u8>().ok()?;
if hh_n > 23 || mm_n > 59 {
return None;
}
if sign == '+' && hh_n == 0 && mm_n == 0 {
Some("Z".to_string())
} else {
Some(format!("{sign}{hh}:{mm}"))
}
}
fn checksum_to_hex(bytes: &[u8]) -> String {
bytes.iter().map(|b| format!("{b:02x}")).collect()
}
enum FilespecSource {
Indirect(crate::ObjectRef),
Direct(Dictionary),
}
fn walk_embedded_files_name_tree<R: Read + Seek>(
pdf: &mut Pdf<R>,
node: Object,
entries: &mut Vec<(String, FilespecSource)>,
seen: &mut std::collections::BTreeSet<crate::ObjectRef>,
depth: usize,
max_depth: usize,
) -> Result<(), ConvertError> {
if depth > max_depth {
return Ok(());
}
let dict = match node {
Object::Dictionary(d) => d,
_ => return Ok(()),
};
if let Some(Object::Array(names)) = dict.get("Names") {
let names = names.clone();
let mut iter = names.into_iter();
while let (Some(name_obj), Some(value_obj)) = (iter.next(), iter.next()) {
let name_str = match name_obj {
Object::String(bytes) => decode_pdf_text_string(&bytes)
.unwrap_or_else(|| String::from_utf8_lossy(&bytes).into_owned()),
_ => continue,
};
let source = match value_obj {
Object::Reference(r) => FilespecSource::Indirect(r),
Object::Dictionary(d) => FilespecSource::Direct(d),
_ => continue,
};
entries.push((name_str, source));
}
return Ok(());
}
if let Some(Object::Array(kids)) = dict.get("Kids") {
let kids = kids.clone();
for kid in kids {
let kid_ref = match kid {
Object::Reference(r) => r,
_ => continue,
};
if !seen.insert(kid_ref) {
continue; }
let child = pdf.resolve(kid_ref).map_err(ConvertError::from)?;
walk_embedded_files_name_tree(pdf, child, entries, seen, depth + 1, max_depth)?;
}
}
Ok(())
}
fn filespec_to_json<R: Read + Seek>(
pdf: &mut Pdf<R>,
filespec_ref: crate::ObjectRef,
) -> Result<JsonValue, ConvertError> {
let filespec_str = format!("{} {} R", filespec_ref.number, filespec_ref.generation);
let filespec_obj = pdf.resolve(filespec_ref).map_err(ConvertError::from)?;
let filespec_dict = match filespec_obj {
Object::Dictionary(d) => d,
_ => {
return Ok(JsonValue::Object(vec![
("description".to_string(), JsonValue::Null),
("filespec".to_string(), JsonValue::String(filespec_str)),
("names".to_string(), JsonValue::Object(vec![])),
("preferredcontents".to_string(), JsonValue::Null),
("preferredname".to_string(), JsonValue::Null),
("streams".to_string(), JsonValue::Object(vec![])),
]));
}
};
filespec_dict_to_json(pdf, &filespec_dict, Some(filespec_str))
}
fn filespec_dict_to_json<R: Read + Seek>(
pdf: &mut Pdf<R>,
filespec_dict: &Dictionary,
filespec_str: Option<String>,
) -> Result<JsonValue, ConvertError> {
let filespec_dict = filespec_dict.clone();
let filespec_value = match filespec_str {
Some(s) => JsonValue::String(s),
None => JsonValue::Null,
};
let description = match filespec_dict.get("Desc") {
Some(Object::String(bytes)) => {
let s = decode_pdf_text_string(bytes)
.unwrap_or_else(|| String::from_utf8_lossy(bytes).into_owned());
JsonValue::String(s)
}
_ => JsonValue::Null,
};
let name_keys = ["DOS", "F", "Mac", "UF", "Unix"];
let mut names_pairs: Vec<(String, JsonValue)> = Vec::new();
for key in &name_keys {
if let Some(Object::String(bytes)) = filespec_dict.get(*key) {
let s = decode_pdf_text_string(bytes)
.unwrap_or_else(|| String::from_utf8_lossy(bytes).into_owned());
names_pairs.push((format!("/{key}"), JsonValue::String(s)));
}
}
let preferred_name_key_order = ["UF", "F", "Unix", "Mac", "DOS"];
let preferredname = preferred_name_key_order
.iter()
.find_map(|key| {
if let Some(Object::String(bytes)) = filespec_dict.get(*key) {
let s = decode_pdf_text_string(bytes)
.unwrap_or_else(|| String::from_utf8_lossy(bytes).into_owned());
Some(JsonValue::String(s))
} else {
None
}
})
.unwrap_or(JsonValue::Null);
let ef_dict = match filespec_dict.get("EF") {
Some(Object::Dictionary(d)) => Some(d.clone()),
Some(Object::Reference(r)) => match pdf.resolve(*r).map_err(ConvertError::from)? {
Object::Dictionary(d) => Some(d),
_ => None,
},
_ => None,
};
let preferred_ef_key_order = ["UF", "F", "Unix", "Mac", "DOS"];
let preferredcontents = if let Some(ref ef) = ef_dict {
preferred_ef_key_order
.iter()
.find_map(|key| {
if let Some(Object::Reference(r)) = ef.get(*key) {
Some(JsonValue::String(format!(
"{} {} R",
r.number, r.generation
)))
} else {
None
}
})
.unwrap_or(JsonValue::Null)
} else {
JsonValue::Null
};
let ef_key_order = ["DOS", "F", "Mac", "UF", "Unix"];
let mut streams_pairs: Vec<(String, JsonValue)> = Vec::new();
if let Some(ref ef) = ef_dict {
for key in &ef_key_order {
let stream_ref = match ef.get(*key) {
Some(Object::Reference(r)) => *r,
_ => continue,
};
let stream_obj = pdf.resolve(stream_ref).map_err(ConvertError::from)?;
let stream = match stream_obj {
Object::Stream(s) => s,
_ => continue,
};
let mimetype = match stream.dict.get("Subtype") {
Some(Object::Name(bytes)) => {
let s = String::from_utf8_lossy(bytes).into_owned();
JsonValue::String(s)
}
_ => JsonValue::Null,
};
let params_dict = match stream.dict.get("Params") {
Some(Object::Dictionary(d)) => Some(d.clone()),
Some(Object::Reference(r)) => match pdf.resolve(*r).map_err(ConvertError::from)? {
Object::Dictionary(d) => Some(d),
_ => None,
},
_ => None,
};
let checksum = if let Some(ref p) = params_dict {
match p.get("CheckSum") {
Some(Object::String(bytes)) => JsonValue::String(checksum_to_hex(bytes)),
_ => JsonValue::Null,
}
} else {
JsonValue::Null
};
let creationdate = if let Some(ref p) = params_dict {
match p.get("CreationDate") {
Some(Object::String(bytes)) => match parse_pdf_date(bytes) {
Some(s) => JsonValue::String(s),
None => JsonValue::Null,
},
_ => JsonValue::Null,
}
} else {
JsonValue::Null
};
let modificationdate = if let Some(ref p) = params_dict {
match p.get("ModDate") {
Some(Object::String(bytes)) => match parse_pdf_date(bytes) {
Some(s) => JsonValue::String(s),
None => JsonValue::Null,
},
_ => JsonValue::Null,
}
} else {
JsonValue::Null
};
let stream_entry = JsonValue::Object(vec![
("checksum".to_string(), checksum),
("creationdate".to_string(), creationdate),
("mimetype".to_string(), mimetype),
("modificationdate".to_string(), modificationdate),
]);
streams_pairs.push((format!("/{key}"), stream_entry));
}
}
Ok(JsonValue::Object(vec![
("description".to_string(), description),
("filespec".to_string(), filespec_value),
("names".to_string(), JsonValue::Object(names_pairs)),
("preferredcontents".to_string(), preferredcontents),
("preferredname".to_string(), preferredname),
("streams".to_string(), JsonValue::Object(streams_pairs)),
]))
}
pub fn build_attachments_section<R: Read + Seek>(
pdf: &mut Pdf<R>,
) -> Result<JsonValue, ConvertError> {
use crate::pages::DEFAULT_MAX_PAGE_TREE_DEPTH;
let catalog_ref = match pdf.root_ref() {
Some(r) => r,
None => return Ok(JsonValue::Object(vec![])),
};
let catalog = pdf.resolve(catalog_ref).map_err(ConvertError::from)?;
let catalog_dict = match catalog {
Object::Dictionary(d) => d,
_ => return Ok(JsonValue::Object(vec![])),
};
let names_dict = match catalog_dict.get("Names") {
Some(Object::Dictionary(d)) => d.clone(),
Some(Object::Reference(r)) => match pdf.resolve(*r).map_err(ConvertError::from)? {
Object::Dictionary(d) => d,
_ => return Ok(JsonValue::Object(vec![])),
},
_ => return Ok(JsonValue::Object(vec![])),
};
let ef_root = match names_dict.get("EmbeddedFiles") {
Some(Object::Dictionary(d)) => Object::Dictionary(d.clone()),
Some(Object::Reference(r)) => pdf.resolve(*r).map_err(ConvertError::from)?,
_ => return Ok(JsonValue::Object(vec![])),
};
let mut raw_entries: Vec<(String, FilespecSource)> = Vec::new();
let mut seen = std::collections::BTreeSet::new();
walk_embedded_files_name_tree(
pdf,
ef_root,
&mut raw_entries,
&mut seen,
0,
DEFAULT_MAX_PAGE_TREE_DEPTH,
)?;
raw_entries.sort_by(|a, b| a.0.cmp(&b.0));
let mut pairs: Vec<(String, JsonValue)> = Vec::new();
for (name, source) in raw_entries {
let entry = match source {
FilespecSource::Indirect(filespec_ref) => filespec_to_json(pdf, filespec_ref)?,
FilespecSource::Direct(dict) => filespec_dict_to_json(pdf, &dict, None)?,
};
pairs.push((name, entry));
}
Ok(JsonValue::Object(pairs))
}
fn cf_method_string(encrypt: &Dictionary, selector: Option<&str>) -> &'static str {
fn revision_default(encrypt: &Dictionary) -> &'static str {
match encrypt.get("R") {
Some(Object::Integer(r)) if *r >= 5 => "AESv3",
Some(Object::Integer(4)) => "AESv2",
_ => "RC4",
}
}
let Some(selector) = selector else {
return revision_default(encrypt);
};
if selector == "Identity" {
return "none";
}
let Some(Object::Dictionary(cf)) = encrypt.get("CF") else {
return revision_default(encrypt);
};
let Some(Object::Dictionary(filter)) = cf.get(selector) else {
return revision_default(encrypt);
};
match filter.get("CFM") {
Some(Object::Name(cfm)) => match cfm.as_slice() {
b"AESV2" => "AESv2",
b"AESV3" => "AESv3",
b"V2" => "RC4",
b"None" => "none",
_ => revision_default(encrypt),
},
_ => revision_default(encrypt),
}
}
fn dict_name_str<'a>(dict: &'a Dictionary, key: &str) -> Option<&'a str> {
match dict.get(key) {
Some(Object::Name(n)) => std::str::from_utf8(n).ok(),
_ => None,
}
}
fn capabilities_from_p(p_raw: i32) -> Vec<(String, JsonValue)> {
let p = p_raw as u32;
let accessibility = (p & 0x0200) != 0;
let extract = (p & 0x0010) != 0;
let modify = (p & 0x0008) != 0;
let modifyannotations = (p & 0x0020) != 0;
let modifyassembly = (p & 0x0400) != 0;
let modifyforms = (p & 0x0100) != 0;
let modifyother = modify;
let printhigh = (p & 0x0800) != 0;
let printlow = (p & 0x0004) != 0;
vec![
("accessibility".into(), JsonValue::Bool(accessibility)),
("extract".into(), JsonValue::Bool(extract)),
("modify".into(), JsonValue::Bool(modify)),
(
"modifyannotations".into(),
JsonValue::Bool(modifyannotations),
),
("modifyassembly".into(), JsonValue::Bool(modifyassembly)),
("modifyforms".into(), JsonValue::Bool(modifyforms)),
("modifyother".into(), JsonValue::Bool(modifyother)),
("printhigh".into(), JsonValue::Bool(printhigh)),
("printlow".into(), JsonValue::Bool(printlow)),
]
}
fn all_true_capabilities() -> JsonValue {
JsonValue::Object(vec![
("accessibility".into(), JsonValue::Bool(true)),
("extract".into(), JsonValue::Bool(true)),
("modify".into(), JsonValue::Bool(true)),
("modifyannotations".into(), JsonValue::Bool(true)),
("modifyassembly".into(), JsonValue::Bool(true)),
("modifyforms".into(), JsonValue::Bool(true)),
("modifyother".into(), JsonValue::Bool(true)),
("printhigh".into(), JsonValue::Bool(true)),
("printlow".into(), JsonValue::Bool(true)),
])
}
pub fn build_encrypt_section<R: Read + Seek>(pdf: &mut Pdf<R>) -> Result<JsonValue, ConvertError> {
let encrypt_dict: Option<Dictionary> = match pdf.trailer().get("Encrypt").cloned() {
None => None,
Some(Object::Dictionary(d)) => Some(d),
Some(Object::Reference(r)) => match pdf.resolve(r).map_err(ConvertError::from)? {
Object::Dictionary(d) => Some(d),
_ => None,
},
_ => None,
};
let is_encrypted = pdf.is_encrypted();
match encrypt_dict {
None => {
let capabilities = all_true_capabilities();
let parameters = JsonValue::Object(vec![
("P".into(), JsonValue::Integer(0)),
("R".into(), JsonValue::Integer(0)),
("V".into(), JsonValue::Integer(0)),
("bits".into(), JsonValue::Integer(0)),
("filemethod".into(), JsonValue::String("none".into())),
("key".into(), JsonValue::Null),
("method".into(), JsonValue::String("none".into())),
("streammethod".into(), JsonValue::String("none".into())),
("stringmethod".into(), JsonValue::String("none".into())),
]);
Ok(JsonValue::Object(vec![
("capabilities".into(), capabilities),
("encrypted".into(), JsonValue::Bool(false)),
("ownerpasswordmatched".into(), JsonValue::Bool(false)),
("parameters".into(), parameters),
("recovereduserpassword".into(), JsonValue::Null),
("userpasswordmatched".into(), JsonValue::Bool(false)),
]))
}
Some(ref enc) => {
let v = match enc.get("V") {
Some(Object::Integer(n)) => *n,
_ => 0,
};
let r = match enc.get("R") {
Some(Object::Integer(n)) => *n,
_ => 0,
};
let p_raw = match enc.get("P") {
Some(Object::Integer(n)) => *n as i32,
_ => 0,
};
let bits = match enc.get("Length") {
Some(Object::Integer(n)) => *n,
None => 40,
_ => 0,
};
let stmf = dict_name_str(enc, "StmF");
let strf = dict_name_str(enc, "StrF");
let eff = dict_name_str(enc, "EFF");
let (streammethod, stringmethod, filemethod) = if v >= 4 {
let sm = cf_method_string(enc, stmf);
let st = cf_method_string(enc, strf);
let fm = cf_method_string(enc, eff.or(stmf));
(sm, st, fm)
} else if v == 1 || v == 2 {
("RC4", "RC4", "RC4")
} else {
("none", "none", "none")
};
let method = streammethod;
let capabilities = JsonValue::Object(capabilities_from_p(p_raw));
let parameters = JsonValue::Object(vec![
("P".into(), JsonValue::Integer(p_raw as i64)),
("R".into(), JsonValue::Integer(r)),
("V".into(), JsonValue::Integer(v)),
("bits".into(), JsonValue::Integer(bits)),
("filemethod".into(), JsonValue::String(filemethod.into())),
("key".into(), JsonValue::Null),
("method".into(), JsonValue::String(method.into())),
(
"streammethod".into(),
JsonValue::String(streammethod.into()),
),
(
"stringmethod".into(),
JsonValue::String(stringmethod.into()),
),
]);
Ok(JsonValue::Object(vec![
("capabilities".into(), capabilities),
("encrypted".into(), JsonValue::Bool(is_encrypted)),
(
"ownerpasswordmatched".into(),
JsonValue::Bool(pdf.owner_password_matched()),
),
("parameters".into(), parameters),
("recovereduserpassword".into(), JsonValue::Null),
(
"userpasswordmatched".into(),
JsonValue::Bool(pdf.user_password_matched()),
),
]))
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum JsonKey {
Acroform,
Attachments,
Encrypt,
Objectinfo,
Objects,
Outlines,
Pagelabels,
Pages,
Qpdf,
}
impl JsonKey {
pub const ALL_NAMES: &'static [&'static str] = &[
"acroform",
"attachments",
"encrypt",
"objectinfo",
"objects",
"outlines",
"pagelabels",
"pages",
"qpdf",
];
#[allow(clippy::should_implement_trait)]
pub fn from_str(s: &str) -> Option<Self> {
match s {
"acroform" => Some(JsonKey::Acroform),
"attachments" => Some(JsonKey::Attachments),
"encrypt" => Some(JsonKey::Encrypt),
"objectinfo" => Some(JsonKey::Objectinfo),
"objects" => Some(JsonKey::Objects),
"outlines" => Some(JsonKey::Outlines),
"pagelabels" => Some(JsonKey::Pagelabels),
"pages" => Some(JsonKey::Pages),
"qpdf" => Some(JsonKey::Qpdf),
_ => None,
}
}
fn output_key_name(self) -> &'static str {
match self {
JsonKey::Acroform => "acroform",
JsonKey::Attachments => "attachments",
JsonKey::Encrypt => "encrypt",
JsonKey::Objectinfo => "qpdf",
JsonKey::Objects => "qpdf",
JsonKey::Outlines => "outlines",
JsonKey::Pagelabels => "pagelabels",
JsonKey::Pages => "pages",
JsonKey::Qpdf => "qpdf",
}
}
}
pub fn filter_json_keys(v2: JsonValue, keys: &[JsonKey]) -> JsonValue {
if keys.is_empty() {
return v2;
}
let mut requested: std::collections::HashSet<&'static str> = std::collections::HashSet::new();
for k in keys {
requested.insert(k.output_key_name());
}
let pairs = match v2 {
JsonValue::Object(p) => p,
other => return other,
};
let mut out: Vec<(String, JsonValue)> = Vec::new();
for envelope_key in ["version", "parameters"] {
if let Some((k, v)) = pairs.iter().find(|(k, _)| k == envelope_key) {
out.push((k.clone(), v.clone()));
}
}
const V2_ORDER: &[&str] = &[
"pages",
"pagelabels",
"acroform",
"attachments",
"encrypt",
"outlines",
"qpdf",
];
for §ion_name in V2_ORDER {
if !requested.contains(section_name) {
continue;
}
if let Some((k, v)) = pairs.iter().find(|(k, _)| k == section_name) {
out.push((k.clone(), v.clone()));
}
}
JsonValue::Object(out)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum JsonObjectSelector {
Object { number: u32, generation: u16 },
Trailer,
}
impl JsonObjectSelector {
#[allow(clippy::should_implement_trait)]
pub fn from_str(s: &str) -> Option<Self> {
if s == "trailer" {
return Some(JsonObjectSelector::Trailer);
}
if s.is_empty() {
return None;
}
let parts: Vec<&str> = s.splitn(3, ',').collect();
if parts.len() > 2 {
return None;
}
let num_str = parts[0];
if num_str.is_empty() || !num_str.bytes().all(|b| b.is_ascii_digit()) {
return None;
}
let number: u32 = num_str.parse().ok()?;
let generation: u16 = if parts.len() == 2 {
let gen_str = parts[1];
if gen_str.is_empty() || !gen_str.bytes().all(|b| b.is_ascii_digit()) {
return None;
}
gen_str.parse().ok()?
} else {
0
};
Some(JsonObjectSelector::Object { number, generation })
}
}
pub fn filter_json_objects(v2: JsonValue, selectors: &[JsonObjectSelector]) -> JsonValue {
if selectors.is_empty() {
return v2;
}
let mut wanted: std::collections::HashSet<String> =
std::collections::HashSet::with_capacity(selectors.len());
for sel in selectors {
match sel {
JsonObjectSelector::Object { number, generation } => {
wanted.insert(format!("obj:{number} {generation} R"));
}
JsonObjectSelector::Trailer => {
wanted.insert("trailer".to_string());
}
}
}
let mut pairs = match v2 {
JsonValue::Object(p) => p,
other => return other,
};
let qpdf_idx = match pairs.iter().position(|(k, _)| k == "qpdf") {
Some(i) => i,
None => return JsonValue::Object(pairs),
};
let qpdf_val = std::mem::replace(
&mut pairs[qpdf_idx].1,
JsonValue::Null, );
let mut arr = match qpdf_val {
JsonValue::Array(a) if a.len() == 2 => a,
other => {
pairs[qpdf_idx].1 = other;
return JsonValue::Object(pairs);
}
};
let objects_map = std::mem::replace(&mut arr[1], JsonValue::Null);
let filtered_map = match objects_map {
JsonValue::Object(obj_pairs) => {
let kept: Vec<(String, JsonValue)> = obj_pairs
.into_iter()
.filter(|(k, _)| wanted.contains(k))
.collect();
JsonValue::Object(kept)
}
other => {
arr[1] = other;
pairs[qpdf_idx].1 = JsonValue::Array(arr);
return JsonValue::Object(pairs);
}
};
arr[1] = filtered_map;
pairs[qpdf_idx].1 = JsonValue::Array(arr);
JsonValue::Object(pairs)
}
pub fn build_qpdf_json_v2<R: Read + Seek>(
pdf: &mut Pdf<R>,
decode_level: DecodeLevel,
) -> Result<JsonValue, ConvertError> {
build_qpdf_json_v2_with_options(pdf, decode_level, &StreamDataMode::None)
}
pub fn build_qpdf_json_v2_with_options<R: Read + Seek>(
pdf: &mut Pdf<R>,
decode_level: DecodeLevel,
stream_mode: &StreamDataMode,
) -> Result<JsonValue, ConvertError> {
let mut pairs = match build_envelope(decode_level) {
JsonValue::Object(p) => p,
_ => unreachable!("build_envelope always returns an Object"),
};
let pages = build_pages_section(pdf)?;
pairs.push(("pages".to_string(), pages));
let pagelabels = build_pagelabels_section(pdf)?;
pairs.push(("pagelabels".to_string(), pagelabels));
let acroform = build_acroform_section(pdf)?;
pairs.push(("acroform".to_string(), acroform));
let attachments = build_attachments_section(pdf)?;
pairs.push(("attachments".to_string(), attachments));
let encrypt = build_encrypt_section(pdf)?;
pairs.push(("encrypt".to_string(), encrypt));
let outlines = build_outlines_section(pdf)?;
pairs.push(("outlines".to_string(), outlines));
let max_object_id = pdf
.object_refs()
.iter()
.map(|r| r.number)
.max()
.unwrap_or(0);
let qpdf_metadata = QpdfMetadata {
pdf_version: pdf.version().to_string(),
max_object_id,
pushed_inherited_page_resources: false,
called_get_all_pages: true,
};
let qpdf = build_qpdf_key_with_stream_mode(pdf, qpdf_metadata, stream_mode)?;
pairs.push(("qpdf".to_string(), qpdf));
Ok(JsonValue::Object(pairs))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::json::write;
fn emit(v: &JsonValue) -> String {
let mut buf = Vec::new();
write(v, &mut buf).expect("write failed");
String::from_utf8(buf).expect("not utf-8")
}
#[test]
fn envelope_generalized_structural_match() {
let envelope = build_envelope(DecodeLevel::Generalized);
let out = emit(&envelope);
assert!(
out.contains("\"version\": 2"),
"missing version field: {out}"
);
assert!(
out.contains("\"decodelevel\": \"generalized\""),
"missing decodelevel: {out}"
);
assert!(out.ends_with('\n'), "missing trailing newline");
let expected = "{\n \"version\": 2,\n \"parameters\": {\n \"decodelevel\": \"generalized\"\n }\n}\n";
assert_eq!(out, expected, "structural mismatch");
}
#[test]
fn envelope_none_decodelevel() {
let out = emit(&build_envelope(DecodeLevel::None));
assert!(
out.contains("\"decodelevel\": \"none\""),
"wrong decodelevel: {out}"
);
}
#[test]
fn envelope_specialized_decodelevel() {
let out = emit(&build_envelope(DecodeLevel::Specialized));
assert!(
out.contains("\"decodelevel\": \"specialized\""),
"wrong decodelevel: {out}"
);
}
#[test]
fn envelope_all_decodelevel() {
let out = emit(&build_envelope(DecodeLevel::All));
assert!(
out.contains("\"decodelevel\": \"all\""),
"wrong decodelevel: {out}"
);
}
#[test]
fn key_order_version_before_parameters() {
let envelope = build_envelope(DecodeLevel::Generalized);
let out = emit(&envelope);
let version_pos = out.find("\"version\"").expect("version not found");
let parameters_pos = out.find("\"parameters\"").expect("parameters not found");
assert!(
version_pos < parameters_pos,
"version must appear before parameters, got: {out}"
);
}
#[test]
fn parameters_has_only_decodelevel() {
let envelope = build_envelope(DecodeLevel::Generalized);
let JsonValue::Object(pairs) = &envelope else {
panic!("envelope is not an Object");
};
let (_, params_val) = pairs
.iter()
.find(|(k, _)| k == "parameters")
.expect("parameters key not found");
let JsonValue::Object(param_pairs) = params_val else {
panic!("parameters is not an Object");
};
assert_eq!(
param_pairs.len(),
1,
"parameters must have exactly 1 key, got: {:?}",
param_pairs.iter().map(|(k, _)| k).collect::<Vec<_>>()
);
assert_eq!(
param_pairs[0].0, "decodelevel",
"the single key must be 'decodelevel'"
);
}
#[test]
fn default_decode_level_is_generalized() {
assert_eq!(DecodeLevel::default(), DecodeLevel::Generalized);
}
#[test]
fn as_qpdf_str_all_variants() {
assert_eq!(DecodeLevel::None.as_qpdf_str(), "none");
assert_eq!(DecodeLevel::Generalized.as_qpdf_str(), "generalized");
assert_eq!(DecodeLevel::Specialized.as_qpdf_str(), "specialized");
assert_eq!(DecodeLevel::All.as_qpdf_str(), "all");
}
#[test]
fn object_bool_true_to_json() {
assert_eq!(
pdf_object_to_json(&Object::Boolean(true)).unwrap(),
JsonValue::Bool(true)
);
}
#[test]
fn object_bool_false_to_json() {
assert_eq!(
pdf_object_to_json(&Object::Boolean(false)).unwrap(),
JsonValue::Bool(false)
);
}
#[test]
fn object_integer_to_json() {
assert_eq!(
pdf_object_to_json(&Object::Integer(42)).unwrap(),
JsonValue::Integer(42)
);
assert_eq!(
pdf_object_to_json(&Object::Integer(-7)).unwrap(),
JsonValue::Integer(-7)
);
}
#[test]
fn object_real_to_json() {
assert_eq!(
pdf_object_to_json(&Object::Real(1.5)).unwrap(),
JsonValue::Float(1.5)
);
}
#[test]
fn object_real_non_finite_returns_error() {
assert_eq!(
pdf_object_to_json(&Object::Real(f64::NAN)),
Err(ConvertError::NonFiniteFloat)
);
assert_eq!(
pdf_object_to_json(&Object::Real(f64::INFINITY)),
Err(ConvertError::NonFiniteFloat)
);
}
#[test]
fn object_name_to_json() {
assert_eq!(
pdf_object_to_json(&Object::Name(b"Type".to_vec())).unwrap(),
JsonValue::String("/Type".to_string())
);
assert_eq!(
pdf_object_to_json(&Object::Name(b"Font".to_vec())).unwrap(),
JsonValue::String("/Font".to_string())
);
}
#[test]
fn object_string_ascii_text_has_u_prefix() {
let result = pdf_object_to_json(&Object::String(b"hello".to_vec())).unwrap();
assert_eq!(result, JsonValue::String("u:hello".to_string()));
}
#[test]
fn object_string_binary_has_b_prefix() {
let result = pdf_object_to_json(&Object::String(vec![0x2d, 0x01, 0x80])).unwrap();
assert_eq!(result, JsonValue::String("b:2d0180".to_string()));
}
#[test]
fn object_string_pdfdoc_high_byte_decodes_as_text() {
let result = pdf_object_to_json(&Object::String(vec![b'A', 0xC7, b'B'])).unwrap();
assert_eq!(result, JsonValue::String("u:A\u{00C7}B".to_string()));
}
#[test]
fn object_string_utf16be_bom_decodes_to_unicode() {
let bytes = vec![0xFE, 0xFF, 0x00, 0x41, 0x00, 0x42];
let result = pdf_object_to_json(&Object::String(bytes)).unwrap();
assert_eq!(result, JsonValue::String("u:AB".to_string()));
}
#[test]
fn object_string_utf16le_bom_decodes_to_unicode() {
let bytes = vec![0xFF, 0xFE, 0x41, 0x00, 0x42, 0x00];
let result = pdf_object_to_json(&Object::String(bytes)).unwrap();
assert_eq!(result, JsonValue::String("u:AB".to_string()));
}
#[test]
fn object_string_utf16be_japanese_decodes_to_unicode() {
let bytes = vec![0xFE, 0xFF, 0x30, 0x42, 0x30, 0x44];
let result = pdf_object_to_json(&Object::String(bytes)).unwrap();
assert_eq!(result, JsonValue::String("u:あい".to_string()));
}
#[test]
fn object_string_utf16be_with_odd_length_falls_back_to_binary() {
let bytes = vec![0xFE, 0xFF, 0x00, 0x41, 0x00];
let result = pdf_object_to_json(&Object::String(bytes)).unwrap();
assert_eq!(result, JsonValue::String("b:feff004100".to_string()));
}
#[test]
fn object_string_undefined_pdfdoc_byte_falls_back_to_binary() {
let bytes = vec![0xab, 0xcd, 0x00, 0xef];
let result = pdf_object_to_json(&Object::String(bytes)).unwrap();
assert_eq!(result, JsonValue::String("b:abcd00ef".to_string()));
}
#[test]
fn object_string_empty_is_text() {
let result = pdf_object_to_json(&Object::String(vec![])).unwrap();
assert_eq!(result, JsonValue::String("u:".to_string()));
}
#[test]
fn object_reference_to_json() {
use crate::ObjectRef;
let result = pdf_object_to_json(&Object::Reference(ObjectRef::new(2, 0))).unwrap();
assert_eq!(result, JsonValue::String("2 0 R".to_string()));
}
#[test]
fn object_null_to_json() {
assert_eq!(pdf_object_to_json(&Object::Null).unwrap(), JsonValue::Null);
}
#[test]
fn object_array_to_json() {
let arr = Object::Array(vec![
Object::Integer(1),
Object::Boolean(true),
Object::Null,
]);
let result = pdf_object_to_json(&arr).unwrap();
assert_eq!(
result,
JsonValue::Array(vec![
JsonValue::Integer(1),
JsonValue::Bool(true),
JsonValue::Null,
])
);
}
#[test]
fn object_dict_to_json_keys_alphabetical() {
use crate::object::Dictionary;
let mut dict = Dictionary::new();
dict.insert("Zebra", Object::Integer(1));
dict.insert("Apple", Object::Integer(2));
dict.insert("Mango", Object::Integer(3));
let result = pdf_object_to_json(&Object::Dictionary(dict)).unwrap();
let JsonValue::Object(pairs) = result else {
panic!("expected Object, got {:?}", result);
};
let keys: Vec<&str> = pairs.iter().map(|(k, _)| k.as_str()).collect();
assert_eq!(keys, vec!["/Apple", "/Mango", "/Zebra"]);
}
#[test]
fn object_stream_nested_yields_stream_shape() {
use crate::object::{Dictionary, Stream};
let stream = Object::Stream(Stream::new(Dictionary::new(), vec![]));
let result = pdf_object_to_json(&stream).unwrap();
let JsonValue::Object(pairs) = &result else {
panic!("expected Object");
};
assert_eq!(pairs.len(), 1);
assert_eq!(pairs[0].0, "stream");
}
fn load_one_page_pdf() -> crate::Pdf<std::io::Cursor<Vec<u8>>> {
let manifest = std::path::Path::new(env!("CARGO_MANIFEST_DIR"));
let fixture = manifest.join("../../tests/fixtures/compat/one-page.pdf");
let bytes = std::fs::read(&fixture)
.unwrap_or_else(|e| panic!("one-page.pdf not found at {}: {e}", fixture.display()));
crate::Pdf::open_mem_owned(bytes).expect("failed to open one-page.pdf")
}
fn load_three_page_pdf() -> crate::Pdf<std::io::Cursor<Vec<u8>>> {
let manifest = std::path::Path::new(env!("CARGO_MANIFEST_DIR"));
let fixture = manifest.join("../../tests/fixtures/compat/three-page.pdf");
let bytes = std::fs::read(&fixture)
.unwrap_or_else(|e| panic!("three-page.pdf not found at {}: {e}", fixture.display()));
crate::Pdf::open_mem_owned(bytes).expect("failed to open three-page.pdf")
}
#[test]
fn build_qpdf_key_returns_two_element_array() {
let mut pdf = load_one_page_pdf();
let meta = QpdfMetadata {
pdf_version: "1.3".to_string(),
max_object_id: 7,
pushed_inherited_page_resources: false,
called_get_all_pages: true,
};
let result = build_qpdf_key(&mut pdf, meta).expect("build_qpdf_key failed");
let JsonValue::Array(elems) = result else {
panic!("expected Array, got {:?}", result);
};
assert_eq!(
elems.len(),
2,
"expected 2 elements (metadata + objects_map)"
);
}
#[test]
fn build_qpdf_key_metadata_keys_and_values() {
let mut pdf = load_one_page_pdf();
let meta = QpdfMetadata {
pdf_version: "1.3".to_string(),
max_object_id: 7,
pushed_inherited_page_resources: false,
called_get_all_pages: true,
};
let JsonValue::Array(elems) =
build_qpdf_key(&mut pdf, meta).expect("build_qpdf_key failed")
else {
panic!("expected Array");
};
let JsonValue::Object(meta_pairs) = &elems[0] else {
panic!("metadata is not an Object");
};
assert_eq!(meta_pairs[0].0, "jsonversion");
assert_eq!(meta_pairs[0].1, JsonValue::Integer(2));
assert_eq!(meta_pairs[1].0, "pdfversion");
assert_eq!(meta_pairs[1].1, JsonValue::String("1.3".to_string()));
assert_eq!(meta_pairs[2].0, "pushedinheritedpageresources");
assert_eq!(meta_pairs[2].1, JsonValue::Bool(false));
assert_eq!(meta_pairs[3].0, "calledgetallpages");
assert_eq!(meta_pairs[3].1, JsonValue::Bool(true));
assert_eq!(meta_pairs[4].0, "maxobjectid");
assert_eq!(meta_pairs[4].1, JsonValue::Integer(7));
}
#[test]
fn build_qpdf_key_objects_map_has_expected_keys() {
let mut pdf = load_one_page_pdf();
let meta = QpdfMetadata {
pdf_version: "1.3".to_string(),
max_object_id: 7,
pushed_inherited_page_resources: false,
called_get_all_pages: true,
};
let JsonValue::Array(elems) =
build_qpdf_key(&mut pdf, meta).expect("build_qpdf_key failed")
else {
panic!("expected Array");
};
let JsonValue::Object(map_pairs) = &elems[1] else {
panic!("objects_map is not an Object");
};
let keys: Vec<&str> = map_pairs.iter().map(|(k, _)| k.as_str()).collect();
assert!(keys.contains(&"trailer"), "trailer key missing: {keys:?}");
assert_eq!(
map_pairs.len(),
8,
"expected 7 objs + trailer, got {keys:?}"
);
let mut sorted = keys.clone();
sorted.sort();
assert_eq!(keys, sorted, "objects_map keys are not sorted: {keys:?}");
}
#[test]
fn build_qpdf_key_obj7_is_stream() {
let mut pdf = load_one_page_pdf();
let meta = QpdfMetadata {
pdf_version: "1.3".to_string(),
max_object_id: 7,
pushed_inherited_page_resources: false,
called_get_all_pages: true,
};
let JsonValue::Array(elems) =
build_qpdf_key(&mut pdf, meta).expect("build_qpdf_key failed")
else {
panic!("expected Array");
};
let JsonValue::Object(map_pairs) = &elems[1] else {
panic!("objects_map is not an Object");
};
let obj7 = map_pairs
.iter()
.find(|(k, _)| k == "obj:7 0 R")
.map(|(_, v)| v)
.expect("obj:7 0 R not found");
let JsonValue::Object(obj7_pairs) = obj7 else {
panic!("obj:7 0 R is not an Object: {obj7:?}");
};
assert_eq!(obj7_pairs[0].0, "stream", "obj:7 must have 'stream' key");
let JsonValue::Object(stream_inner) = &obj7_pairs[0].1 else {
panic!("stream value is not an Object");
};
assert_eq!(stream_inner[0].0, "dict", "stream must have 'dict' key");
}
#[test]
fn build_qpdf_key_trailer_has_value_wrapper() {
let mut pdf = load_one_page_pdf();
let meta = QpdfMetadata {
pdf_version: "1.3".to_string(),
max_object_id: 7,
pushed_inherited_page_resources: false,
called_get_all_pages: true,
};
let JsonValue::Array(elems) =
build_qpdf_key(&mut pdf, meta).expect("build_qpdf_key failed")
else {
panic!("expected Array");
};
let JsonValue::Object(map_pairs) = &elems[1] else {
panic!("objects_map is not an Object");
};
let trailer = map_pairs
.iter()
.find(|(k, _)| k == "trailer")
.map(|(_, v)| v)
.expect("trailer not found");
let JsonValue::Object(trailer_pairs) = trailer else {
panic!("trailer is not an Object");
};
assert_eq!(trailer_pairs[0].0, "value", "trailer must have 'value' key");
let JsonValue::Object(trailer_dict) = &trailer_pairs[0].1 else {
panic!("trailer.value is not an Object");
};
let size = trailer_dict
.iter()
.find(|(k, _)| k == "/Size")
.map(|(_, v)| v)
.expect("/Size not found in trailer");
assert_eq!(*size, JsonValue::Integer(8), "/Size should be 8");
}
#[test]
fn build_qpdf_key_live_null_indirect_object_is_emitted_with_value_null() {
let mut pdf = load_one_page_pdf();
pdf.set_object(crate::ObjectRef::new(2, 0), Object::Null);
let meta = QpdfMetadata {
pdf_version: "1.3".to_string(),
max_object_id: 7,
pushed_inherited_page_resources: false,
called_get_all_pages: true,
};
let JsonValue::Array(elems) =
build_qpdf_key(&mut pdf, meta).expect("build_qpdf_key failed")
else {
panic!("expected Array");
};
let JsonValue::Object(map_pairs) = &elems[1] else {
panic!("objects_map is not an Object");
};
let obj2 = map_pairs
.iter()
.find(|(k, _)| k == "obj:2 0 R")
.map(|(_, v)| v)
.expect("obj:2 0 R must remain in objects_map when it is live and null");
let JsonValue::Object(obj2_pairs) = obj2 else {
panic!("obj:2 0 R is not an Object");
};
assert_eq!(
obj2_pairs.len(),
1,
"live null indirect must have a single 'value' key"
);
assert_eq!(obj2_pairs[0].0, "value");
assert_eq!(obj2_pairs[0].1, JsonValue::Null);
}
#[test]
fn pdf_object_to_json_name_with_non_utf8_byte_escapes_as_hex() {
let obj = Object::Name(b"A\xffB".to_vec());
let json = pdf_object_to_json(&obj).unwrap();
assert_eq!(json, JsonValue::String("/A#ffB".to_string()));
}
#[test]
fn pdf_object_to_json_name_with_delimiters_escapes_them() {
let obj = Object::Name(b"a b#(c)".to_vec());
let json = pdf_object_to_json(&obj).unwrap();
assert_eq!(
json,
JsonValue::String("/a#20b#23#28c#29".to_string()),
"space, #, (, ) must all be hex-escaped"
);
}
#[test]
fn pdf_object_to_json_name_with_only_safe_bytes_is_passthrough() {
let obj = Object::Name(b"Helvetica".to_vec());
let json = pdf_object_to_json(&obj).unwrap();
assert_eq!(json, JsonValue::String("/Helvetica".to_string()));
}
#[test]
fn dict_to_json_keys_with_non_utf8_bytes_use_hex_escape() {
let mut dict = Dictionary::new();
dict.insert(b"K\xffey", Object::Integer(7));
let json = pdf_object_to_json(&Object::Dictionary(dict)).unwrap();
let JsonValue::Object(pairs) = json else {
panic!("expected Object");
};
assert_eq!(pairs.len(), 1);
assert_eq!(pairs[0].0, "/K#ffey");
assert_eq!(pairs[0].1, JsonValue::Integer(7));
}
#[test]
fn pdf_object_to_json_name_with_control_byte_escapes() {
let obj = Object::Name(b"x\x01y".to_vec());
let json = pdf_object_to_json(&obj).unwrap();
assert_eq!(json, JsonValue::String("/x#01y".to_string()));
}
#[test]
fn live_object_refs_excludes_explicitly_deleted_entries() {
let mut pdf = load_one_page_pdf();
let before: std::collections::BTreeSet<_> = pdf.live_object_refs().into_iter().collect();
assert!(
before.contains(&crate::ObjectRef::new(2, 0)),
"obj 2 should start out as live"
);
pdf.delete_object(crate::ObjectRef::new(2, 0));
let after: std::collections::BTreeSet<_> = pdf.live_object_refs().into_iter().collect();
assert!(
!after.contains(&crate::ObjectRef::new(2, 0)),
"obj 2 must drop out of live_object_refs after delete_object"
);
assert_eq!(
before.len() - 1,
after.len(),
"exactly one ref should be removed"
);
}
fn load_fixture_pdf(name: &str) -> crate::Pdf<std::io::Cursor<Vec<u8>>> {
let manifest = std::path::Path::new(env!("CARGO_MANIFEST_DIR"));
let fixture = manifest.join("../../tests/fixtures/compat").join(name);
let bytes = std::fs::read(&fixture)
.unwrap_or_else(|e| panic!("{name} not found at {}: {e}", fixture.display()));
crate::Pdf::open_mem_owned(bytes).unwrap_or_else(|e| panic!("failed to open {name}: {e}"))
}
fn get_page_entry(pages: &JsonValue, idx: usize) -> &[(String, JsonValue)] {
let JsonValue::Array(arr) = pages else {
panic!("pages section is not an Array");
};
let JsonValue::Object(pairs) = &arr[idx] else {
panic!("page entry {idx} is not an Object");
};
pairs.as_slice()
}
#[test]
fn build_pages_section_one_page_length() {
let mut pdf = load_fixture_pdf("one-page.pdf");
let pages = build_pages_section(&mut pdf).expect("build_pages_section failed");
let JsonValue::Array(arr) = &pages else {
panic!("expected Array");
};
assert_eq!(arr.len(), 1, "one-page.pdf must have exactly 1 page entry");
}
#[test]
fn build_pages_section_one_page_key_order() {
let mut pdf = load_fixture_pdf("one-page.pdf");
let pages = build_pages_section(&mut pdf).expect("build_pages_section failed");
let pairs = get_page_entry(&pages, 0);
let keys: Vec<&str> = pairs.iter().map(|(k, _)| k.as_str()).collect();
assert_eq!(
keys,
vec![
"contents",
"images",
"label",
"object",
"outlines",
"pageposfrom1"
],
"key order must be strictly alphabetical"
);
}
#[test]
fn build_pages_section_one_page_values() {
let mut pdf = load_fixture_pdf("one-page.pdf");
let pages = build_pages_section(&mut pdf).expect("build_pages_section failed");
let pairs = get_page_entry(&pages, 0);
assert_eq!(
pairs[0].1,
JsonValue::Array(vec![JsonValue::String("7 0 R".to_string())]),
"contents mismatch"
);
assert_eq!(pairs[1].1, JsonValue::Array(vec![]), "images must be empty");
assert_eq!(pairs[2].1, JsonValue::Null, "label must be null");
assert_eq!(
pairs[3].1,
JsonValue::String("3 0 R".to_string()),
"object mismatch"
);
assert_eq!(
pairs[4].1,
JsonValue::Array(vec![]),
"outlines must be empty"
);
assert_eq!(pairs[5].1, JsonValue::Integer(1), "pageposfrom1 must be 1");
}
#[test]
fn build_pages_section_three_page_length_and_positions() {
let mut pdf = load_fixture_pdf("three-page.pdf");
let pages = build_pages_section(&mut pdf).expect("build_pages_section failed");
let JsonValue::Array(arr) = &pages else {
panic!("expected Array");
};
assert_eq!(arr.len(), 3, "three-page.pdf must have 3 page entries");
let expected = [
("3 0 R", "9 0 R", 1i64),
("4 0 R", "10 0 R", 2),
("5 0 R", "11 0 R", 3),
];
for (i, (exp_obj, exp_contents, exp_pos)) in expected.iter().enumerate() {
let pairs = get_page_entry(&pages, i);
assert_eq!(
pairs[0].1,
JsonValue::Array(vec![JsonValue::String(exp_contents.to_string())]),
"page {i} contents mismatch"
);
assert_eq!(
pairs[3].1,
JsonValue::String(exp_obj.to_string()),
"page {i} object mismatch"
);
assert_eq!(
pairs[5].1,
JsonValue::Integer(*exp_pos),
"page {i} pageposfrom1 mismatch"
);
assert_eq!(pairs[2].1, JsonValue::Null, "page {i} label must be null");
assert_eq!(
pairs[4].1,
JsonValue::Array(vec![]),
"page {i} outlines must be empty"
);
}
}
#[test]
fn build_pages_section_attachment_two_page_values() {
let mut pdf = load_fixture_pdf("attachment-two-page.pdf");
let pages = build_pages_section(&mut pdf).expect("build_pages_section failed");
let JsonValue::Array(arr) = &pages else {
panic!("expected Array");
};
assert_eq!(
arr.len(),
2,
"attachment-two-page.pdf must have 2 page entries"
);
let expected = [("6 0 R", "9 0 R", 1i64), ("7 0 R", "11 0 R", 2)];
for (i, (exp_obj, exp_contents, exp_pos)) in expected.iter().enumerate() {
let pairs = get_page_entry(&pages, i);
assert_eq!(
pairs[0].1,
JsonValue::Array(vec![JsonValue::String(exp_contents.to_string())]),
"page {i} contents mismatch"
);
assert_eq!(
pairs[3].1,
JsonValue::String(exp_obj.to_string()),
"page {i} object mismatch"
);
assert_eq!(
pairs[5].1,
JsonValue::Integer(*exp_pos),
"page {i} pageposfrom1 mismatch"
);
}
}
#[test]
fn collect_content_refs_single_ref_to_stream() {
let mut pdf = load_one_page_pdf();
let obj = Object::Reference(crate::ObjectRef::new(7, 0));
let refs = collect_content_refs(&mut pdf, &obj).expect("collect_content_refs failed");
assert_eq!(refs, vec!["7 0 R".to_string()]);
}
#[test]
fn collect_content_refs_array_of_refs() {
let mut pdf = load_one_page_pdf();
let obj = Object::Array(vec![
Object::Reference(crate::ObjectRef::new(4, 0)),
Object::Reference(crate::ObjectRef::new(5, 0)),
]);
let refs = collect_content_refs(&mut pdf, &obj).expect("collect_content_refs failed");
assert_eq!(refs, vec!["4 0 R".to_string(), "5 0 R".to_string()]);
}
#[test]
fn collect_content_refs_null_returns_empty() {
let mut pdf = load_one_page_pdf();
let obj = Object::Null;
let refs = collect_content_refs(&mut pdf, &obj).expect("collect_content_refs failed");
assert!(refs.is_empty());
}
#[test]
fn collect_content_refs_array_skips_non_refs() {
let mut pdf = load_one_page_pdf();
let obj = Object::Array(vec![
Object::Reference(crate::ObjectRef::new(3, 0)),
Object::Integer(99), Object::Reference(crate::ObjectRef::new(5, 0)),
]);
let refs = collect_content_refs(&mut pdf, &obj).expect("collect_content_refs failed");
assert_eq!(refs, vec!["3 0 R".to_string(), "5 0 R".to_string()]);
}
#[test]
fn collect_content_refs_indirect_array_is_flattened() {
let mut pdf = load_one_page_pdf();
pdf.set_object(
crate::ObjectRef::new(2, 0),
Object::Array(vec![
Object::Reference(crate::ObjectRef::new(4, 0)),
Object::Reference(crate::ObjectRef::new(5, 0)),
]),
);
let obj = Object::Reference(crate::ObjectRef::new(2, 0));
let refs = collect_content_refs(&mut pdf, &obj).expect("collect_content_refs failed");
assert_eq!(
refs,
vec!["4 0 R".to_string(), "5 0 R".to_string()],
"indirect Array of refs must be unwrapped, not emitted as the array's ref number"
);
}
fn patch_pagelabels(pdf: &mut crate::Pdf<std::io::Cursor<Vec<u8>>>, pagelabels: Object) {
let catalog_ref = pdf.root_ref().expect("no /Root");
let mut catalog = match pdf.resolve(catalog_ref).expect("resolve catalog") {
Object::Dictionary(d) => d,
_ => panic!("catalog is not a Dictionary"),
};
catalog.insert("PageLabels", pagelabels);
pdf.set_object(catalog_ref, Object::Dictionary(catalog));
}
#[test]
fn pagelabels_missing_returns_empty_array() {
let mut pdf = load_one_page_pdf();
let result = build_pagelabels_section(&mut pdf).expect("build_pagelabels_section failed");
assert_eq!(
result,
JsonValue::Array(vec![]),
"missing /PageLabels must yield empty array"
);
}
#[test]
fn pagelabels_single_range_decimal() {
let mut pdf = load_one_page_pdf();
let mut label = Dictionary::new();
label.insert("S", Object::Name(b"D".to_vec()));
label.insert("St", Object::Integer(1));
let pagelabels = Object::Dictionary({
let mut d = Dictionary::new();
d.insert(
"Nums",
Object::Array(vec![Object::Integer(0), Object::Dictionary(label)]),
);
d
});
patch_pagelabels(&mut pdf, pagelabels);
let result = build_pagelabels_section(&mut pdf).expect("build_pagelabels_section failed");
let JsonValue::Array(arr) = &result else {
panic!("expected Array, got {result:?}");
};
assert_eq!(arr.len(), 1, "expected 1 entry");
let JsonValue::Object(entry) = &arr[0] else {
panic!("entry is not an Object");
};
assert_eq!(entry[0].0, "index");
assert_eq!(entry[0].1, JsonValue::Integer(0));
assert_eq!(entry[1].0, "label");
let JsonValue::Object(label_pairs) = &entry[1].1 else {
panic!("label is not an Object");
};
assert_eq!(label_pairs[0], ("first".to_string(), JsonValue::Integer(1)));
assert_eq!(
label_pairs[1],
("prefix".to_string(), JsonValue::String(String::new()))
);
assert_eq!(
label_pairs[2],
("style".to_string(), JsonValue::String("D".to_string()))
);
}
#[test]
fn pagelabels_multiple_ranges() {
let mut pdf = load_one_page_pdf();
let mut label0 = Dictionary::new();
label0.insert("S", Object::Name(b"D".to_vec()));
let mut label5 = Dictionary::new();
label5.insert("S", Object::Name(b"R".to_vec()));
label5.insert("P", Object::String(b"Appx".to_vec()));
label5.insert("St", Object::Integer(1));
let mut label10 = Dictionary::new();
label10.insert("S", Object::Name(b"a".to_vec()));
let pagelabels = Object::Dictionary({
let mut d = Dictionary::new();
d.insert(
"Nums",
Object::Array(vec![
Object::Integer(0),
Object::Dictionary(label0),
Object::Integer(5),
Object::Dictionary(label5),
Object::Integer(10),
Object::Dictionary(label10),
]),
);
d
});
patch_pagelabels(&mut pdf, pagelabels);
let result = build_pagelabels_section(&mut pdf).expect("build_pagelabels_section failed");
let JsonValue::Array(arr) = &result else {
panic!("expected Array");
};
assert_eq!(arr.len(), 3, "expected 3 entries");
let get_index = |i: usize| {
let JsonValue::Object(e) = &arr[i] else {
panic!()
};
match &e[0].1 {
JsonValue::Integer(n) => *n,
_ => panic!(),
}
};
assert_eq!(get_index(0), 0);
assert_eq!(get_index(1), 5);
assert_eq!(get_index(2), 10);
let get_style = |i: usize| {
let JsonValue::Object(e) = &arr[i] else {
panic!()
};
let JsonValue::Object(lp) = &e[1].1 else {
panic!()
};
lp[2].1.clone()
};
assert_eq!(get_style(0), JsonValue::String("D".to_string()));
assert_eq!(get_style(1), JsonValue::String("R".to_string()));
assert_eq!(get_style(2), JsonValue::String("a".to_string()));
let JsonValue::Object(e1) = &arr[1] else {
panic!()
};
let JsonValue::Object(lp1) = &e1[1].1 else {
panic!()
};
assert_eq!(lp1[1].1, JsonValue::String("Appx".to_string()));
}
#[test]
fn pagelabels_no_style_gives_null() {
let mut pdf = load_one_page_pdf();
let mut label = Dictionary::new();
label.insert("P", Object::String(b"App".to_vec()));
let pagelabels = Object::Dictionary({
let mut d = Dictionary::new();
d.insert(
"Nums",
Object::Array(vec![Object::Integer(0), Object::Dictionary(label)]),
);
d
});
patch_pagelabels(&mut pdf, pagelabels);
let result = build_pagelabels_section(&mut pdf).expect("build_pagelabels_section failed");
let JsonValue::Array(arr) = &result else {
panic!("expected Array");
};
assert_eq!(arr.len(), 1);
let JsonValue::Object(entry) = &arr[0] else {
panic!()
};
let JsonValue::Object(label_pairs) = &entry[1].1 else {
panic!()
};
assert_eq!(label_pairs[2].0, "style");
assert_eq!(
label_pairs[2].1,
JsonValue::Null,
"style must be null when /S is absent"
);
}
#[test]
fn pagelabels_kids_subtree_walk() {
let mut pdf = load_one_page_pdf();
let mut label = Dictionary::new();
label.insert("S", Object::Name(b"r".to_vec()));
let mut subtree = Dictionary::new();
subtree.insert(
"Nums",
Object::Array(vec![Object::Integer(0), Object::Dictionary(label)]),
);
let subtree_ref = crate::ObjectRef::new(99, 0);
pdf.set_object(subtree_ref, Object::Dictionary(subtree));
let pagelabels = Object::Dictionary({
let mut d = Dictionary::new();
d.insert("Kids", Object::Array(vec![Object::Reference(subtree_ref)]));
d
});
patch_pagelabels(&mut pdf, pagelabels);
let result = build_pagelabels_section(&mut pdf).expect("build_pagelabels_section failed");
let JsonValue::Array(arr) = &result else {
panic!("expected Array");
};
assert_eq!(arr.len(), 1, "expected 1 entry from /Kids walk");
let JsonValue::Object(entry) = &arr[0] else {
panic!()
};
assert_eq!(entry[0].1, JsonValue::Integer(0));
let JsonValue::Object(lp) = &entry[1].1 else {
panic!()
};
assert_eq!(lp[2].1, JsonValue::String("r".to_string()));
}
#[test]
fn pagelabels_compat_fixtures_all_empty() {
let fixtures = ["one-page.pdf", "three-page.pdf", "attachment-two-page.pdf"];
for name in fixtures {
let mut pdf = load_fixture_pdf(name);
let result = build_pagelabels_section(&mut pdf)
.unwrap_or_else(|e| panic!("{name}: build_pagelabels_section failed: {e:?}"));
assert_eq!(
result,
JsonValue::Array(vec![]),
"{name}: expected empty pagelabels array"
);
}
}
#[test]
fn build_qpdf_json_v2_has_expected_top_level_keys_in_order() {
let mut pdf = load_one_page_pdf();
let v2 = build_qpdf_json_v2(&mut pdf, DecodeLevel::Generalized)
.expect("build_qpdf_json_v2 failed");
let JsonValue::Object(pairs) = v2 else {
panic!("expected Object at top level");
};
let keys: Vec<&str> = pairs.iter().map(|(k, _)| k.as_str()).collect();
assert_eq!(
keys,
vec![
"version",
"parameters",
"pages",
"pagelabels",
"acroform",
"attachments",
"encrypt",
"outlines",
"qpdf"
]
);
}
#[test]
fn build_qpdf_json_v2_includes_pagelabels_section() {
let mut pdf = load_one_page_pdf();
let v2 = build_qpdf_json_v2(&mut pdf, DecodeLevel::Generalized)
.expect("build_qpdf_json_v2 failed");
let JsonValue::Object(pairs) = v2 else {
panic!("expected Object at top level");
};
let pagelabels = pairs
.iter()
.find(|(k, _)| k == "pagelabels")
.map(|(_, v)| v)
.expect("pagelabels key must be present in the composite output");
assert!(
matches!(pagelabels, JsonValue::Array(_)),
"pagelabels must be an Array"
);
}
#[test]
fn build_qpdf_json_v2_pages_count_matches_fixture() {
let mut pdf = load_three_page_pdf();
let v2 = build_qpdf_json_v2(&mut pdf, DecodeLevel::Generalized)
.expect("build_qpdf_json_v2 failed");
let JsonValue::Object(pairs) = v2 else {
panic!("expected Object at top level");
};
let pages = pairs
.iter()
.find(|(k, _)| k == "pages")
.map(|(_, v)| v)
.expect("pages key missing");
let JsonValue::Array(page_entries) = pages else {
panic!("pages must be Array");
};
assert_eq!(
page_entries.len(),
3,
"three-page.pdf must produce 3 page entries"
);
}
#[test]
fn build_qpdf_json_v2_qpdf_metadata_uses_actual_pdf_version() {
let mut pdf = load_one_page_pdf();
let v2 = build_qpdf_json_v2(&mut pdf, DecodeLevel::Generalized)
.expect("build_qpdf_json_v2 failed");
let JsonValue::Object(pairs) = v2 else {
panic!("expected Object");
};
let qpdf = pairs.iter().find(|(k, _)| k == "qpdf").unwrap().1.clone();
let JsonValue::Array(qpdf_arr) = qpdf else {
panic!("qpdf must be Array");
};
let JsonValue::Object(meta_pairs) = &qpdf_arr[0] else {
panic!("qpdf[0] must be Object");
};
let pdf_version = meta_pairs
.iter()
.find(|(k, _)| k == "pdfversion")
.map(|(_, v)| v)
.expect("pdfversion missing");
assert_eq!(*pdf_version, JsonValue::String("1.3".to_string()));
}
fn patch_outline_root(
pdf: &mut crate::Pdf<std::io::Cursor<Vec<u8>>>,
outline_root_ref: crate::ObjectRef,
outline_root: Dictionary,
) {
let catalog_ref = pdf.root_ref().expect("no /Root");
let mut catalog = match pdf.resolve(catalog_ref).expect("resolve catalog") {
Object::Dictionary(d) => d,
_ => panic!("catalog is not a Dictionary"),
};
catalog.insert("Outlines", Object::Reference(outline_root_ref));
pdf.set_object(catalog_ref, Object::Dictionary(catalog));
pdf.set_object(outline_root_ref, Object::Dictionary(outline_root));
}
#[test]
fn outlines_missing_returns_empty_array() {
let mut pdf = load_one_page_pdf();
let result = build_outlines_section(&mut pdf).expect("build_outlines_section failed");
assert_eq!(
result,
JsonValue::Array(vec![]),
"missing /Outlines must yield empty array"
);
}
#[test]
fn outlines_compat_fixtures_all_empty() {
let fixtures = ["one-page.pdf", "three-page.pdf", "attachment-two-page.pdf"];
for name in fixtures {
let mut pdf = load_fixture_pdf(name);
let result = build_outlines_section(&mut pdf)
.unwrap_or_else(|e| panic!("{name}: build_outlines_section failed: {e:?}"));
assert_eq!(
result,
JsonValue::Array(vec![]),
"{name}: expected empty outlines array"
);
}
}
#[test]
fn outlines_single_entry() {
let mut pdf = load_one_page_pdf();
let outline_root_ref = crate::ObjectRef::new(100, 0);
let item_ref = crate::ObjectRef::new(101, 0);
let mut outline_root = Dictionary::new();
outline_root.insert("Type", Object::Name(b"Outlines".to_vec()));
outline_root.insert("First", Object::Reference(item_ref));
outline_root.insert("Last", Object::Reference(item_ref));
outline_root.insert("Count", Object::Integer(1));
patch_outline_root(&mut pdf, outline_root_ref, outline_root);
let mut item = Dictionary::new();
item.insert("Title", Object::String(b"Chapter 1".to_vec()));
item.insert("Parent", Object::Reference(outline_root_ref));
pdf.set_object(item_ref, Object::Dictionary(item));
let result = build_outlines_section(&mut pdf).expect("build_outlines_section failed");
let JsonValue::Array(entries) = &result else {
panic!("expected Array, got {result:?}");
};
assert_eq!(entries.len(), 1, "expected 1 outline entry");
let JsonValue::Object(entry) = &entries[0] else {
panic!("entry is not an Object");
};
let keys: Vec<&str> = entry.iter().map(|(k, _)| k.as_str()).collect();
assert_eq!(
keys,
vec![
"action",
"count",
"dest",
"flags",
"kids",
"object",
"structureelement",
"title"
],
"key order must be alphabetical"
);
assert_eq!(entry[0].1, JsonValue::Null, "action must be Null");
assert_eq!(entry[1].1, JsonValue::Null, "count must be Null");
assert_eq!(entry[2].1, JsonValue::Null, "dest must be Null");
assert_eq!(entry[3].1, JsonValue::Null, "flags must be Null");
assert_eq!(entry[4].1, JsonValue::Array(vec![]), "kids must be empty");
assert_eq!(
entry[5].1,
JsonValue::String("101 0 R".to_string()),
"object mismatch"
);
assert_eq!(entry[6].1, JsonValue::Null, "structureelement must be Null");
assert_eq!(
entry[7].1,
JsonValue::String("Chapter 1".to_string()),
"title must be bare string without u: prefix"
);
}
#[test]
fn outlines_hierarchical_tree() {
let mut pdf = load_one_page_pdf();
let outline_root_ref = crate::ObjectRef::new(100, 0);
let parent_ref = crate::ObjectRef::new(101, 0);
let child1_ref = crate::ObjectRef::new(102, 0);
let child2_ref = crate::ObjectRef::new(103, 0);
let mut outline_root = Dictionary::new();
outline_root.insert("Type", Object::Name(b"Outlines".to_vec()));
outline_root.insert("First", Object::Reference(parent_ref));
outline_root.insert("Last", Object::Reference(parent_ref));
outline_root.insert("Count", Object::Integer(3)); patch_outline_root(&mut pdf, outline_root_ref, outline_root);
let mut parent = Dictionary::new();
parent.insert("Title", Object::String(b"Part 1".to_vec()));
parent.insert("Parent", Object::Reference(outline_root_ref));
parent.insert("First", Object::Reference(child1_ref));
parent.insert("Last", Object::Reference(child2_ref));
parent.insert("Count", Object::Integer(2));
pdf.set_object(parent_ref, Object::Dictionary(parent));
let mut child1 = Dictionary::new();
child1.insert("Title", Object::String(b"Chapter 1".to_vec()));
child1.insert("Parent", Object::Reference(parent_ref));
child1.insert("Next", Object::Reference(child2_ref));
pdf.set_object(child1_ref, Object::Dictionary(child1));
let mut child2 = Dictionary::new();
child2.insert("Title", Object::String(b"Chapter 2".to_vec()));
child2.insert("Parent", Object::Reference(parent_ref));
child2.insert("Prev", Object::Reference(child1_ref));
pdf.set_object(child2_ref, Object::Dictionary(child2));
let result = build_outlines_section(&mut pdf).expect("build_outlines_section failed");
let JsonValue::Array(root_entries) = &result else {
panic!("expected Array");
};
assert_eq!(root_entries.len(), 1, "root chain has 1 entry (parent)");
let JsonValue::Object(parent_entry) = &root_entries[0] else {
panic!("parent entry is not an Object");
};
let kids_val = &parent_entry.iter().find(|(k, _)| k == "kids").unwrap().1;
let JsonValue::Array(kids) = kids_val else {
panic!("kids is not an Array");
};
assert_eq!(kids.len(), 2, "parent must have 2 children in kids");
let get_title = |entry: &JsonValue| {
let JsonValue::Object(pairs) = entry else {
panic!("kid entry is not an Object");
};
pairs.iter().find(|(k, _)| k == "title").unwrap().1.clone()
};
assert_eq!(
get_title(&kids[0]),
JsonValue::String("Chapter 1".to_string())
);
assert_eq!(
get_title(&kids[1]),
JsonValue::String("Chapter 2".to_string())
);
}
#[test]
fn outlines_cycle_guard_prevents_infinite_loop() {
let mut pdf = load_one_page_pdf();
let outline_root_ref = crate::ObjectRef::new(100, 0);
let item_ref = crate::ObjectRef::new(101, 0);
let mut outline_root = Dictionary::new();
outline_root.insert("Type", Object::Name(b"Outlines".to_vec()));
outline_root.insert("First", Object::Reference(item_ref));
outline_root.insert("Last", Object::Reference(item_ref));
patch_outline_root(&mut pdf, outline_root_ref, outline_root);
let mut item = Dictionary::new();
item.insert("Title", Object::String(b"Loop".to_vec()));
item.insert("Parent", Object::Reference(outline_root_ref));
item.insert("Next", Object::Reference(item_ref)); pdf.set_object(item_ref, Object::Dictionary(item));
let result = build_outlines_section(&mut pdf).expect("build_outlines_section failed");
let JsonValue::Array(entries) = &result else {
panic!("expected Array");
};
assert_eq!(
entries.len(),
1,
"cycle guard must stop after 1 entry, got {}",
entries.len()
);
}
#[test]
fn outlines_broken_parent_link_does_not_crash() {
let mut pdf = load_one_page_pdf();
let outline_root_ref = crate::ObjectRef::new(100, 0);
let item_ref = crate::ObjectRef::new(101, 0);
let mut outline_root = Dictionary::new();
outline_root.insert("Type", Object::Name(b"Outlines".to_vec()));
outline_root.insert("First", Object::Reference(item_ref));
outline_root.insert("Last", Object::Reference(item_ref));
patch_outline_root(&mut pdf, outline_root_ref, outline_root);
let mut item = Dictionary::new();
item.insert("Title", Object::String(b"Broken Parent".to_vec()));
item.insert("Parent", Object::Reference(crate::ObjectRef::new(999, 0))); pdf.set_object(item_ref, Object::Dictionary(item));
let result = build_outlines_section(&mut pdf).expect("build_outlines_section failed");
let JsonValue::Array(entries) = &result else {
panic!("expected Array");
};
assert_eq!(entries.len(), 1, "expected 1 entry despite broken /Parent");
let JsonValue::Object(entry) = &entries[0] else {
panic!("entry is not an Object");
};
let title = entry.iter().find(|(k, _)| k == "title").unwrap().1.clone();
assert_eq!(title, JsonValue::String("Broken Parent".to_string()));
}
#[test]
fn build_qpdf_json_v2_includes_outlines_section() {
let mut pdf = load_one_page_pdf();
let v2 = build_qpdf_json_v2(&mut pdf, DecodeLevel::Generalized)
.expect("build_qpdf_json_v2 failed");
let JsonValue::Object(pairs) = v2 else {
panic!("expected Object at top level");
};
let outlines = pairs
.iter()
.find(|(k, _)| k == "outlines")
.map(|(_, v)| v)
.expect("outlines key must be present in composite output");
assert!(
matches!(outlines, JsonValue::Array(_)),
"outlines must be an Array"
);
assert_eq!(
*outlines,
JsonValue::Array(vec![]),
"one-page.pdf has no outlines"
);
}
#[test]
fn outlines_utf16be_title_decoded_as_bare_string() {
let mut pdf = load_one_page_pdf();
let outline_root_ref = crate::ObjectRef::new(100, 0);
let item_ref = crate::ObjectRef::new(101, 0);
let mut outline_root = Dictionary::new();
outline_root.insert("Type", Object::Name(b"Outlines".to_vec()));
outline_root.insert("First", Object::Reference(item_ref));
outline_root.insert("Last", Object::Reference(item_ref));
patch_outline_root(&mut pdf, outline_root_ref, outline_root);
let title_bytes = vec![0xFE, 0xFF, 0x00, 0x41, 0x00, 0x42];
let mut item = Dictionary::new();
item.insert("Title", Object::String(title_bytes));
item.insert("Parent", Object::Reference(outline_root_ref));
pdf.set_object(item_ref, Object::Dictionary(item));
let result = build_outlines_section(&mut pdf).expect("build_outlines_section failed");
let JsonValue::Array(entries) = &result else {
panic!("expected Array");
};
let JsonValue::Object(entry) = &entries[0] else {
panic!("entry is not an Object");
};
let title = entry.iter().find(|(k, _)| k == "title").unwrap().1.clone();
assert_eq!(title, JsonValue::String("AB".to_string()));
}
#[test]
fn outlines_direct_action_dictionary_is_preserved() {
let mut pdf = load_one_page_pdf();
let outline_root_ref = crate::ObjectRef::new(100, 0);
let item_ref = crate::ObjectRef::new(101, 0);
let mut outline_root = Dictionary::new();
outline_root.insert("Type", Object::Name(b"Outlines".to_vec()));
outline_root.insert("First", Object::Reference(item_ref));
outline_root.insert("Last", Object::Reference(item_ref));
patch_outline_root(&mut pdf, outline_root_ref, outline_root);
let mut action = Dictionary::new();
action.insert("S", Object::Name(b"URI".to_vec()));
action.insert("URI", Object::String(b"https://example.com".to_vec()));
let mut item = Dictionary::new();
item.insert("Title", Object::String(b"Visit example".to_vec()));
item.insert("Parent", Object::Reference(outline_root_ref));
item.insert("A", Object::Dictionary(action));
pdf.set_object(item_ref, Object::Dictionary(item));
let result = build_outlines_section(&mut pdf).expect("build_outlines_section failed");
let JsonValue::Array(entries) = &result else {
panic!("expected Array");
};
let JsonValue::Object(entry) = &entries[0] else {
panic!("entry is not an Object");
};
let action_value = entry
.iter()
.find(|(k, _)| k == "action")
.map(|(_, v)| v)
.expect("action key missing");
let JsonValue::Object(action_pairs) = action_value else {
panic!(
"expected the direct /A dictionary to be preserved as an Object, got {:?}",
action_value
);
};
let s_value = action_pairs
.iter()
.find(|(k, _)| k == "/S")
.map(|(_, v)| v)
.expect("/S key missing");
assert_eq!(s_value, &JsonValue::String("/URI".to_string()));
let uri_value = action_pairs
.iter()
.find(|(k, _)| k == "/URI")
.map(|(_, v)| v)
.expect("/URI key missing");
assert_eq!(
uri_value,
&JsonValue::String("u:https://example.com".to_string())
);
}
#[test]
fn outlines_indirect_action_reference_still_emits_ref_string() {
let mut pdf = load_one_page_pdf();
let outline_root_ref = crate::ObjectRef::new(100, 0);
let item_ref = crate::ObjectRef::new(101, 0);
let action_ref = crate::ObjectRef::new(102, 0);
let mut outline_root = Dictionary::new();
outline_root.insert("Type", Object::Name(b"Outlines".to_vec()));
outline_root.insert("First", Object::Reference(item_ref));
outline_root.insert("Last", Object::Reference(item_ref));
patch_outline_root(&mut pdf, outline_root_ref, outline_root);
let mut action = Dictionary::new();
action.insert("S", Object::Name(b"GoTo".to_vec()));
pdf.set_object(action_ref, Object::Dictionary(action));
let mut item = Dictionary::new();
item.insert("Title", Object::String(b"Go".to_vec()));
item.insert("Parent", Object::Reference(outline_root_ref));
item.insert("A", Object::Reference(action_ref));
pdf.set_object(item_ref, Object::Dictionary(item));
let result = build_outlines_section(&mut pdf).expect("build_outlines_section failed");
let JsonValue::Array(entries) = result else {
panic!("expected Array");
};
let JsonValue::Object(entry) = &entries[0] else {
panic!("entry is not an Object");
};
let action_value = entry
.iter()
.find(|(k, _)| k == "action")
.map(|(_, v)| v.clone())
.unwrap();
assert_eq!(action_value, JsonValue::String("102 0 R".to_string()));
}
fn patch_acroform(
pdf: &mut crate::Pdf<std::io::Cursor<Vec<u8>>>,
acroform_ref: crate::ObjectRef,
acroform: Dictionary,
) {
let catalog_ref = pdf.root_ref().expect("no /Root");
let mut catalog = match pdf.resolve(catalog_ref).expect("resolve catalog") {
Object::Dictionary(d) => d,
_ => panic!("catalog is not a Dictionary"),
};
catalog.insert("AcroForm", Object::Reference(acroform_ref));
pdf.set_object(catalog_ref, Object::Dictionary(catalog));
pdf.set_object(acroform_ref, Object::Dictionary(acroform));
}
#[test]
fn acroform_missing_returns_empty() {
let mut pdf = load_one_page_pdf();
let result = build_acroform_section(&mut pdf).expect("build_acroform_section failed");
let JsonValue::Object(pairs) = &result else {
panic!("expected Object, got {result:?}");
};
let keys: Vec<&str> = pairs.iter().map(|(k, _)| k.as_str()).collect();
assert_eq!(keys, vec!["fields", "hasacroform", "needappearances"]);
assert_eq!(pairs[0].1, JsonValue::Array(vec![]), "fields must be empty");
assert_eq!(
pairs[1].1,
JsonValue::Bool(false),
"hasacroform must be false"
);
assert_eq!(
pairs[2].1,
JsonValue::Bool(false),
"needappearances must be false"
);
}
#[test]
fn acroform_present_empty_fields() {
let mut pdf = load_one_page_pdf();
let acroform_ref = crate::ObjectRef::new(200, 0);
let mut acroform = Dictionary::new();
acroform.insert("Fields", Object::Array(vec![]));
patch_acroform(&mut pdf, acroform_ref, acroform);
let result = build_acroform_section(&mut pdf).expect("build_acroform_section failed");
let JsonValue::Object(pairs) = &result else {
panic!("expected Object");
};
assert_eq!(pairs[0].1, JsonValue::Array(vec![]), "fields must be empty");
assert_eq!(
pairs[1].1,
JsonValue::Bool(true),
"hasacroform must be true"
);
assert_eq!(
pairs[2].1,
JsonValue::Bool(false),
"needappearances must be false"
);
}
#[test]
fn acroform_single_leaf_field() {
let mut pdf = load_one_page_pdf();
let acroform_ref = crate::ObjectRef::new(200, 0);
let field_ref = crate::ObjectRef::new(201, 0);
let mut acroform = Dictionary::new();
acroform.insert("Fields", Object::Array(vec![Object::Reference(field_ref)]));
acroform.insert("NeedAppearances", Object::Boolean(true));
patch_acroform(&mut pdf, acroform_ref, acroform);
let mut field = Dictionary::new();
field.insert("T", Object::String(b"firstname".to_vec()));
field.insert("FT", Object::Name(b"Tx".to_vec()));
field.insert("V", Object::String(b"John".to_vec()));
field.insert("Ff", Object::Integer(0));
pdf.set_object(field_ref, Object::Dictionary(field));
let result = build_acroform_section(&mut pdf).expect("build_acroform_section failed");
let JsonValue::Object(top) = &result else {
panic!("expected Object");
};
assert_eq!(top[1].1, JsonValue::Bool(true), "hasacroform must be true");
assert_eq!(
top[2].1,
JsonValue::Bool(true),
"needappearances must be true"
);
let JsonValue::Array(fields) = &top[0].1 else {
panic!("fields must be Array");
};
assert_eq!(fields.len(), 1, "expected 1 field entry");
let JsonValue::Object(entry) = &fields[0] else {
panic!("field entry must be Object");
};
let keys: Vec<&str> = entry.iter().map(|(k, _)| k.as_str()).collect();
assert_eq!(
keys,
vec![
"alternatename",
"annotations",
"defaultvalue",
"fieldflags",
"fieldtype",
"fullname",
"mappingname",
"object",
"parent",
"value"
],
"key order must be alphabetical"
);
assert_eq!(entry[0].1, JsonValue::Null, "alternatename must be null");
assert_eq!(
entry[1].1,
JsonValue::Array(vec![]),
"annotations must be empty (no widget)"
);
assert_eq!(entry[2].1, JsonValue::Null, "defaultvalue must be null");
assert_eq!(entry[3].1, JsonValue::Integer(0), "fieldflags must be 0");
assert_eq!(
entry[4].1,
JsonValue::String("Tx".to_string()),
"fieldtype must be Tx (bare, no /)"
);
assert_eq!(
entry[5].1,
JsonValue::String("firstname".to_string()),
"fullname must match /T"
);
assert_eq!(entry[6].1, JsonValue::Null, "mappingname must be null");
assert_eq!(
entry[7].1,
JsonValue::String("201 0 R".to_string()),
"object must be ref string"
);
assert_eq!(entry[8].1, JsonValue::Null, "parent must be null at root");
assert_eq!(
entry[9].1,
JsonValue::String("u:John".to_string()),
"value must be u:John"
);
}
#[test]
fn acroform_parent_child_fullname() {
let mut pdf = load_one_page_pdf();
let acroform_ref = crate::ObjectRef::new(200, 0);
let parent_field_ref = crate::ObjectRef::new(201, 0);
let child_field_ref = crate::ObjectRef::new(202, 0);
let mut acroform = Dictionary::new();
acroform.insert(
"Fields",
Object::Array(vec![Object::Reference(parent_field_ref)]),
);
patch_acroform(&mut pdf, acroform_ref, acroform);
let mut parent_field = Dictionary::new();
parent_field.insert("T", Object::String(b"person".to_vec()));
parent_field.insert("FT", Object::Name(b"Tx".to_vec()));
parent_field.insert(
"Kids",
Object::Array(vec![Object::Reference(child_field_ref)]),
);
pdf.set_object(parent_field_ref, Object::Dictionary(parent_field));
let mut child_field = Dictionary::new();
child_field.insert("T", Object::String(b"name".to_vec()));
child_field.insert("FT", Object::Name(b"Tx".to_vec()));
child_field.insert("Parent", Object::Reference(parent_field_ref));
pdf.set_object(child_field_ref, Object::Dictionary(child_field));
let result = build_acroform_section(&mut pdf).expect("build_acroform_section failed");
let JsonValue::Object(top) = &result else {
panic!("expected Object");
};
let JsonValue::Array(fields) = &top[0].1 else {
panic!("fields must be Array");
};
assert_eq!(fields.len(), 2, "expected 2 entries (parent + child)");
let JsonValue::Object(parent_entry) = &fields[0] else {
panic!("first entry must be Object");
};
let parent_fullname = parent_entry
.iter()
.find(|(k, _)| k == "fullname")
.map(|(_, v)| v)
.expect("fullname missing");
assert_eq!(
*parent_fullname,
JsonValue::String("person".to_string()),
"parent fullname must be 'person'"
);
let parent_obj = parent_entry
.iter()
.find(|(k, _)| k == "object")
.map(|(_, v)| v)
.expect("object missing");
assert_eq!(*parent_obj, JsonValue::String("201 0 R".to_string()));
let JsonValue::Object(child_entry) = &fields[1] else {
panic!("second entry must be Object");
};
let child_fullname = child_entry
.iter()
.find(|(k, _)| k == "fullname")
.map(|(_, v)| v)
.expect("fullname missing");
assert_eq!(
*child_fullname,
JsonValue::String("person.name".to_string()),
"child fullname must be 'person.name'"
);
let child_parent = child_entry
.iter()
.find(|(k, _)| k == "parent")
.map(|(_, v)| v)
.expect("parent missing");
assert_eq!(
*child_parent,
JsonValue::String("201 0 R".to_string()),
"child parent must point to 201 0 R"
);
}
#[test]
fn acroform_needappearances_true() {
let mut pdf = load_one_page_pdf();
let acroform_ref = crate::ObjectRef::new(200, 0);
let mut acroform = Dictionary::new();
acroform.insert("Fields", Object::Array(vec![]));
acroform.insert("NeedAppearances", Object::Boolean(true));
patch_acroform(&mut pdf, acroform_ref, acroform);
let result = build_acroform_section(&mut pdf).expect("build_acroform_section failed");
let JsonValue::Object(pairs) = &result else {
panic!("expected Object");
};
assert_eq!(
pairs[2].1,
JsonValue::Bool(true),
"needappearances must be true"
);
}
#[test]
fn acroform_no_fields_key_yields_empty() {
let mut pdf = load_one_page_pdf();
let acroform_ref = crate::ObjectRef::new(200, 0);
let acroform = Dictionary::new();
patch_acroform(&mut pdf, acroform_ref, acroform);
let result = build_acroform_section(&mut pdf).expect("build_acroform_section failed");
let JsonValue::Object(pairs) = &result else {
panic!("expected Object");
};
assert_eq!(
pairs[0].1,
JsonValue::Array(vec![]),
"fields must be empty when /Fields absent"
);
assert_eq!(
pairs[1].1,
JsonValue::Bool(true),
"hasacroform must be true even with no /Fields"
);
}
#[test]
fn acroform_compat_fixtures_all_no_acroform() {
let fixtures = ["one-page.pdf", "three-page.pdf", "attachment-two-page.pdf"];
for name in fixtures {
let mut pdf = load_fixture_pdf(name);
let result = build_acroform_section(&mut pdf)
.unwrap_or_else(|e| panic!("{name}: build_acroform_section failed: {e:?}"));
let JsonValue::Object(pairs) = &result else {
panic!("{name}: expected Object");
};
assert_eq!(
pairs[1].1,
JsonValue::Bool(false),
"{name}: hasacroform must be false"
);
assert_eq!(
pairs[0].1,
JsonValue::Array(vec![]),
"{name}: fields must be empty"
);
}
}
#[test]
fn build_qpdf_json_v2_has_expected_top_level_keys_with_acroform() {
let mut pdf = load_one_page_pdf();
let v2 = build_qpdf_json_v2(&mut pdf, DecodeLevel::Generalized)
.expect("build_qpdf_json_v2 failed");
let JsonValue::Object(pairs) = v2 else {
panic!("expected Object at top level");
};
let keys: Vec<&str> = pairs.iter().map(|(k, _)| k.as_str()).collect();
assert_eq!(
keys,
vec![
"version",
"parameters",
"pages",
"pagelabels",
"acroform",
"attachments",
"encrypt",
"outlines",
"qpdf"
],
"key order must match qpdf v2: acroform, attachments, encrypt, outlines"
);
}
#[test]
fn acroform_inheritable_fields_descend_from_parent() {
let mut pdf = load_one_page_pdf();
let acroform_ref = crate::ObjectRef::new(200, 0);
let parent_field_ref = crate::ObjectRef::new(201, 0);
let child_field_ref = crate::ObjectRef::new(202, 0);
let mut acroform = Dictionary::new();
acroform.insert(
"Fields",
Object::Array(vec![Object::Reference(parent_field_ref)]),
);
patch_acroform(&mut pdf, acroform_ref, acroform);
let mut parent_field = Dictionary::new();
parent_field.insert("T", Object::String(b"person".to_vec()));
parent_field.insert("FT", Object::Name(b"Tx".to_vec()));
parent_field.insert("V", Object::String(b"alice".to_vec()));
parent_field.insert("DV", Object::String(b"default-alice".to_vec()));
parent_field.insert("Ff", Object::Integer(8192));
parent_field.insert(
"Kids",
Object::Array(vec![Object::Reference(child_field_ref)]),
);
pdf.set_object(parent_field_ref, Object::Dictionary(parent_field));
let mut child_field = Dictionary::new();
child_field.insert("T", Object::String(b"name".to_vec()));
child_field.insert("Parent", Object::Reference(parent_field_ref));
pdf.set_object(child_field_ref, Object::Dictionary(child_field));
let result = build_acroform_section(&mut pdf).expect("build_acroform_section failed");
let JsonValue::Object(top) = &result else {
panic!("expected Object");
};
let JsonValue::Array(fields) = &top[0].1 else {
panic!("fields must be Array");
};
let JsonValue::Object(child_entry) = &fields[1] else {
panic!("child entry must be Object");
};
let get = |k: &str| -> JsonValue {
child_entry
.iter()
.find(|(key, _)| key == k)
.map(|(_, v)| v.clone())
.unwrap_or(JsonValue::Null)
};
assert_eq!(
get("fieldtype"),
JsonValue::String("Tx".to_string()),
"child must inherit /FT from parent"
);
assert_eq!(
get("value"),
JsonValue::String("u:alice".to_string()),
"child must inherit /V from parent"
);
assert_eq!(
get("defaultvalue"),
JsonValue::String("u:default-alice".to_string()),
"child must inherit /DV from parent"
);
assert_eq!(
get("fieldflags"),
JsonValue::Integer(8192),
"child must inherit /Ff from parent"
);
}
#[test]
fn acroform_unnamed_intermediate_field_with_kids_recurses() {
let mut pdf = load_one_page_pdf();
let acroform_ref = crate::ObjectRef::new(200, 0);
let unnamed_ref = crate::ObjectRef::new(201, 0); let leaf_ref = crate::ObjectRef::new(202, 0);
let mut acroform = Dictionary::new();
acroform.insert(
"Fields",
Object::Array(vec![Object::Reference(unnamed_ref)]),
);
patch_acroform(&mut pdf, acroform_ref, acroform);
let mut unnamed = Dictionary::new();
unnamed.insert("FT", Object::Name(b"Tx".to_vec()));
unnamed.insert("Kids", Object::Array(vec![Object::Reference(leaf_ref)]));
pdf.set_object(unnamed_ref, Object::Dictionary(unnamed));
let mut leaf = Dictionary::new();
leaf.insert("T", Object::String(b"name".to_vec()));
leaf.insert("Parent", Object::Reference(unnamed_ref));
pdf.set_object(leaf_ref, Object::Dictionary(leaf));
let result = build_acroform_section(&mut pdf).expect("build_acroform_section failed");
let JsonValue::Object(top) = &result else {
panic!("expected Object");
};
let JsonValue::Array(fields) = &top[0].1 else {
panic!("fields must be Array");
};
assert_eq!(
fields.len(),
2,
"expected 2 entries: unnamed intermediate + leaf"
);
let JsonValue::Object(leaf_entry) = &fields[1] else {
panic!("leaf entry must be Object");
};
let leaf_fullname = leaf_entry
.iter()
.find(|(k, _)| k == "fullname")
.map(|(_, v)| v.clone())
.unwrap();
assert_eq!(
leaf_fullname,
JsonValue::String("name".to_string()),
"leaf fullname must be 'name' (unnamed intermediate contributes no segment)"
);
let leaf_ft = leaf_entry
.iter()
.find(|(k, _)| k == "fieldtype")
.map(|(_, v)| v.clone())
.unwrap();
assert_eq!(leaf_ft, JsonValue::String("Tx".to_string()));
}
#[test]
fn acroform_widget_kid_with_parent_classified_as_annotation() {
let mut pdf = load_one_page_pdf();
let acroform_ref = crate::ObjectRef::new(200, 0);
let field_ref = crate::ObjectRef::new(201, 0);
let widget_ref = crate::ObjectRef::new(202, 0);
let mut acroform = Dictionary::new();
acroform.insert("Fields", Object::Array(vec![Object::Reference(field_ref)]));
patch_acroform(&mut pdf, acroform_ref, acroform);
let mut field = Dictionary::new();
field.insert("T", Object::String(b"signature".to_vec()));
field.insert("FT", Object::Name(b"Sig".to_vec()));
field.insert("Kids", Object::Array(vec![Object::Reference(widget_ref)]));
pdf.set_object(field_ref, Object::Dictionary(field));
let mut widget = Dictionary::new();
widget.insert("Subtype", Object::Name(b"Widget".to_vec()));
widget.insert("Parent", Object::Reference(field_ref));
pdf.set_object(widget_ref, Object::Dictionary(widget));
let result = build_acroform_section(&mut pdf).expect("build_acroform_section failed");
let JsonValue::Object(top) = &result else {
panic!("expected Object");
};
let JsonValue::Array(fields) = &top[0].1 else {
panic!("fields must be Array");
};
assert_eq!(
fields.len(),
1,
"widget kid with /Parent must NOT create a second field entry"
);
let JsonValue::Object(field_entry) = &fields[0] else {
panic!("field entry must be Object");
};
let annotations = field_entry
.iter()
.find(|(k, _)| k == "annotations")
.map(|(_, v)| v.clone())
.unwrap();
assert_eq!(
annotations,
JsonValue::Array(vec![JsonValue::String("202 0 R".to_string())]),
"the widget kid must be listed in annotations, not promoted to a field"
);
}
#[test]
fn acroform_merged_widget_field_with_local_value_is_classified_as_field() {
let mut pdf = load_one_page_pdf();
let acroform_ref = crate::ObjectRef::new(200, 0);
let parent_field_ref = crate::ObjectRef::new(201, 0);
let merged_ref = crate::ObjectRef::new(202, 0);
let mut acroform = Dictionary::new();
acroform.insert(
"Fields",
Object::Array(vec![Object::Reference(parent_field_ref)]),
);
patch_acroform(&mut pdf, acroform_ref, acroform);
let mut parent_field = Dictionary::new();
parent_field.insert("T", Object::String(b"address".to_vec()));
parent_field.insert("FT", Object::Name(b"Tx".to_vec()));
parent_field.insert("Kids", Object::Array(vec![Object::Reference(merged_ref)]));
pdf.set_object(parent_field_ref, Object::Dictionary(parent_field));
let mut merged = Dictionary::new();
merged.insert("Subtype", Object::Name(b"Widget".to_vec()));
merged.insert("Parent", Object::Reference(parent_field_ref));
merged.insert("V", Object::String(b"42 Somewhere".to_vec()));
merged.insert("Ff", Object::Integer(4));
pdf.set_object(merged_ref, Object::Dictionary(merged));
let result = build_acroform_section(&mut pdf).expect("build_acroform_section failed");
let JsonValue::Object(top) = &result else {
panic!("expected Object");
};
let JsonValue::Array(fields) = &top[0].1 else {
panic!("fields must be Array");
};
assert_eq!(
fields.len(),
2,
"merged widget+field with /V must appear as a separate field entry"
);
let JsonValue::Object(merged_entry) = &fields[1] else {
panic!("merged entry must be Object");
};
let value = merged_entry
.iter()
.find(|(k, _)| k == "value")
.map(|(_, v)| v.clone())
.unwrap();
assert_eq!(value, JsonValue::String("u:42 Somewhere".to_string()));
let flags = merged_entry
.iter()
.find(|(k, _)| k == "fieldflags")
.map(|(_, v)| v.clone())
.unwrap();
assert_eq!(flags, JsonValue::Integer(4));
let annotations = merged_entry
.iter()
.find(|(k, _)| k == "annotations")
.map(|(_, v)| v.clone())
.unwrap();
assert_eq!(
annotations,
JsonValue::Array(vec![JsonValue::String("202 0 R".to_string())])
);
}
#[test]
fn acroform_local_field_value_overrides_parent_inheritance() {
let mut pdf = load_one_page_pdf();
let acroform_ref = crate::ObjectRef::new(200, 0);
let parent_field_ref = crate::ObjectRef::new(201, 0);
let child_field_ref = crate::ObjectRef::new(202, 0);
let mut acroform = Dictionary::new();
acroform.insert(
"Fields",
Object::Array(vec![Object::Reference(parent_field_ref)]),
);
patch_acroform(&mut pdf, acroform_ref, acroform);
let mut parent_field = Dictionary::new();
parent_field.insert("T", Object::String(b"person".to_vec()));
parent_field.insert("V", Object::String(b"alice".to_vec()));
parent_field.insert(
"Kids",
Object::Array(vec![Object::Reference(child_field_ref)]),
);
pdf.set_object(parent_field_ref, Object::Dictionary(parent_field));
let mut child_field = Dictionary::new();
child_field.insert("T", Object::String(b"name".to_vec()));
child_field.insert("V", Object::String(b"bob".to_vec()));
child_field.insert("Parent", Object::Reference(parent_field_ref));
pdf.set_object(child_field_ref, Object::Dictionary(child_field));
let result = build_acroform_section(&mut pdf).expect("build_acroform_section failed");
let JsonValue::Object(top) = &result else {
panic!("expected Object");
};
let JsonValue::Array(fields) = &top[0].1 else {
panic!("fields must be Array");
};
let JsonValue::Object(child_entry) = &fields[1] else {
panic!("child entry must be Object");
};
let value = child_entry
.iter()
.find(|(k, _)| k == "value")
.map(|(_, v)| v.clone())
.unwrap();
assert_eq!(
value,
JsonValue::String("u:bob".to_string()),
"local /V must win over parent's /V"
);
}
#[test]
fn acroform_indirect_fields_array_is_resolved() {
let mut pdf = load_one_page_pdf();
let acroform_ref = crate::ObjectRef::new(200, 0);
let fields_array_ref = crate::ObjectRef::new(201, 0);
let field_ref = crate::ObjectRef::new(202, 0);
let mut acroform = Dictionary::new();
acroform.insert("Fields", Object::Reference(fields_array_ref));
patch_acroform(&mut pdf, acroform_ref, acroform);
pdf.set_object(
fields_array_ref,
Object::Array(vec![Object::Reference(field_ref)]),
);
let mut field = Dictionary::new();
field.insert("T", Object::String(b"name".to_vec()));
field.insert("FT", Object::Name(b"Tx".to_vec()));
pdf.set_object(field_ref, Object::Dictionary(field));
let result = build_acroform_section(&mut pdf).expect("build_acroform_section failed");
let JsonValue::Object(top) = &result else {
panic!("expected Object");
};
let JsonValue::Array(fields) = &top[0].1 else {
panic!("fields must be Array");
};
assert_eq!(
fields.len(),
1,
"indirect /Fields array must be resolved, not dropped"
);
let JsonValue::Object(entry) = &fields[0] else {
panic!("entry must be Object");
};
let fullname = entry
.iter()
.find(|(k, _)| k == "fullname")
.map(|(_, v)| v.clone())
.unwrap();
assert_eq!(fullname, JsonValue::String("name".to_string()));
}
#[test]
fn acroform_indirect_kids_array_is_resolved() {
let mut pdf = load_one_page_pdf();
let acroform_ref = crate::ObjectRef::new(200, 0);
let parent_ref = crate::ObjectRef::new(201, 0);
let kids_array_ref = crate::ObjectRef::new(202, 0);
let child_ref = crate::ObjectRef::new(203, 0);
let mut acroform = Dictionary::new();
acroform.insert("Fields", Object::Array(vec![Object::Reference(parent_ref)]));
patch_acroform(&mut pdf, acroform_ref, acroform);
let mut parent_field = Dictionary::new();
parent_field.insert("T", Object::String(b"group".to_vec()));
parent_field.insert("FT", Object::Name(b"Tx".to_vec()));
parent_field.insert("Kids", Object::Reference(kids_array_ref));
pdf.set_object(parent_ref, Object::Dictionary(parent_field));
pdf.set_object(
kids_array_ref,
Object::Array(vec![Object::Reference(child_ref)]),
);
let mut child = Dictionary::new();
child.insert("T", Object::String(b"name".to_vec()));
child.insert("Parent", Object::Reference(parent_ref));
pdf.set_object(child_ref, Object::Dictionary(child));
let result = build_acroform_section(&mut pdf).expect("build_acroform_section failed");
let JsonValue::Object(top) = &result else {
panic!("expected Object");
};
let JsonValue::Array(fields) = &top[0].1 else {
panic!("fields must be Array");
};
assert_eq!(
fields.len(),
2,
"indirect /Kids array must be resolved so descendants are emitted"
);
let JsonValue::Object(child_entry) = &fields[1] else {
panic!("child entry must be Object");
};
let child_fullname = child_entry
.iter()
.find(|(k, _)| k == "fullname")
.map(|(_, v)| v.clone())
.unwrap();
assert_eq!(child_fullname, JsonValue::String("group.name".to_string()));
}
fn load_attachment_pdf() -> crate::Pdf<std::io::Cursor<Vec<u8>>> {
let manifest = std::path::Path::new(env!("CARGO_MANIFEST_DIR"));
let fixture = manifest.join("../../tests/fixtures/compat/attachment-two-page.pdf");
let bytes = std::fs::read(&fixture).unwrap_or_else(|e| {
panic!(
"attachment-two-page.pdf not found at {}: {e}",
fixture.display()
)
});
crate::Pdf::open_mem_owned(bytes).expect("failed to open attachment-two-page.pdf")
}
fn patch_embedded_files(
pdf: &mut crate::Pdf<std::io::Cursor<Vec<u8>>>,
names_ref: crate::ObjectRef,
ef_root_ref: crate::ObjectRef,
filespec_ref: crate::ObjectRef,
filespec: Dictionary,
name: &[u8],
) {
let mut ef_root = Dictionary::new();
ef_root.insert(
"Names",
Object::Array(vec![
Object::String(name.to_vec()),
Object::Reference(filespec_ref),
]),
);
pdf.set_object(ef_root_ref, Object::Dictionary(ef_root));
let mut names_dict = Dictionary::new();
names_dict.insert("EmbeddedFiles", Object::Reference(ef_root_ref));
pdf.set_object(names_ref, Object::Dictionary(names_dict));
let catalog_ref = pdf.root_ref().expect("no /Root");
let mut catalog = match pdf.resolve(catalog_ref).expect("resolve catalog") {
Object::Dictionary(d) => d,
_ => panic!("catalog is not a Dictionary"),
};
catalog.insert("Names", Object::Reference(names_ref));
pdf.set_object(catalog_ref, Object::Dictionary(catalog));
pdf.set_object(filespec_ref, Object::Dictionary(filespec));
}
#[test]
fn attachments_no_embedded_files_returns_empty() {
let mut pdf = load_one_page_pdf();
let result = build_attachments_section(&mut pdf).expect("build_attachments_section failed");
assert_eq!(result, JsonValue::Object(vec![]), "expected empty object");
}
#[test]
fn attachments_fixture_has_one_entry() {
let mut pdf = load_attachment_pdf();
let result = build_attachments_section(&mut pdf).expect("build_attachments_section failed");
let JsonValue::Object(pairs) = &result else {
panic!("expected Object, got {result:?}");
};
assert_eq!(
pairs.len(),
1,
"attachment-two-page.pdf must have exactly 1 attachment"
);
assert_eq!(
pairs[0].0, "attachment.txt",
"attachment name must be 'attachment.txt'"
);
}
#[test]
fn attachments_fixture_entry_fields() {
let mut pdf = load_attachment_pdf();
let result = build_attachments_section(&mut pdf).expect("build_attachments_section failed");
let JsonValue::Object(pairs) = &result else {
panic!("expected Object");
};
let JsonValue::Object(entry) = &pairs[0].1 else {
panic!("entry must be Object");
};
let get = |k: &str| -> &JsonValue {
entry
.iter()
.find(|(key, _)| key == k)
.map(|(_, v)| v)
.unwrap_or_else(|| panic!("key '{k}' not found in entry"))
};
let keys: Vec<&str> = entry.iter().map(|(k, _)| k.as_str()).collect();
assert_eq!(
keys,
vec![
"description",
"filespec",
"names",
"preferredcontents",
"preferredname",
"streams"
],
"entry keys must be in alphabetical order"
);
assert_eq!(
*get("description"),
JsonValue::Null,
"description must be null"
);
let JsonValue::String(filespec_str) = get("filespec") else {
panic!("filespec must be a String");
};
assert!(
filespec_str.ends_with(" R"),
"filespec must be a ref string like 'N M R', got: {filespec_str}"
);
assert_eq!(
*get("preferredname"),
JsonValue::String("attachment.txt".to_string()),
"preferredname must be 'attachment.txt'"
);
let JsonValue::Object(streams) = get("streams") else {
panic!("streams must be Object");
};
assert!(!streams.is_empty(), "streams must not be empty");
for (stream_key, stream_val) in streams {
let JsonValue::Object(stream_entry) = stream_val else {
panic!("stream entry for {stream_key} must be Object");
};
let stream_keys: Vec<&str> = stream_entry.iter().map(|(k, _)| k.as_str()).collect();
assert_eq!(
stream_keys,
vec!["checksum", "creationdate", "mimetype", "modificationdate"],
"stream entry for {stream_key} must have 4 keys in alphabetical order"
);
}
let JsonValue::Object(names) = get("names") else {
panic!("names must be Object");
};
let name_keys: Vec<&str> = names.iter().map(|(k, _)| k.as_str()).collect();
assert!(
name_keys.contains(&"/F") || name_keys.contains(&"/UF"),
"names must contain at least /F or /UF"
);
for (_key, val) in names {
assert_eq!(
*val,
JsonValue::String("attachment.txt".to_string()),
"each name entry must be 'attachment.txt'"
);
}
let JsonValue::String(preferred_contents_str) = get("preferredcontents") else {
panic!("preferredcontents must be a String ref");
};
assert!(
preferred_contents_str.ends_with(" R"),
"preferredcontents must be a ref string, got: {preferred_contents_str}"
);
let JsonValue::Object(streams2) = get("streams") else {
panic!("streams must be Object");
};
for (stream_key, stream_val) in streams2 {
let JsonValue::Object(stream_entry) = stream_val else {
panic!("stream entry for {stream_key} must be Object");
};
let s_get = |k: &str| -> &JsonValue {
stream_entry
.iter()
.find(|(key, _)| key == k)
.map(|(_, v)| v)
.unwrap_or_else(|| panic!("key '{k}' not found in stream {stream_key}"))
};
assert_eq!(
*s_get("checksum"),
JsonValue::String("542266a1f565c3e5d8cfbd55eb7dfa40".to_string()),
"checksum mismatch for stream {stream_key}"
);
assert_eq!(
*s_get("creationdate"),
JsonValue::String("2026-01-01T00:00:00Z".to_string()),
"creationdate mismatch for stream {stream_key}"
);
assert_eq!(
*s_get("modificationdate"),
JsonValue::String("2026-01-01T00:00:00Z".to_string()),
"modificationdate mismatch for stream {stream_key}"
);
assert_eq!(
*s_get("mimetype"),
JsonValue::Null,
"mimetype must be null for stream {stream_key} (no /Subtype in fixture)"
);
}
}
#[test]
fn attachments_synthetic_key_order_and_priorities() {
let mut pdf = load_one_page_pdf();
let stream_f_ref = crate::ObjectRef::new(300, 0);
let stream_uf_ref = crate::ObjectRef::new(301, 0);
let filespec_ref = crate::ObjectRef::new(302, 0);
let ef_root_ref = crate::ObjectRef::new(303, 0);
let names_ref = crate::ObjectRef::new(304, 0);
let mut f_params = Dictionary::new();
let checksum_bytes: Vec<u8> = (0u8..16).collect();
f_params.insert("CheckSum", Object::String(checksum_bytes.clone()));
f_params.insert(
"CreationDate",
Object::String(b"D:20260101000000Z".to_vec()),
);
f_params.insert(
"ModDate",
Object::String(b"D:20260202120000+09'00'".to_vec()),
);
let mut stream_f_dict = Dictionary::new();
stream_f_dict.insert("Type", Object::Name(b"EmbeddedFile".to_vec()));
stream_f_dict.insert("Subtype", Object::Name(b"text/plain".to_vec()));
stream_f_dict.insert("Params", Object::Dictionary(f_params));
pdf.set_object(
stream_f_ref,
Object::Stream(crate::object::Stream::new(stream_f_dict, vec![])),
);
let mut stream_uf_dict = Dictionary::new();
stream_uf_dict.insert("Type", Object::Name(b"EmbeddedFile".to_vec()));
pdf.set_object(
stream_uf_ref,
Object::Stream(crate::object::Stream::new(stream_uf_dict, vec![])),
);
let mut ef_dict = Dictionary::new();
ef_dict.insert("F", Object::Reference(stream_f_ref));
ef_dict.insert("UF", Object::Reference(stream_uf_ref));
let mut filespec = Dictionary::new();
filespec.insert("Type", Object::Name(b"Filespec".to_vec()));
filespec.insert("F", Object::String(b"f-name.txt".to_vec()));
filespec.insert("UF", Object::String(b"uf-name.txt".to_vec()));
filespec.insert("Desc", Object::String(b"My file description".to_vec()));
filespec.insert("EF", Object::Dictionary(ef_dict));
patch_embedded_files(
&mut pdf,
names_ref,
ef_root_ref,
filespec_ref,
filespec,
b"my-attachment.txt",
);
let result = build_attachments_section(&mut pdf).expect("build_attachments_section failed");
let JsonValue::Object(pairs) = &result else {
panic!("expected Object");
};
assert_eq!(pairs.len(), 1, "expected 1 attachment");
assert_eq!(pairs[0].0, "my-attachment.txt", "name mismatch");
let JsonValue::Object(entry) = &pairs[0].1 else {
panic!("entry must be Object");
};
let get = |k: &str| -> &JsonValue {
entry
.iter()
.find(|(key, _)| key == k)
.map(|(_, v)| v)
.unwrap_or_else(|| panic!("key '{k}' not found"))
};
assert_eq!(
*get("description"),
JsonValue::String("My file description".to_string()),
"description must be bare string"
);
let JsonValue::Object(names) = get("names") else {
panic!("names must be Object");
};
let name_keys: Vec<&str> = names.iter().map(|(k, _)| k.as_str()).collect();
assert_eq!(
name_keys,
vec!["/F", "/UF"],
"names keys must be /F, /UF in order"
);
assert_eq!(
names[0].1,
JsonValue::String("f-name.txt".to_string()),
"/F name mismatch"
);
assert_eq!(
names[1].1,
JsonValue::String("uf-name.txt".to_string()),
"/UF name mismatch"
);
assert_eq!(
*get("preferredname"),
JsonValue::String("uf-name.txt".to_string()),
"preferredname must be /UF (uf-name.txt)"
);
assert_eq!(
*get("preferredcontents"),
JsonValue::String(format!(
"{} {} R",
stream_uf_ref.number, stream_uf_ref.generation
)),
"preferredcontents must be /EF/UF ref"
);
let JsonValue::Object(streams) = get("streams") else {
panic!("streams must be Object");
};
let stream_keys: Vec<&str> = streams.iter().map(|(k, _)| k.as_str()).collect();
assert_eq!(
stream_keys,
vec!["/F", "/UF"],
"streams keys must be /F, /UF in order"
);
let JsonValue::Object(f_stream) = &streams[0].1 else {
panic!("/F stream entry must be Object");
};
let f_get = |k: &str| -> &JsonValue {
f_stream
.iter()
.find(|(key, _)| key == k)
.map(|(_, v)| v)
.unwrap_or_else(|| panic!("key '{k}' not found in /F stream"))
};
let expected_hex: String = (0u8..16).map(|b| format!("{b:02x}")).collect();
assert_eq!(
*f_get("checksum"),
JsonValue::String(expected_hex),
"checksum must be lowercase hex"
);
assert_eq!(
*f_get("creationdate"),
JsonValue::String("2026-01-01T00:00:00Z".to_string()),
"creationdate mismatch"
);
assert_eq!(
*f_get("modificationdate"),
JsonValue::String("2026-02-02T12:00:00+09:00".to_string()),
"modificationdate mismatch"
);
assert_eq!(
*f_get("mimetype"),
JsonValue::String("text/plain".to_string()),
"mimetype must be bare 'text/plain'"
);
let JsonValue::Object(uf_stream) = &streams[1].1 else {
panic!("/UF stream entry must be Object");
};
let uf_get = |k: &str| -> &JsonValue {
uf_stream
.iter()
.find(|(key, _)| key == k)
.map(|(_, v)| v)
.unwrap_or_else(|| panic!("key '{k}' not found in /UF stream"))
};
assert_eq!(
*uf_get("mimetype"),
JsonValue::Null,
"/UF mimetype must be null"
);
assert_eq!(
*uf_get("checksum"),
JsonValue::Null,
"/UF checksum must be null"
);
assert_eq!(
*uf_get("creationdate"),
JsonValue::Null,
"/UF creationdate must be null"
);
assert_eq!(
*uf_get("modificationdate"),
JsonValue::Null,
"/UF modificationdate must be null"
);
}
#[test]
fn attachments_direct_inline_filespec_dictionary_is_serialized() {
let mut pdf = load_one_page_pdf();
let mut filespec = Dictionary::new();
filespec.insert("F", Object::String(b"inline.txt".to_vec()));
filespec.insert("UF", Object::String(b"inline.txt".to_vec()));
let mut ef_root = Dictionary::new();
ef_root.insert(
"Names",
Object::Array(vec![
Object::String(b"inline.txt".to_vec()),
Object::Dictionary(filespec), ]),
);
let ef_root_ref = crate::ObjectRef::new(300, 0);
pdf.set_object(ef_root_ref, Object::Dictionary(ef_root));
let mut names_dict = Dictionary::new();
names_dict.insert("EmbeddedFiles", Object::Reference(ef_root_ref));
let names_ref = crate::ObjectRef::new(301, 0);
pdf.set_object(names_ref, Object::Dictionary(names_dict));
let catalog_ref = pdf.root_ref().unwrap();
let mut catalog = match pdf.resolve(catalog_ref).unwrap() {
Object::Dictionary(d) => d,
_ => panic!(),
};
catalog.insert("Names", Object::Reference(names_ref));
pdf.set_object(catalog_ref, Object::Dictionary(catalog));
let result = build_attachments_section(&mut pdf).expect("build_attachments_section failed");
let JsonValue::Object(pairs) = &result else {
panic!("expected Object");
};
assert_eq!(
pairs.len(),
1,
"direct inline filespec must yield an attachments entry"
);
assert_eq!(pairs[0].0, "inline.txt");
let JsonValue::Object(entry) = &pairs[0].1 else {
panic!("entry must be Object");
};
let get = |k: &str| -> &JsonValue {
entry
.iter()
.find(|(key, _)| key == k)
.map(|(_, v)| v)
.unwrap_or_else(|| panic!("key '{k}' missing"))
};
assert_eq!(
*get("filespec"),
JsonValue::Null,
"filespec must be null when the leaf value was a direct dictionary"
);
let JsonValue::Object(names) = get("names") else {
panic!("names must be Object");
};
assert_eq!(names.len(), 2);
assert_eq!(names[0].0, "/F");
assert_eq!(names[1].0, "/UF");
}
#[test]
fn parse_pdf_date_utc_z() {
assert_eq!(
parse_pdf_date(b"D:20260101000000Z"),
Some("2026-01-01T00:00:00Z".to_string())
);
}
#[test]
fn parse_pdf_date_plus_offset() {
assert_eq!(
parse_pdf_date(b"D:20260202120000+09'00'"),
Some("2026-02-02T12:00:00+09:00".to_string())
);
}
#[test]
fn parse_pdf_date_no_tz() {
assert_eq!(
parse_pdf_date(b"D:20260101000000"),
Some("2026-01-01T00:00:00Z".to_string())
);
}
#[test]
fn parse_pdf_date_year_only() {
assert_eq!(
parse_pdf_date(b"D:2026"),
Some("2026-01-01T00:00:00Z".to_string())
);
}
#[test]
fn parse_pdf_date_invalid_returns_none() {
assert_eq!(parse_pdf_date(b"not-a-date"), None);
assert_eq!(parse_pdf_date(b"D:"), None);
assert_eq!(parse_pdf_date(b""), None);
}
#[test]
fn parse_pdf_date_non_ascii_does_not_panic() {
assert_eq!(parse_pdf_date("D:20260é0101".as_bytes()), None);
assert_eq!(parse_pdf_date("D:あいう".as_bytes()), None);
assert_eq!(parse_pdf_date("D:2026あ".as_bytes()), None);
}
#[test]
fn parse_pdf_date_non_digit_components_return_none() {
assert_eq!(parse_pdf_date(b"D:2026XX0101000000Z"), None);
assert_eq!(parse_pdf_date(b"D:20260101NN0000Z"), None);
}
#[test]
fn parse_pdf_date_trailing_garbage_returns_none() {
assert_eq!(parse_pdf_date(b"D:20260101000000garbage"), None);
assert_eq!(parse_pdf_date(b"D:20260101000000*"), None);
}
#[test]
fn parse_pdf_date_malformed_tz_offset_returns_none() {
assert_eq!(parse_pdf_date(b"D:20260101000000+X"), None);
assert_eq!(parse_pdf_date(b"D:20260101000000+0X"), None);
assert_eq!(parse_pdf_date(b"D:20260101000000+0900XX"), None);
}
#[test]
fn parse_pdf_date_partial_date_component_returns_none() {
assert_eq!(parse_pdf_date(b"D:20261"), None);
assert_eq!(parse_pdf_date(b"D:2026010"), None);
assert_eq!(parse_pdf_date(b"D:202601010"), None);
assert!(parse_pdf_date(b"D:2026").is_some());
assert!(parse_pdf_date(b"D:202601").is_some());
assert!(parse_pdf_date(b"D:20260101000000").is_some());
}
#[test]
fn parse_pdf_date_out_of_range_components_return_none() {
assert_eq!(parse_pdf_date(b"D:20261301000000Z"), None, "month 13");
assert_eq!(parse_pdf_date(b"D:20260132000000Z"), None, "day 32");
assert_eq!(parse_pdf_date(b"D:20260101240000Z"), None, "hour 24");
assert_eq!(parse_pdf_date(b"D:20260101006000Z"), None, "minute 60");
assert_eq!(parse_pdf_date(b"D:20260101000060Z"), None, "second 60");
assert_eq!(parse_pdf_date(b"D:20260001000000Z"), None, "month 00");
assert_eq!(parse_pdf_date(b"D:20260100000000Z"), None, "day 00");
}
#[test]
fn parse_pdf_date_out_of_range_tz_offset_returns_none() {
assert_eq!(parse_pdf_date(b"D:20260101000000+99'00'"), None);
assert_eq!(parse_pdf_date(b"D:20260101000000+09'99'"), None);
assert_eq!(parse_pdf_date(b"D:20260101000000-2400"), None);
}
#[test]
fn parse_pdf_date_multiple_trailing_apostrophes_in_offset_returns_none() {
assert_eq!(parse_pdf_date(b"D:20260101000000+09''"), None);
assert_eq!(parse_pdf_date(b"D:20260101000000+09'00'''"), None);
assert_eq!(
parse_pdf_date(b"D:20260101000000+09'00'"),
Some("2026-01-01T00:00:00+09:00".to_string())
);
}
#[test]
fn checksum_to_hex_roundtrip() {
let bytes: Vec<u8> = (0u8..16).collect();
let hex = checksum_to_hex(&bytes);
assert_eq!(hex, "000102030405060708090a0b0c0d0e0f");
assert_eq!(hex.len(), 32);
}
fn load_encrypted_r4_pdf() -> crate::Pdf<std::io::Cursor<Vec<u8>>> {
let manifest = std::path::Path::new(env!("CARGO_MANIFEST_DIR"));
let fixture = manifest.join("../../tests/fixtures/compat/encrypted-r4-three-page.pdf");
let bytes = std::fs::read(&fixture).unwrap_or_else(|e| {
panic!(
"encrypted-r4-three-page.pdf not found at {}: {e}",
fixture.display()
)
});
crate::Pdf::open_mem_owned(bytes).expect("failed to open encrypted-r4-three-page.pdf")
}
#[test]
fn encrypt_section_plaintext_encrypted_false() {
let mut pdf = load_one_page_pdf();
let enc = build_encrypt_section(&mut pdf).expect("build_encrypt_section failed");
let JsonValue::Object(ref pairs) = enc else {
panic!("encrypt section must be an Object");
};
let encrypted = pairs
.iter()
.find(|(k, _)| k == "encrypted")
.unwrap()
.1
.clone();
assert_eq!(encrypted, JsonValue::Bool(false));
}
#[test]
fn encrypt_section_plaintext_ownerpasswordmatched_false() {
let mut pdf = load_one_page_pdf();
let enc = build_encrypt_section(&mut pdf).expect("build_encrypt_section failed");
let JsonValue::Object(ref pairs) = enc else {
panic!("not an Object")
};
let v = pairs
.iter()
.find(|(k, _)| k == "ownerpasswordmatched")
.unwrap()
.1
.clone();
assert_eq!(v, JsonValue::Bool(false));
let v2 = pairs
.iter()
.find(|(k, _)| k == "userpasswordmatched")
.unwrap()
.1
.clone();
assert_eq!(v2, JsonValue::Bool(false));
}
#[test]
fn encrypt_section_plaintext_parameters_are_zero_and_none() {
let mut pdf = load_one_page_pdf();
let enc = build_encrypt_section(&mut pdf).expect("build_encrypt_section failed");
let JsonValue::Object(ref pairs) = enc else {
panic!("not an Object")
};
let params = pairs
.iter()
.find(|(k, _)| k == "parameters")
.unwrap()
.1
.clone();
let JsonValue::Object(ref p) = params else {
panic!("parameters must be Object")
};
let get = |k: &str| p.iter().find(|(ky, _)| ky == k).unwrap().1.clone();
assert_eq!(get("P"), JsonValue::Integer(0));
assert_eq!(get("R"), JsonValue::Integer(0));
assert_eq!(get("V"), JsonValue::Integer(0));
assert_eq!(get("bits"), JsonValue::Integer(0));
assert_eq!(get("filemethod"), JsonValue::String("none".into()));
assert_eq!(get("method"), JsonValue::String("none".into()));
assert_eq!(get("streammethod"), JsonValue::String("none".into()));
assert_eq!(get("stringmethod"), JsonValue::String("none".into()));
assert_eq!(get("key"), JsonValue::Null);
}
#[test]
fn encrypt_section_plaintext_capabilities_all_true() {
let mut pdf = load_one_page_pdf();
let enc = build_encrypt_section(&mut pdf).expect("build_encrypt_section failed");
let JsonValue::Object(ref pairs) = enc else {
panic!("not Object")
};
let caps = pairs
.iter()
.find(|(k, _)| k == "capabilities")
.unwrap()
.1
.clone();
let JsonValue::Object(ref cp) = caps else {
panic!("capabilities must be Object")
};
for (_, v) in cp.iter() {
assert_eq!(
*v,
JsonValue::Bool(true),
"all plaintext capabilities must be true"
);
}
}
#[test]
fn encrypt_section_encrypted_r4_encrypted_true() {
let mut pdf = load_encrypted_r4_pdf();
let enc = build_encrypt_section(&mut pdf).expect("build_encrypt_section failed");
let JsonValue::Object(ref pairs) = enc else {
panic!("not Object")
};
let v = pairs
.iter()
.find(|(k, _)| k == "encrypted")
.unwrap()
.1
.clone();
assert_eq!(v, JsonValue::Bool(true));
}
#[test]
fn encrypt_section_plaintext_password_match_flags_are_both_false() {
let mut pdf = load_one_page_pdf();
let enc = build_encrypt_section(&mut pdf).expect("build_encrypt_section failed");
let JsonValue::Object(ref pairs) = enc else {
panic!("not Object")
};
let owner = pairs
.iter()
.find(|(k, _)| k == "ownerpasswordmatched")
.unwrap()
.1
.clone();
let user = pairs
.iter()
.find(|(k, _)| k == "userpasswordmatched")
.unwrap()
.1
.clone();
assert_eq!(owner, JsonValue::Bool(false));
assert_eq!(user, JsonValue::Bool(false));
}
#[test]
fn encrypt_section_pdf_accessor_independent_of_is_encrypted() {
let pdf = load_one_page_pdf();
assert!(!pdf.is_encrypted());
assert!(!pdf.owner_password_matched());
assert!(!pdf.user_password_matched());
}
#[test]
fn cf_method_string_defaults_to_aesv2_for_revision_4() {
let mut encrypt = Dictionary::new();
encrypt.insert("R", Object::Integer(4));
assert_eq!(cf_method_string(&encrypt, Some("StdCF")), "AESv2");
let mut cf = Dictionary::new();
cf.insert("OtherCF", Object::Dictionary(Dictionary::new()));
encrypt.insert("CF", Object::Dictionary(cf));
assert_eq!(cf_method_string(&encrypt, Some("StdCF")), "AESv2");
let mut encrypt2 = Dictionary::new();
encrypt2.insert("R", Object::Integer(4));
let mut cf2 = Dictionary::new();
cf2.insert("StdCF", Object::Dictionary(Dictionary::new()));
encrypt2.insert("CF", Object::Dictionary(cf2));
assert_eq!(cf_method_string(&encrypt2, Some("StdCF")), "AESv2");
}
#[test]
fn cf_method_string_defaults_to_aesv3_for_revision_5_and_6() {
for r in [5i64, 6] {
let mut encrypt = Dictionary::new();
encrypt.insert("R", Object::Integer(r));
assert_eq!(cf_method_string(&encrypt, Some("StdCF")), "AESv3");
assert_eq!(cf_method_string(&encrypt, None), "AESv3");
}
}
#[test]
fn cf_method_string_defaults_to_rc4_for_legacy_revisions() {
let mut encrypt = Dictionary::new();
encrypt.insert("R", Object::Integer(3));
assert_eq!(cf_method_string(&encrypt, Some("StdCF")), "RC4");
let empty = Dictionary::new();
assert_eq!(cf_method_string(&empty, Some("StdCF")), "RC4");
}
#[test]
fn cf_method_string_identity_selector_still_returns_none() {
let mut encrypt = Dictionary::new();
encrypt.insert("R", Object::Integer(4));
assert_eq!(cf_method_string(&encrypt, Some("Identity")), "none");
}
#[test]
fn encrypt_section_encrypted_r4_pdf_accessors_both_true_for_empty_password() {
let pdf = load_encrypted_r4_pdf();
assert!(pdf.is_encrypted());
assert!(pdf.owner_password_matched());
assert!(pdf.user_password_matched());
}
#[test]
fn encrypt_section_encrypted_r4_ownerpasswordmatched_true() {
let mut pdf = load_encrypted_r4_pdf();
let enc = build_encrypt_section(&mut pdf).expect("build_encrypt_section failed");
let JsonValue::Object(ref pairs) = enc else {
panic!("not Object")
};
let v = pairs
.iter()
.find(|(k, _)| k == "ownerpasswordmatched")
.unwrap()
.1
.clone();
assert_eq!(v, JsonValue::Bool(true));
let v2 = pairs
.iter()
.find(|(k, _)| k == "userpasswordmatched")
.unwrap()
.1
.clone();
assert_eq!(v2, JsonValue::Bool(true));
}
#[test]
fn encrypt_section_encrypted_r4_parameters() {
let mut pdf = load_encrypted_r4_pdf();
let enc = build_encrypt_section(&mut pdf).expect("build_encrypt_section failed");
let JsonValue::Object(ref pairs) = enc else {
panic!("not Object")
};
let params = pairs
.iter()
.find(|(k, _)| k == "parameters")
.unwrap()
.1
.clone();
let JsonValue::Object(ref p) = params else {
panic!("parameters must be Object")
};
let get = |k: &str| p.iter().find(|(ky, _)| ky == k).unwrap().1.clone();
assert_eq!(get("P"), JsonValue::Integer(-4));
assert_eq!(get("R"), JsonValue::Integer(4));
assert_eq!(get("V"), JsonValue::Integer(4));
assert_eq!(get("bits"), JsonValue::Integer(128));
assert_eq!(get("filemethod"), JsonValue::String("AESv2".into()));
assert_eq!(get("method"), JsonValue::String("AESv2".into()));
assert_eq!(get("streammethod"), JsonValue::String("AESv2".into()));
assert_eq!(get("stringmethod"), JsonValue::String("AESv2".into()));
assert_eq!(get("key"), JsonValue::Null);
}
#[test]
fn encrypt_section_encrypted_r4_capabilities_all_true() {
let mut pdf = load_encrypted_r4_pdf();
let enc = build_encrypt_section(&mut pdf).expect("build_encrypt_section failed");
let JsonValue::Object(ref pairs) = enc else {
panic!("not Object")
};
let caps = pairs
.iter()
.find(|(k, _)| k == "capabilities")
.unwrap()
.1
.clone();
let JsonValue::Object(ref cp) = caps else {
panic!("capabilities must be Object")
};
for (name, v) in cp.iter() {
assert_eq!(
*v,
JsonValue::Bool(true),
"capability {name} must be true for P=-4"
);
}
}
#[test]
fn encrypt_section_capabilities_key_order() {
let mut pdf = load_one_page_pdf();
let enc = build_encrypt_section(&mut pdf).expect("build_encrypt_section failed");
let JsonValue::Object(ref pairs) = enc else {
panic!("not Object")
};
let caps = pairs
.iter()
.find(|(k, _)| k == "capabilities")
.unwrap()
.1
.clone();
let JsonValue::Object(ref cp) = caps else {
panic!("capabilities must be Object")
};
let keys: Vec<&str> = cp.iter().map(|(k, _)| k.as_str()).collect();
assert_eq!(
keys,
vec![
"accessibility",
"extract",
"modify",
"modifyannotations",
"modifyassembly",
"modifyforms",
"modifyother",
"printhigh",
"printlow",
]
);
}
#[test]
fn encrypt_section_parameters_key_order() {
let mut pdf = load_one_page_pdf();
let enc = build_encrypt_section(&mut pdf).expect("build_encrypt_section failed");
let JsonValue::Object(ref pairs) = enc else {
panic!("not Object")
};
let params = pairs
.iter()
.find(|(k, _)| k == "parameters")
.unwrap()
.1
.clone();
let JsonValue::Object(ref p) = params else {
panic!("parameters must be Object")
};
let keys: Vec<&str> = p.iter().map(|(k, _)| k.as_str()).collect();
assert_eq!(
keys,
vec![
"P",
"R",
"V",
"bits",
"filemethod",
"key",
"method",
"streammethod",
"stringmethod"
]
);
}
#[test]
fn encrypt_section_top_level_key_order() {
let mut pdf = load_one_page_pdf();
let enc = build_encrypt_section(&mut pdf).expect("build_encrypt_section failed");
let JsonValue::Object(ref pairs) = enc else {
panic!("not Object")
};
let keys: Vec<&str> = pairs.iter().map(|(k, _)| k.as_str()).collect();
assert_eq!(
keys,
vec![
"capabilities",
"encrypted",
"ownerpasswordmatched",
"parameters",
"recovereduserpassword",
"userpasswordmatched",
]
);
}
#[test]
fn encrypt_section_recovereduserpassword_always_null() {
let mut pdf_plain = load_one_page_pdf();
let enc_plain = build_encrypt_section(&mut pdf_plain).expect("plain failed");
let JsonValue::Object(ref p) = enc_plain else {
panic!("not Object")
};
let v = p
.iter()
.find(|(k, _)| k == "recovereduserpassword")
.unwrap()
.1
.clone();
assert_eq!(v, JsonValue::Null);
let mut pdf_enc = load_encrypted_r4_pdf();
let enc_enc = build_encrypt_section(&mut pdf_enc).expect("encrypted failed");
let JsonValue::Object(ref pe) = enc_enc else {
panic!("not Object")
};
let ve = pe
.iter()
.find(|(k, _)| k == "recovereduserpassword")
.unwrap()
.1
.clone();
assert_eq!(ve, JsonValue::Null);
}
#[test]
fn build_qpdf_json_v2_includes_encrypt_section() {
let mut pdf = load_one_page_pdf();
let v2 = build_qpdf_json_v2(&mut pdf, DecodeLevel::Generalized)
.expect("build_qpdf_json_v2 failed");
let JsonValue::Object(pairs) = v2 else {
panic!("expected Object at top level")
};
let enc = pairs.iter().find(|(k, _)| k == "encrypt").map(|(_, v)| v);
assert!(
enc.is_some(),
"encrypt key must be present in composite output"
);
assert!(
matches!(enc.unwrap(), JsonValue::Object(_)),
"encrypt must be an Object"
);
}
fn get_obj7_stream_inner(
pdf: &mut crate::Pdf<std::io::Cursor<Vec<u8>>>,
mode: &StreamDataMode,
) -> Vec<(String, JsonValue)> {
let meta = QpdfMetadata {
pdf_version: "1.3".to_string(),
max_object_id: 7,
pushed_inherited_page_resources: false,
called_get_all_pages: true,
};
let JsonValue::Array(elems) =
build_qpdf_key_with_stream_mode(pdf, meta, mode).expect("build failed")
else {
panic!("expected Array");
};
let JsonValue::Object(map_pairs) = &elems[1] else {
panic!("objects_map is not an Object");
};
let obj7 = map_pairs
.iter()
.find(|(k, _)| k == "obj:7 0 R")
.map(|(_, v)| v)
.expect("obj:7 0 R not found");
let JsonValue::Object(obj7_pairs) = obj7 else {
panic!("obj:7 0 R is not an Object");
};
assert_eq!(obj7_pairs[0].0, "stream");
let JsonValue::Object(inner) = &obj7_pairs[0].1 else {
panic!("stream value is not an Object");
};
inner.clone()
}
#[test]
fn stream_data_mode_none_emits_dict_only() {
let mut pdf = load_one_page_pdf();
let inner = get_obj7_stream_inner(&mut pdf, &StreamDataMode::None);
assert_eq!(
inner.len(),
1,
"None mode: expected 1 key (dict), got {:?}",
inner.iter().map(|(k, _)| k).collect::<Vec<_>>()
);
assert_eq!(inner[0].0, "dict");
}
#[test]
fn stream_data_mode_inline_emits_base64_data_and_dict() {
let mut pdf = load_one_page_pdf();
let oref = crate::ObjectRef::new(7, 0);
let obj7_raw = pdf.resolve(oref).expect("resolve obj:7");
let raw_bytes = match &obj7_raw {
Object::Stream(s) => s.data.clone(),
other => panic!("obj:7 is not a Stream: {other:?}"),
};
let inner = get_obj7_stream_inner(&mut pdf, &StreamDataMode::Inline);
assert_eq!(inner.len(), 2, "Inline mode: expected 2 keys");
assert_eq!(inner[0].0, "data", "first key must be 'data'");
assert_eq!(inner[1].0, "dict", "second key must be 'dict'");
let JsonValue::String(b64) = &inner[0].1 else {
panic!("data is not a String");
};
let decoded = base64_decode_test_helper(b64);
assert_eq!(decoded, raw_bytes, "base64 round-trip failed");
}
#[test]
fn stream_data_mode_file_emits_datafile_and_dict() {
let mut pdf = load_one_page_pdf();
let inner = get_obj7_stream_inner(
&mut pdf,
&StreamDataMode::File {
prefix: "out".to_string(),
},
);
assert_eq!(inner.len(), 2, "File mode: expected 2 keys");
assert_eq!(inner[0].0, "datafile", "first key must be 'datafile'");
assert_eq!(inner[1].0, "dict", "second key must be 'dict'");
assert_eq!(inner[0].1, JsonValue::String("out-007".to_string()));
}
#[test]
fn stream_data_mode_trailer_always_has_value_wrapper() {
let mut pdf = load_one_page_pdf();
for mode in &[
StreamDataMode::None,
StreamDataMode::Inline,
StreamDataMode::File {
prefix: "x".to_string(),
},
] {
let meta = QpdfMetadata {
pdf_version: "1.3".to_string(),
max_object_id: 7,
pushed_inherited_page_resources: false,
called_get_all_pages: true,
};
let JsonValue::Array(elems) =
build_qpdf_key_with_stream_mode(&mut pdf, meta, mode).expect("build failed")
else {
panic!("expected Array");
};
let JsonValue::Object(map_pairs) = &elems[1] else {
panic!("objects_map is not an Object");
};
let trailer = map_pairs
.iter()
.find(|(k, _)| k == "trailer")
.map(|(_, v)| v)
.expect("trailer not found");
let JsonValue::Object(trailer_pairs) = trailer else {
panic!("trailer is not an Object for mode {mode:?}");
};
assert_eq!(
trailer_pairs[0].0, "value",
"trailer must have 'value' key regardless of StreamDataMode ({mode:?})"
);
}
}
#[test]
fn base64_encode_rfc4648_vectors() {
assert_eq!(base64_encode(b""), "");
assert_eq!(base64_encode(b"f"), "Zg==");
assert_eq!(base64_encode(b"fo"), "Zm8=");
assert_eq!(base64_encode(b"foo"), "Zm9v");
assert_eq!(base64_encode(b"foob"), "Zm9vYg==");
assert_eq!(base64_encode(b"fooba"), "Zm9vYmE=");
assert_eq!(base64_encode(b"foobar"), "Zm9vYmFy");
}
#[test]
fn base64_encode_all_byte_values() {
let all_bytes: Vec<u8> = (0u8..=255).collect();
let encoded = base64_encode(&all_bytes);
assert_eq!(encoded.len(), 344);
let decoded = base64_decode_test_helper(&encoded);
assert_eq!(decoded, all_bytes);
}
#[test]
fn build_qpdf_json_v2_with_options_inline_propagates_to_qpdf_key() {
let mut pdf = load_one_page_pdf();
let v2 = build_qpdf_json_v2_with_options(
&mut pdf,
DecodeLevel::Generalized,
&StreamDataMode::Inline,
)
.expect("build failed");
let JsonValue::Object(top_pairs) = &v2 else {
panic!("expected Object at top level");
};
let qpdf_val = top_pairs
.iter()
.find(|(k, _)| k == "qpdf")
.map(|(_, v)| v)
.expect("qpdf key not found");
let JsonValue::Array(qpdf_arr) = qpdf_val else {
panic!("qpdf is not an Array");
};
let JsonValue::Object(obj_map) = &qpdf_arr[1] else {
panic!("qpdf[1] is not an Object");
};
let obj7 = obj_map
.iter()
.find(|(k, _)| k == "obj:7 0 R")
.map(|(_, v)| v)
.expect("obj:7 0 R not found in qpdf key");
let JsonValue::Object(obj7_pairs) = obj7 else {
panic!("obj:7 is not an Object");
};
let JsonValue::Object(stream_inner) = &obj7_pairs[0].1 else {
panic!("stream value is not Object");
};
assert_eq!(stream_inner[0].0, "data",
"Inline mode must produce 'data' key in stream entry via build_qpdf_json_v2_with_options");
assert!(
matches!(&stream_inner[0].1, JsonValue::String(_)),
"data must be a String"
);
}
#[test]
fn json_key_from_str_all_known() {
assert_eq!(JsonKey::from_str("acroform"), Some(JsonKey::Acroform));
assert_eq!(JsonKey::from_str("attachments"), Some(JsonKey::Attachments));
assert_eq!(JsonKey::from_str("encrypt"), Some(JsonKey::Encrypt));
assert_eq!(JsonKey::from_str("objectinfo"), Some(JsonKey::Objectinfo));
assert_eq!(JsonKey::from_str("objects"), Some(JsonKey::Objects));
assert_eq!(JsonKey::from_str("outlines"), Some(JsonKey::Outlines));
assert_eq!(JsonKey::from_str("pagelabels"), Some(JsonKey::Pagelabels));
assert_eq!(JsonKey::from_str("pages"), Some(JsonKey::Pages));
assert_eq!(JsonKey::from_str("qpdf"), Some(JsonKey::Qpdf));
}
#[test]
fn json_key_from_str_unknown_returns_none() {
assert_eq!(JsonKey::from_str(""), None);
assert_eq!(JsonKey::from_str("Pages"), None); assert_eq!(JsonKey::from_str("version"), None);
assert_eq!(JsonKey::from_str("parameters"), None);
assert_eq!(JsonKey::from_str("bogus"), None);
}
#[test]
fn json_key_all_names_order() {
assert_eq!(JsonKey::ALL_NAMES[0], "acroform");
assert_eq!(JsonKey::ALL_NAMES[1], "attachments");
assert_eq!(JsonKey::ALL_NAMES[2], "encrypt");
assert_eq!(JsonKey::ALL_NAMES[3], "objectinfo");
assert_eq!(JsonKey::ALL_NAMES[4], "objects");
assert_eq!(JsonKey::ALL_NAMES[5], "outlines");
assert_eq!(JsonKey::ALL_NAMES[6], "pagelabels");
assert_eq!(JsonKey::ALL_NAMES[7], "pages");
assert_eq!(JsonKey::ALL_NAMES[8], "qpdf");
assert_eq!(JsonKey::ALL_NAMES.len(), 9);
}
#[test]
fn json_key_output_key_name_aliasing() {
assert_eq!(JsonKey::Objectinfo.output_key_name(), "qpdf");
assert_eq!(JsonKey::Objects.output_key_name(), "qpdf");
assert_eq!(JsonKey::Acroform.output_key_name(), "acroform");
assert_eq!(JsonKey::Attachments.output_key_name(), "attachments");
assert_eq!(JsonKey::Encrypt.output_key_name(), "encrypt");
assert_eq!(JsonKey::Outlines.output_key_name(), "outlines");
assert_eq!(JsonKey::Pagelabels.output_key_name(), "pagelabels");
assert_eq!(JsonKey::Pages.output_key_name(), "pages");
assert_eq!(JsonKey::Qpdf.output_key_name(), "qpdf");
}
fn make_v2_doc() -> JsonValue {
JsonValue::Object(vec![
("version".to_string(), JsonValue::Integer(2)),
(
"parameters".to_string(),
JsonValue::Object(vec![(
"decodelevel".to_string(),
JsonValue::String("generalized".to_string()),
)]),
),
("pages".to_string(), JsonValue::Array(vec![])),
("pagelabels".to_string(), JsonValue::Array(vec![])),
("acroform".to_string(), JsonValue::Null),
("attachments".to_string(), JsonValue::Object(vec![])),
("encrypt".to_string(), JsonValue::Null),
("outlines".to_string(), JsonValue::Array(vec![])),
("qpdf".to_string(), JsonValue::Array(vec![])),
])
}
fn key_names(v: &JsonValue) -> Vec<&str> {
match v {
JsonValue::Object(pairs) => pairs.iter().map(|(k, _)| k.as_str()).collect(),
_ => panic!("expected Object"),
}
}
#[test]
fn filter_json_keys_empty_returns_unchanged() {
let doc = make_v2_doc();
let filtered = filter_json_keys(doc.clone(), &[]);
assert_eq!(key_names(&filtered), key_names(&doc));
}
#[test]
fn filter_json_keys_single_pages() {
let doc = make_v2_doc();
let filtered = filter_json_keys(doc, &[JsonKey::Pages]);
let names = key_names(&filtered);
assert_eq!(names, vec!["version", "parameters", "pages"]);
}
#[test]
fn filter_json_keys_pages_and_pagelabels() {
let doc = make_v2_doc();
let filtered = filter_json_keys(doc, &[JsonKey::Pages, JsonKey::Pagelabels]);
let names = key_names(&filtered);
assert_eq!(names, vec!["version", "parameters", "pages", "pagelabels"]);
}
#[test]
fn filter_json_keys_objects_alias_to_qpdf() {
let doc = make_v2_doc();
let filtered = filter_json_keys(doc, &[JsonKey::Objects]);
let names = key_names(&filtered);
assert_eq!(names, vec!["version", "parameters", "qpdf"]);
}
#[test]
fn filter_json_keys_objectinfo_alias_to_qpdf() {
let doc = make_v2_doc();
let filtered = filter_json_keys(doc, &[JsonKey::Objectinfo]);
let names = key_names(&filtered);
assert_eq!(names, vec!["version", "parameters", "qpdf"]);
}
#[test]
fn filter_json_keys_dedupe_pages() {
let doc = make_v2_doc();
let filtered = filter_json_keys(doc, &[JsonKey::Pages, JsonKey::Pages]);
let names = key_names(&filtered);
assert_eq!(names, vec!["version", "parameters", "pages"]);
}
#[test]
fn filter_json_keys_objects_and_qpdf_dedupe() {
let doc = make_v2_doc();
let filtered = filter_json_keys(doc, &[JsonKey::Objects, JsonKey::Qpdf]);
let names = key_names(&filtered);
assert_eq!(names, vec!["version", "parameters", "qpdf"]);
}
#[test]
fn filter_json_keys_absent_key_skipped() {
let partial_doc = JsonValue::Object(vec![
("version".to_string(), JsonValue::Integer(2)),
(
"parameters".to_string(),
JsonValue::Object(vec![(
"decodelevel".to_string(),
JsonValue::String("generalized".to_string()),
)]),
),
("pages".to_string(), JsonValue::Array(vec![])),
]);
let filtered = filter_json_keys(partial_doc, &[JsonKey::Pages, JsonKey::Encrypt]);
let names = key_names(&filtered);
assert_eq!(names, vec!["version", "parameters", "pages"]);
assert!(!names.contains(&"encrypt"));
}
#[test]
fn filter_json_keys_output_order_fixed() {
let doc = make_v2_doc();
let filtered = filter_json_keys(doc, &[JsonKey::Qpdf, JsonKey::Pages]);
let names = key_names(&filtered);
assert_eq!(names, vec!["version", "parameters", "pages", "qpdf"]);
}
#[test]
fn filter_json_keys_non_object_returned_as_is() {
let v = JsonValue::Integer(42);
let result = filter_json_keys(v, &[JsonKey::Pages]);
assert_eq!(result, JsonValue::Integer(42));
}
#[test]
fn json_object_selector_from_str_trailer() {
assert_eq!(
JsonObjectSelector::from_str("trailer"),
Some(JsonObjectSelector::Trailer)
);
}
#[test]
fn json_object_selector_from_str_num_only() {
assert_eq!(
JsonObjectSelector::from_str("3"),
Some(JsonObjectSelector::Object {
number: 3,
generation: 0
})
);
}
#[test]
fn json_object_selector_from_str_num_gen_zero() {
assert_eq!(
JsonObjectSelector::from_str("3,0"),
Some(JsonObjectSelector::Object {
number: 3,
generation: 0
})
);
}
#[test]
fn json_object_selector_from_str_num_gen_nonzero() {
assert_eq!(
JsonObjectSelector::from_str("3,5"),
Some(JsonObjectSelector::Object {
number: 3,
generation: 5
})
);
}
#[test]
fn json_object_selector_from_str_invalid_three_parts() {
assert_eq!(JsonObjectSelector::from_str("3,5,6"), None);
}
#[test]
fn json_object_selector_from_str_invalid_non_numeric() {
assert_eq!(JsonObjectSelector::from_str("abc"), None);
}
#[test]
fn json_object_selector_from_str_invalid_alpha_suffix() {
assert_eq!(JsonObjectSelector::from_str("3a"), None);
}
#[test]
fn json_object_selector_from_str_invalid_empty() {
assert_eq!(JsonObjectSelector::from_str(""), None);
}
#[test]
fn json_object_selector_from_str_invalid_negative() {
assert_eq!(JsonObjectSelector::from_str("-3"), None);
}
#[test]
fn json_object_selector_from_str_invalid_overflow_u32() {
assert_eq!(JsonObjectSelector::from_str("999999999999"), None);
}
#[test]
fn json_object_selector_from_str_invalid_gen_non_numeric() {
assert_eq!(JsonObjectSelector::from_str("3,a"), None);
}
#[test]
fn json_object_selector_from_str_invalid_gen_overflow_u16() {
assert_eq!(JsonObjectSelector::from_str("3,65536"), None);
}
#[test]
fn json_object_selector_from_str_uppercase_trailer_rejected() {
assert_eq!(JsonObjectSelector::from_str("Trailer"), None);
assert_eq!(JsonObjectSelector::from_str("TRAILER"), None);
}
fn make_qpdf_doc_with_objects() -> JsonValue {
let metadata = JsonValue::Object(vec![
("jsonversion".to_string(), JsonValue::Integer(2)),
(
"pdfversion".to_string(),
JsonValue::String("1.4".to_string()),
),
(
"pushedinheritedpageresources".to_string(),
JsonValue::Bool(false),
),
("calledgetallpages".to_string(), JsonValue::Bool(true)),
("maxobjectid".to_string(), JsonValue::Integer(5)),
]);
let objects_map = JsonValue::Object(vec![
(
"obj:3 0 R".to_string(),
JsonValue::Object(vec![("value".to_string(), JsonValue::Integer(42))]),
),
(
"obj:5 0 R".to_string(),
JsonValue::Object(vec![("value".to_string(), JsonValue::Integer(99))]),
),
(
"trailer".to_string(),
JsonValue::Object(vec![("value".to_string(), JsonValue::Object(vec![]))]),
),
]);
JsonValue::Object(vec![
("version".to_string(), JsonValue::Integer(2)),
(
"parameters".to_string(),
JsonValue::Object(vec![(
"decodelevel".to_string(),
JsonValue::String("generalized".to_string()),
)]),
),
("pages".to_string(), JsonValue::Array(vec![])),
(
"qpdf".to_string(),
JsonValue::Array(vec![metadata, objects_map]),
),
])
}
fn qpdf_objects_keys(v: &JsonValue) -> Vec<&str> {
match v {
JsonValue::Object(pairs) => {
let qpdf_arr = pairs.iter().find(|(k, _)| k == "qpdf").map(|(_, v)| v);
match qpdf_arr {
Some(JsonValue::Array(arr)) if arr.len() == 2 => match &arr[1] {
JsonValue::Object(obj_pairs) => {
obj_pairs.iter().map(|(k, _)| k.as_str()).collect()
}
_ => vec![],
},
_ => vec![],
}
}
_ => panic!("expected Object"),
}
}
#[test]
fn filter_json_objects_empty_selectors_unchanged() {
let doc = make_qpdf_doc_with_objects();
let filtered = filter_json_objects(doc.clone(), &[]);
assert_eq!(key_names(&filtered), key_names(&doc));
assert_eq!(
qpdf_objects_keys(&filtered),
vec!["obj:3 0 R", "obj:5 0 R", "trailer"]
);
}
#[test]
fn filter_json_objects_single_object() {
let doc = make_qpdf_doc_with_objects();
let sel = JsonObjectSelector::Object {
number: 3,
generation: 0,
};
let filtered = filter_json_objects(doc, &[sel]);
assert_eq!(qpdf_objects_keys(&filtered), vec!["obj:3 0 R"]);
assert!(key_names(&filtered).contains(&"pages"));
}
#[test]
fn filter_json_objects_trailer_only() {
let doc = make_qpdf_doc_with_objects();
let filtered = filter_json_objects(doc, &[JsonObjectSelector::Trailer]);
assert_eq!(qpdf_objects_keys(&filtered), vec!["trailer"]);
}
#[test]
fn filter_json_objects_object_and_trailer() {
let doc = make_qpdf_doc_with_objects();
let sels = vec![
JsonObjectSelector::Object {
number: 3,
generation: 0,
},
JsonObjectSelector::Trailer,
];
let filtered = filter_json_objects(doc, &sels);
assert_eq!(qpdf_objects_keys(&filtered), vec!["obj:3 0 R", "trailer"]);
}
#[test]
fn filter_json_objects_missing_object_empty_result() {
let doc = make_qpdf_doc_with_objects();
let sel = JsonObjectSelector::Object {
number: 999,
generation: 0,
};
let filtered = filter_json_objects(doc, &[sel]);
assert_eq!(qpdf_objects_keys(&filtered), Vec::<&str>::new());
}
#[test]
fn filter_json_objects_duplicate_selectors_dedupe() {
let doc = make_qpdf_doc_with_objects();
let sel = JsonObjectSelector::Object {
number: 3,
generation: 0,
};
let filtered = filter_json_objects(doc, &[sel, sel]);
assert_eq!(qpdf_objects_keys(&filtered), vec!["obj:3 0 R"]);
}
#[test]
fn filter_json_objects_no_qpdf_key_unchanged() {
let doc = JsonValue::Object(vec![
("version".to_string(), JsonValue::Integer(2)),
("pages".to_string(), JsonValue::Array(vec![])),
]);
let sel = JsonObjectSelector::Object {
number: 3,
generation: 0,
};
let filtered = filter_json_objects(doc, &[sel]);
assert_eq!(key_names(&filtered), vec!["version", "pages"]);
}
#[test]
fn filter_json_objects_envelope_and_pages_preserved() {
let doc = make_qpdf_doc_with_objects();
let sel = JsonObjectSelector::Object {
number: 3,
generation: 0,
};
let filtered = filter_json_objects(doc, &[sel]);
let names = key_names(&filtered);
assert!(names.contains(&"version"), "version missing");
assert!(names.contains(&"parameters"), "parameters missing");
assert!(names.contains(&"pages"), "pages missing");
assert!(names.contains(&"qpdf"), "qpdf missing");
}
fn base64_decode_test_helper(s: &str) -> Vec<u8> {
fn val(c: u8) -> u8 {
match c {
b'A'..=b'Z' => c - b'A',
b'a'..=b'z' => c - b'a' + 26,
b'0'..=b'9' => c - b'0' + 52,
b'+' => 62,
b'/' => 63,
b'=' => 0, _ => panic!("invalid base64 char: {c}"),
}
}
let bytes = s.as_bytes();
assert_eq!(bytes.len() % 4, 0, "base64 length must be multiple of 4");
let mut out = Vec::with_capacity(bytes.len() / 4 * 3);
for chunk in bytes.chunks(4) {
let (a, b, c, d) = (val(chunk[0]), val(chunk[1]), val(chunk[2]), val(chunk[3]));
let combined = ((a as u32) << 18) | ((b as u32) << 12) | ((c as u32) << 6) | (d as u32);
out.push(((combined >> 16) & 0xFF) as u8);
if chunk[2] != b'=' {
out.push(((combined >> 8) & 0xFF) as u8);
}
if chunk[3] != b'=' {
out.push((combined & 0xFF) as u8);
}
}
out
}
#[test]
fn filter_json_keys_normalizes_envelope_to_version_then_parameters() {
let v2 = JsonValue::Object(vec![
(
"parameters".to_string(),
JsonValue::Object(vec![(
"decodelevel".to_string(),
JsonValue::String("generalized".to_string()),
)]),
),
("version".to_string(), JsonValue::Integer(2)),
("pages".to_string(), JsonValue::Array(vec![])),
]);
let filtered = filter_json_keys(v2, &[JsonKey::Pages]);
let JsonValue::Object(pairs) = filtered else {
panic!("expected Object");
};
let keys: Vec<&str> = pairs.iter().map(|(k, _)| k.as_str()).collect();
assert_eq!(
keys,
vec!["version", "parameters", "pages"],
"envelope must always be emitted as version, parameters, … even when the input has the opposite order"
);
}
#[test]
fn filter_json_keys_preserves_envelope_order_when_version_only_present() {
let v2 = JsonValue::Object(vec![
("version".to_string(), JsonValue::Integer(2)),
("pages".to_string(), JsonValue::Array(vec![])),
]);
let filtered = filter_json_keys(v2, &[JsonKey::Pages]);
let JsonValue::Object(pairs) = filtered else {
panic!("expected Object");
};
let keys: Vec<&str> = pairs.iter().map(|(k, _)| k.as_str()).collect();
assert_eq!(keys, vec!["version", "pages"]);
}
}