use crate::json::JsonValue;
use crate::object::{Dictionary, Object, ObjectRef, Stream};
use crate::reader::Pdf;
use std::borrow::Cow;
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
}
pub(crate) fn qpdf_utf8_value(bytes: &[u8]) -> Vec<u8> {
if let Some(rest) = bytes.strip_prefix(&[0xfe, 0xff]) {
return lossy_utf16_to_utf8(rest, false).into_bytes();
}
if let Some(rest) = bytes.strip_prefix(&[0xff, 0xfe]) {
return lossy_utf16_to_utf8(rest, true).into_bytes();
}
if let Some(rest) = bytes.strip_prefix(&[0xef, 0xbb, 0xbf]) {
return rest.to_vec();
}
bytes
.iter()
.map(|&byte| match byte {
0x7f | 0x9f | 0xad => '\u{fffd}',
_ => PDFDOC_ENCODING[byte as usize].unwrap_or(byte as char),
})
.collect::<String>()
.into_bytes()
}
pub(crate) 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 use_hex_string(bytes: &[u8]) -> bool {
let mut non_ascii: usize = 0;
for &b in bytes {
match b {
0x20..=0x7E => continue,
0x18..=0x1F | 0x7F | 0x80..=0xFF => non_ascii += 1,
0x08 | 0x09 | 0x0A | 0x0C | 0x0D => continue,
_ => return true,
}
}
5 * non_ascii > bytes.len()
}
fn lossy_utf16_to_utf8(bytes: &[u8], is_le: bool) -> String {
let mut out = String::with_capacity(bytes.len());
let mut codepoint: u32 = 0;
let mut i = 0;
while i + 1 < bytes.len() {
let (msb_idx, lsb_idx) = if is_le { (i + 1, i) } else { (i, i + 1) };
let bits = (u16::from(bytes[msb_idx]) << 8) | u16::from(bytes[lsb_idx]);
match bits & 0xFC00 {
0xD800 => {
codepoint = 0x10000 + ((u32::from(bits) & 0x3FF) << 10);
i += 2;
continue;
}
0xDC00 => {
codepoint += u32::from(bits) & 0x3FF;
}
_ => {
codepoint = u32::from(bits);
}
}
if let Some(c) = char::from_u32(codepoint) {
out.push(c);
}
codepoint = 0;
i += 2;
}
out
}
fn pdf_string_to_json_string(bytes: &[u8]) -> String {
if let Some(rest) = bytes.strip_prefix(&[0xFE, 0xFF]) {
return format!("u:{}", lossy_utf16_to_utf8(rest, false));
}
if let Some(rest) = bytes.strip_prefix(&[0xFF, 0xFE]) {
return format!("u:{}", lossy_utf16_to_utf8(rest, true));
}
if let Some(rest) = bytes.strip_prefix(&[0xEF, 0xBB, 0xBF]) {
if let Ok(s) = std::str::from_utf8(rest) {
return format!("u:{s}");
}
}
if !use_hex_string(bytes) {
if let Some(text) = decode_pdf_text_string(bytes) {
return format!("u:{text}");
}
}
let mut out = String::with_capacity(2 + bytes.len() * 2);
out.push_str("b:");
for &b in bytes {
out.push(char::from_digit(u32::from(b >> 4), 16).expect("nibble < 16"));
out.push(char::from_digit(u32::from(b & 0xf), 16).expect("nibble < 16"));
}
out
}
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 qpdf_dict_to_json<R: Read + Seek>(
pdf: &mut Pdf<R>,
dict: &Dictionary,
) -> Result<JsonValue, ConvertError> {
let mut pairs = Vec::new();
for (raw_key, value) in dict.iter() {
let omit = crate::qpdf_null::value_is_null(pdf, value)?;
if omit {
continue;
}
pairs.push((
encode_pdf_name_bytes(raw_key),
qpdf_pdf_object_to_json(pdf, value)?,
));
}
pairs.sort_by(|a, b| a.0.cmp(&b.0));
Ok(JsonValue::Object(pairs))
}
fn qpdf_pdf_object_to_json<R: Read + Seek>(
pdf: &mut Pdf<R>,
object: &Object,
) -> Result<JsonValue, ConvertError> {
match object {
Object::Reference(reference) if !crate::qpdf_null::reference_is_valid(*reference) => {
Ok(JsonValue::Null)
}
Object::Reference(reference) => Ok(JsonValue::String(format!(
"{} {} R",
reference.number, reference.generation
))),
Object::Array(items) => items
.iter()
.map(|item| qpdf_pdf_object_to_json(pdf, item))
.collect::<Result<Vec<_>, _>>()
.map(JsonValue::Array),
Object::Dictionary(dict) => qpdf_dict_to_json(pdf, dict),
Object::Stream(stream) => Ok(JsonValue::Object(vec![(
"stream".to_string(),
JsonValue::Object(vec![(
"dict".to_string(),
qpdf_dict_to_json(pdf, &stream.dict)?,
)]),
)])),
other => pdf_object_to_json(other),
}
}
fn qpdf_resolve_top_level_object<R: Read + Seek>(
pdf: &mut Pdf<R>,
start: ObjectRef,
) -> Result<Object, ConvertError> {
let mut current = start;
let mut visited = std::collections::BTreeSet::new();
loop {
if !visited.insert(current) {
return Ok(Object::Null);
}
match pdf.resolve_qpdf_json_object(current)? {
Object::Reference(next) => current = next,
terminal => return Ok(terminal),
}
}
}
pub fn qpdf_raw_stream_payload<R: Read + Seek>(
pdf: &mut Pdf<R>,
object_ref: ObjectRef,
decode_level: DecodeLevel,
) -> Result<Option<Vec<u8>>, ConvertError> {
let Object::Stream(stream) = qpdf_resolve_top_level_object(pdf, object_ref)? else {
return Ok(None);
};
Ok(Some(
stream_payload_for_decode_level(&stream, decode_level).into_owned(),
))
}
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) | Object::RealLiteral { value: 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 },
}
pub fn format_json_side_file_path(prefix: &str, obj_num: u32) -> String {
format!("{prefix}-{obj_num}")
}
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,
DecodeLevel::Generalized,
&StreamDataMode::None,
)
}
pub fn build_qpdf_key_with_stream_mode<R: Read + Seek>(
pdf: &mut Pdf<R>,
metadata: QpdfMetadata,
decode_level: DecodeLevel,
stream_mode: &StreamDataMode,
) -> Result<JsonValue, ConvertError> {
let prepared = pdf.prepare_qpdf_json_objects()?;
build_qpdf_key_selected_with_stream_mode(
pdf,
metadata,
decode_level,
stream_mode,
&[],
&prepared.refs,
)
}
fn build_qpdf_key_selected_with_stream_mode<R: Read + Seek>(
pdf: &mut Pdf<R>,
metadata: QpdfMetadata,
decode_level: DecodeLevel,
stream_mode: &StreamDataMode,
selectors: &[JsonObjectSelector],
prepared_refs: &[ObjectRef],
) -> 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 mut map_pairs: Vec<(String, JsonValue)> = Vec::new();
for &oref in prepared_refs {
let selected = selectors.is_empty()
|| selectors.iter().any(|selector| {
matches!(
selector,
JsonObjectSelector::Object { number, generation }
if *number == oref.number && *generation == oref.generation
)
});
if !selected {
continue;
}
let key = format!("obj:{} {} R", oref.number, oref.generation);
let obj = qpdf_resolve_top_level_object(pdf, oref)?;
let json_val = match &obj {
Object::Stream(stream) => {
let dict_json = qpdf_dict_to_json(pdf, &stream.dict)?;
let stream_inner = match stream_mode {
StreamDataMode::None => {
JsonValue::Object(vec![("dict".to_string(), dict_json)])
}
StreamDataMode::Inline => {
let payload = stream_payload_for_decode_level(stream, decode_level);
let data_str = base64_encode(&payload);
JsonValue::Object(vec![
("data".to_string(), JsonValue::String(data_str)),
("dict".to_string(), dict_json),
])
}
StreamDataMode::File { prefix } => {
let datafile = format_json_side_file_path(prefix, 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 = qpdf_pdf_object_to_json(pdf, other)?;
JsonValue::Object(vec![("value".to_string(), val)])
}
};
map_pairs.push((key, json_val));
}
if selectors.is_empty()
|| selectors
.iter()
.any(|selector| matches!(selector, JsonObjectSelector::Trailer))
{
let trailer_dict = pdf.trailer().clone();
let trailer_json = qpdf_dict_to_json(pdf, &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 stream_payload_for_decode_level(
stream: &Stream,
decode_level: DecodeLevel,
) -> Cow<'_, [u8]> {
match decode_level {
DecodeLevel::None => Cow::Borrowed(&stream.data),
DecodeLevel::Generalized | DecodeLevel::Specialized | DecodeLevel::All => {
match crate::filters::decode_stream_data(&stream.dict, &stream.data) {
Ok(decoded) => Cow::Owned(decoded),
Err(_) => Cow::Borrowed(&stream.data),
}
}
}
}
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_array = match pdf.resolve_borrowed(*r).map_err(ConvertError::from)? {
Object::Stream(_) => return Ok(vec![ref_string(r)]),
Object::Array(arr) => Object::Array(arr.clone()),
_ => return Ok(vec![]),
};
collect_content_refs(pdf, &resolved_array)
}
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_borrowed(*r).map_err(ConvertError::from)?;
match resolved {
Object::Dictionary(d) => d.clone(),
_ => 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_borrowed(xobj_ref).map_err(ConvertError::from)?;
if let Some(stream) = resolved.as_stream() {
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_borrowed(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 range = crate::page_label_document_helper::LabelRange::from_dict(dict);
let style = match range.style.to_name() {
Some(s) => JsonValue::String(s.to_string()),
None => JsonValue::Null,
};
JsonValue::Object(vec![
("first".to_string(), JsonValue::Integer(range.start)),
("prefix".to_string(), JsonValue::String(range.prefix)),
("style".to_string(), style),
])
}
pub fn build_pagelabels_section<R: Read + Seek>(
pdf: &mut Pdf<R>,
) -> Result<JsonValue, ConvertError> {
use crate::pages::DEFAULT_MAX_PAGE_TREE_DEPTH;
crate::pages::page_refs(pdf)?;
let catalog_ref = match pdf.root_ref() {
Some(r) => r,
None => return Ok(JsonValue::Array(vec![])),
};
let catalog = pdf
.resolve_borrowed(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 mut entries: Vec<(i64, Dictionary)> = crate::name_number_tree::read_number_tree(
pdf,
pagelabels_val,
|pdf, v| match v {
Object::Dictionary(d) => Ok(Some(d)),
Object::Reference(r) => Ok(pdf.resolve_borrowed(r)?.as_dict().cloned()),
_ => Ok(None),
},
DEFAULT_MAX_PAGE_TREE_DEPTH,
)
.map_err(ConvertError::from)?;
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_item_to_json(
tree: &crate::OutlineTree,
id: crate::OutlineId,
page_numbers: &std::collections::BTreeMap<crate::ObjectRef, i64>,
) -> Result<JsonValue, ConvertError> {
let item = &tree[id];
let dest = pdf_object_to_json(&item.dest)?;
let destpageposfrom1 = match item.dest_page() {
Object::Reference(reference) => page_numbers
.get(&reference)
.copied()
.map(JsonValue::Integer)
.unwrap_or(JsonValue::Null),
_ => JsonValue::Null,
};
let kids = item
.kids
.iter()
.copied()
.map(|kid| outline_item_to_json(tree, kid, page_numbers))
.collect::<Result<Vec<_>, _>>()?;
let object = match item.source_ref {
Some(reference) => JsonValue::String(reference.to_string()),
None => pdf_object_to_json(&item.object)?,
};
Ok(JsonValue::Object(vec![
("dest".to_string(), dest),
("destpageposfrom1".to_string(), destpageposfrom1),
("kids".to_string(), JsonValue::Array(kids)),
("object".to_string(), object),
("open".to_string(), JsonValue::Bool(item.count >= 0)),
("title".to_string(), JsonValue::String(item.title.clone())),
]))
}
pub fn build_outlines_section<R: Read + Seek>(pdf: &mut Pdf<R>) -> Result<JsonValue, ConvertError> {
let page_numbers = crate::pages::page_refs(pdf)?
.into_iter()
.enumerate()
.map(|(index, reference)| (reference, index as i64 + 1))
.collect::<std::collections::BTreeMap<_, _>>();
let tree = pdf.outline().get_tree()?;
let entries = tree
.roots()
.iter()
.copied()
.map(|id| outline_item_to_json(&tree, id, &page_numbers))
.collect::<Result<Vec<_>, _>>()?;
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_borrowed(field_ref)
.map_err(ConvertError::from)?;
let field_dict = match field_obj {
Object::Dictionary(d) => d.clone(),
_ => 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_borrowed(r).map_err(ConvertError::from)? {
Object::Array(arr) => arr.clone(),
_ => 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_borrowed(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> {
use crate::pages::DEFAULT_MAX_PAGE_TREE_DEPTH;
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();
let mut depth: usize = 0;
while let Some(Object::Reference(pr)) = parent {
if depth >= DEFAULT_MAX_PAGE_TREE_DEPTH {
return Err(ConvertError::PdfError(format!(
"AcroForm field-tree depth limit {DEFAULT_MAX_PAGE_TREE_DEPTH} exceeded"
)));
}
if !seen.insert(pr) {
break;
}
match pdf.resolve_borrowed(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,
}
depth += 1;
}
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;
crate::pages::page_refs(pdf)?;
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_borrowed(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_borrowed(r).map_err(ConvertError::from)? {
Object::Dictionary(d) => d.clone(),
_ => {
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_borrowed(r).map_err(ConvertError::from)? {
Object::Array(arr) => arr.clone(),
_ => 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 {
let rest = tz_str.strip_prefix('-')?;
parse_tz_offset('-', rest)?
};
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 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_borrowed(filespec_ref)
.map_err(ConvertError::from)?;
let filespec_dict = match filespec_obj {
Object::Dictionary(d) => d.clone(),
_ => {
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_borrowed(*r).map_err(ConvertError::from)? {
Object::Dictionary(d) => Some(d.clone()),
_ => 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_borrowed(stream_ref)
.map_err(ConvertError::from)?;
let stream_dict = match stream_obj {
Object::Stream(s) => s.dict.clone(),
_ => 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_borrowed(*r).map_err(ConvertError::from)? {
Object::Dictionary(d) => Some(d.clone()),
_ => 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_borrowed(catalog_ref)
.map_err(ConvertError::from)?;
let names_val = match catalog {
Object::Dictionary(d) => d.get("Names").cloned(),
_ => return Ok(JsonValue::Object(vec![])),
};
let names_dict = match names_val {
Some(Object::Dictionary(d)) => d.clone(),
Some(Object::Reference(r)) => match pdf.resolve_borrowed(r).map_err(ConvertError::from)? {
Object::Dictionary(d) => d.clone(),
_ => return Ok(JsonValue::Object(vec![])),
},
_ => return Ok(JsonValue::Object(vec![])),
};
let ef_root = match names_dict.get("EmbeddedFiles").cloned() {
Some(v) => v,
None => return Ok(JsonValue::Object(vec![])),
};
let mut raw_entries: Vec<(String, FilespecSource)> = crate::name_number_tree::read_name_tree(
pdf,
ef_root,
|_, v| {
Ok(match v {
Object::Reference(r) => Some(FilespecSource::Indirect(r)),
Object::Dictionary(d) => Some(FilespecSource::Direct(d)),
_ => None,
})
},
DEFAULT_MAX_PAGE_TREE_DEPTH,
)
.map_err(ConvertError::from)?
.into_iter()
.map(|(key_bytes, source)| {
let name = decode_pdf_text_string(&key_bytes)
.unwrap_or_else(|| String::from_utf8_lossy(&key_bytes).into_owned());
(name, source)
})
.collect();
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_borrowed(r).map_err(ConvertError::from)? {
Object::Dictionary(d) => Some(d.clone()),
_ => 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,
Outlines,
Pagelabels,
Pages,
Qpdf,
}
impl JsonKey {
pub const ALL_NAMES: &'static [&'static str] = &[
"acroform",
"attachments",
"encrypt",
"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),
"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::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> {
build_qpdf_json_v2_selected_with_options(pdf, decode_level, stream_mode, &[])
}
fn json_section_selected(keys: &[JsonKey], section: JsonKey) -> bool {
keys.is_empty()
|| keys
.iter()
.any(|key| key.output_key_name() == section.output_key_name())
}
pub fn build_qpdf_json_v2_selected_with_options<R: Read + Seek>(
pdf: &mut Pdf<R>,
decode_level: DecodeLevel,
stream_mode: &StreamDataMode,
keys: &[JsonKey],
) -> Result<JsonValue, ConvertError> {
build_qpdf_json_v2_selected_objects_with_options(pdf, decode_level, stream_mode, keys, &[])
}
pub fn build_qpdf_json_v2_selected_objects_with_options<R: Read + Seek>(
pdf: &mut Pdf<R>,
decode_level: DecodeLevel,
stream_mode: &StreamDataMode,
keys: &[JsonKey],
objects: &[JsonObjectSelector],
) -> Result<JsonValue, ConvertError> {
let mut pairs = match build_envelope(decode_level) {
JsonValue::Object(p) => p,
_ => unreachable!("build_envelope always returns an Object"),
};
if json_section_selected(keys, JsonKey::Pages) {
let pages = build_pages_section(pdf)?;
pairs.push(("pages".to_string(), pages));
}
if json_section_selected(keys, JsonKey::Pagelabels) {
let pagelabels = build_pagelabels_section(pdf)?;
pairs.push(("pagelabels".to_string(), pagelabels));
}
if json_section_selected(keys, JsonKey::Acroform) {
let acroform = build_acroform_section(pdf)?;
pairs.push(("acroform".to_string(), acroform));
}
if json_section_selected(keys, JsonKey::Attachments) {
let attachments = build_attachments_section(pdf)?;
pairs.push(("attachments".to_string(), attachments));
}
if json_section_selected(keys, JsonKey::Encrypt) {
let encrypt = build_encrypt_section(pdf)?;
pairs.push(("encrypt".to_string(), encrypt));
}
if json_section_selected(keys, JsonKey::Outlines) {
let outlines = build_outlines_section(pdf)?;
pairs.push(("outlines".to_string(), outlines));
}
if json_section_selected(keys, JsonKey::Qpdf) {
let prepared = pdf.prepare_qpdf_json_objects()?;
let qpdf_metadata = QpdfMetadata {
pdf_version: pdf.version().to_string(),
max_object_id: prepared.max_object_id,
pushed_inherited_page_resources: false,
called_get_all_pages: pdf.ever_called_get_all_pages(),
};
let qpdf = build_qpdf_key_selected_with_stream_mode(
pdf,
qpdf_metadata,
decode_level,
stream_mode,
objects,
&prepared.refs,
)?; 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")
}
fn empty_pdf() -> Pdf<std::io::Cursor<Vec<u8>>> {
use std::io::Cursor;
let mut bytes = Vec::new();
bytes.extend_from_slice(b"%PDF-1.4\n");
let off1 = bytes.len() as u64;
bytes.extend_from_slice(b"1 0 obj\n<< /Type /Catalog >>\nendobj\n");
let xref = bytes.len() as u64;
bytes.extend_from_slice(
format!(
"xref\n0 2\n0000000000 65535 f \n{off1:010} 00000 n \ntrailer\n<< /Size 2 /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n"
)
.as_bytes(),
);
Pdf::open(Cursor::new(bytes)).expect("open")
}
fn parent_chain(
pdf: &mut Pdf<std::io::Cursor<Vec<u8>>>,
start: u32,
len: u32,
key: &str,
) -> Dictionary {
for i in 0..len {
let num = start + i;
let mut d = Dictionary::new();
if i + 1 < len {
d.insert(
"Parent",
Object::Reference(crate::ObjectRef::new(num + 1, 0)),
);
} else {
d.insert(key, Object::Integer(42));
}
pdf.set_object(crate::ObjectRef::new(num, 0), Object::Dictionary(d));
}
let mut start_dict = Dictionary::new();
start_dict.insert("Parent", Object::Reference(crate::ObjectRef::new(start, 0)));
start_dict
}
#[test]
fn inherited_field_value_errors_on_excessive_parent_depth() {
use crate::pages::DEFAULT_MAX_PAGE_TREE_DEPTH;
let mut pdf = empty_pdf();
let start_dict = parent_chain(&mut pdf, 2, (DEFAULT_MAX_PAGE_TREE_DEPTH as u32) + 5, "V");
let err = inherited_field_value(&mut pdf, &start_dict, "V");
assert!(matches!(err, Err(ConvertError::PdfError(_))));
}
#[test]
fn inherited_field_value_resolves_within_limit() {
let mut pdf = empty_pdf();
let start_dict = parent_chain(&mut pdf, 2, 4, "V");
let got = inherited_field_value(&mut pdf, &start_dict, "V").unwrap();
assert_eq!(got, Some(Object::Integer(42)));
}
#[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 qpdf_utf8_value_decodes_all_qpdf_string_encodings() {
assert_eq!(qpdf_utf8_value(b"plain"), b"plain");
assert_eq!(
qpdf_utf8_value(&[0xef, 0xbb, 0xbf, 0xe5, 0x90, 0x8d]),
"名".as_bytes()
);
assert_eq!(
qpdf_utf8_value(&[0xfe, 0xff, 0x54, 0x0d, 0x52, 0x4d]),
"名前".as_bytes()
);
assert_eq!(
qpdf_utf8_value(&[0xff, 0xfe, 0x0d, 0x54, 0x4d, 0x52]),
"名前".as_bytes()
);
assert_eq!(qpdf_utf8_value(&[0x95]), "Ł".as_bytes());
}
#[test]
fn qpdf_utf8_value_replaces_undefined_pdfdoc_byte() {
assert_eq!(
qpdf_utf8_value(&[b'a', 0xad, b'b']),
"a\u{fffd}b".as_bytes()
);
}
#[test]
fn qpdf_utf8_value_preserves_invalid_explicit_utf8_bytes() {
assert_eq!(qpdf_utf8_value(&[0xef, 0xbb, 0xbf, 0xff]), &[0xff]);
}
#[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_too_dense_falls_back_to_binary() {
let result = pdf_object_to_json(&Object::String(vec![b'A', 0xC7, b'B'])).unwrap();
assert_eq!(result, JsonValue::String("b:41c742".to_string()));
}
#[test]
fn object_string_pdfdoc_high_byte_sparse_decodes_as_text() {
let bytes: Vec<u8> = b"the quick"
.iter()
.copied()
.chain(std::iter::once(0xC7u8))
.chain(b"brown!!".iter().copied())
.collect();
let result = pdf_object_to_json(&Object::String(bytes)).unwrap();
assert_eq!(
result,
JsonValue::String("u:the quick\u{00C7}brown!!".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_drops_trailing_byte() {
let bytes = vec![0xFE, 0xFF, 0x00, 0x41, 0x00];
let result = pdf_object_to_json(&Object::String(bytes)).unwrap();
assert_eq!(result, JsonValue::String("u:A".to_string()));
}
#[test]
fn object_string_random_md5_emits_hex() {
let bytes = vec![
0xd4, 0x1d, 0x8c, 0xd9, 0x8f, 0x00, 0xb2, 0x04, 0xe9, 0x80, 0x09, 0x98, 0xec, 0xf8,
0x42, 0x7e,
];
let result = pdf_object_to_json(&Object::String(bytes)).unwrap();
assert_eq!(
result,
JsonValue::String("b:d41d8cd98f00b204e9800998ecf8427e".to_string())
);
}
#[test]
fn object_string_single_x1e_forces_hex() {
let result = pdf_object_to_json(&Object::String(vec![b'A', 0x1E, b'B'])).unwrap();
assert_eq!(result, JsonValue::String("b:411e42".to_string()));
}
#[test]
fn object_string_del_0x7f_forces_hex() {
let result = pdf_object_to_json(&Object::String(vec![b'A', 0x7F, b'B'])).unwrap();
assert_eq!(result, JsonValue::String("b:417f42".to_string()));
}
#[test]
fn object_string_explicit_utf8_bom_decodes() {
let bytes = vec![0xEF, 0xBB, 0xBF, b'A', b'B'];
let result = pdf_object_to_json(&Object::String(bytes)).unwrap();
assert_eq!(result, JsonValue::String("u:AB".to_string()));
}
#[test]
fn object_string_explicit_utf8_bom_non_ascii() {
let bytes = vec![0xEF, 0xBB, 0xBF, b'c', b'a', b'f', 0xC3, 0xA9];
let result = pdf_object_to_json(&Object::String(bytes)).unwrap();
assert_eq!(result, JsonValue::String("u:café".to_string()));
}
#[test]
fn object_string_with_nul_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 collect_image_refs_keeps_only_indirect_image_streams() {
let mut pdf = load_one_page_pdf();
let page_ref = ObjectRef::new(3, 0);
let image_ref = ObjectRef::new(99, 0);
let mut image_dict = Dictionary::new();
image_dict.insert("Subtype", Object::Name(b"Image".to_vec()));
pdf.set_object(
image_ref,
Object::Stream(Stream::new(image_dict, Vec::new())),
);
let mut xobjects = Dictionary::new();
xobjects.insert(
"Direct",
Object::Stream(Stream::new(Dictionary::new(), Vec::new())),
);
xobjects.insert("Im", Object::Reference(image_ref));
let mut resources = Dictionary::new();
resources.insert("XObject", Object::Dictionary(xobjects));
let Object::Dictionary(mut page) = pdf.resolve(page_ref).expect("resolve page") else {
panic!("page must be a dictionary"); };
page.insert("Resources", Object::Dictionary(resources));
pdf.set_object(page_ref, Object::Dictionary(page));
assert_eq!(
collect_image_refs(&mut pdf, page_ref).expect("collect images"),
vec!["99 0 R"]
);
}
#[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_borrowed(catalog_ref).expect("resolve catalog") {
Object::Dictionary(d) => d.clone(),
_ => 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_indirect_label_value_resolved() {
let mut pdf = load_one_page_pdf();
let label_ref = crate::ObjectRef::new(900, 0);
let mut label = Dictionary::new();
label.insert("S", Object::Name("D".into()));
pdf.set_object(label_ref, Object::Dictionary(label));
let pagelabels = Object::Dictionary({
let mut d = Dictionary::new();
d.insert(
"Nums",
Object::Array(vec![Object::Integer(0), Object::Reference(label_ref)]),
);
d
});
patch_pagelabels(&mut pdf, pagelabels);
let result = build_pagelabels_section(&mut pdf).expect("build_pagelabels_section failed");
assert!(
matches!(&result, JsonValue::Array(arr) if arr.len() == 1),
"indirect label value must resolve to one entry, got {result:?}"
);
}
#[test]
fn pagelabels_non_dict_value_skipped() {
let mut pdf = load_one_page_pdf();
let pagelabels = Object::Dictionary({
let mut d = Dictionary::new();
d.insert(
"Nums",
Object::Array(vec![Object::Integer(0), Object::Integer(42)]),
);
d
});
patch_pagelabels(&mut pdf, pagelabels);
let result = build_pagelabels_section(&mut pdf).expect("build_pagelabels_section failed");
assert_eq!(
result,
JsonValue::Array(vec![]),
"non-dict label value yields no entries"
);
}
#[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"
]
);
}
fn load_repairable_outline_pdf() -> Pdf<std::io::Cursor<Vec<u8>>> {
let objects = [
"<< /Type /Catalog /Pages 2 0 R /Outlines 4 0 R /Names << /Dests << /Kids [8 0 R] >> >> >>",
"<< /Type /Pages /Kids [3 0 R] /Count 1 >>",
"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] >>",
"<< /Type /Outlines /First 5 0 R /Last 5 0 R /Count 1 >>",
"<< /Title (One) /Parent 4 0 R /Dest (shape) >>",
"null",
"null",
"<< /Names [(shape) [3 0 R /Fit]] >>",
];
let mut bytes = b"%PDF-1.7\n".to_vec();
let mut offsets = Vec::with_capacity(objects.len());
for (index, object) in objects.iter().enumerate() {
offsets.push(bytes.len());
bytes
.extend_from_slice(format!("{} 0 obj\n{}\nendobj\n", index + 1, object).as_bytes());
}
let start_xref = bytes.len();
bytes.extend_from_slice(format!("xref\n0 {}\n", objects.len() + 1).as_bytes());
bytes.extend_from_slice(b"0000000000 65535 f \n");
for offset in offsets {
bytes.extend_from_slice(format!("{offset:010} 00000 n \n").as_bytes());
}
bytes.extend_from_slice(
format!(
"trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{start_xref}\n%%EOF\n",
objects.len() + 1
)
.as_bytes(),
);
Pdf::open(std::io::Cursor::new(bytes)).unwrap()
}
fn top_level_key_names(value: &JsonValue) -> Vec<&str> {
let JsonValue::Object(pairs) = value else {
panic!("expected top-level JSON object"); };
pairs.iter().map(|(key, _)| key.as_str()).collect()
}
fn qpdf_object_value<'a>(value: &'a JsonValue, object: &str) -> &'a JsonValue {
let JsonValue::Object(top) = value else {
panic!("expected top-level JSON object"); };
let JsonValue::Array(qpdf) = value_for_key(top, "qpdf") else {
panic!("expected qpdf array"); };
let JsonValue::Object(objects) = &qpdf[1] else {
panic!("expected qpdf object map"); };
let JsonValue::Object(entry) = value_for_key(objects, object) else {
panic!("expected qpdf object entry"); };
value_for_key(entry, "value")
}
fn direct_dests_root(pdf: &mut Pdf<std::io::Cursor<Vec<u8>>>) -> Dictionary {
let Object::Dictionary(catalog) = pdf.resolve(crate::ObjectRef::new(1, 0)).unwrap() else {
panic!("catalog must be a dictionary"); };
let Some(Object::Dictionary(names)) = catalog.get("Names") else {
panic!("catalog /Names must be a direct dictionary"); };
let Some(Object::Dictionary(dests)) = names.get("Dests") else {
panic!("/Names /Dests must be a direct dictionary"); };
dests.clone()
}
#[test]
fn selected_qpdf_skips_outline_repair_and_preserves_raw_objects() {
let mut pdf = load_repairable_outline_pdf();
let before = pdf.resolve(crate::ObjectRef::new(1, 0)).unwrap().clone();
let json = build_qpdf_json_v2_selected_with_options(
&mut pdf,
DecodeLevel::Generalized,
&StreamDataMode::None,
&[JsonKey::Qpdf],
)
.unwrap();
assert_eq!(
top_level_key_names(&json),
["version", "parameters", "qpdf"]
);
assert!(pdf.repair_diagnostics().entries().is_empty());
assert_eq!(pdf.resolve(crate::ObjectRef::new(1, 0)).unwrap(), before);
assert_eq!(
qpdf_object_value(&json, "obj:1 0 R"),
&pdf_object_to_json(&before).unwrap()
);
}
#[test]
fn selected_outlines_repairs_only_the_requested_section() {
let mut pdf = load_repairable_outline_pdf();
let json = build_qpdf_json_v2_selected_with_options(
&mut pdf,
DecodeLevel::Generalized,
&StreamDataMode::None,
&[JsonKey::Outlines],
)
.unwrap();
assert_eq!(
top_level_key_names(&json),
["version", "parameters", "outlines"]
);
assert_eq!(pdf.repair_diagnostics().entries().len(), 1);
let dests = direct_dests_root(&mut pdf);
assert!(dests.get("Kids").is_none());
assert!(matches!(dests.get("Names"), Some(Object::Array(_))));
}
#[test]
fn selected_outlines_precede_qpdf_and_raw_objects_reflect_repair() {
let mut pdf = load_repairable_outline_pdf();
let json = build_qpdf_json_v2_selected_with_options(
&mut pdf,
DecodeLevel::Generalized,
&StreamDataMode::None,
&[JsonKey::Qpdf, JsonKey::Outlines],
)
.unwrap();
assert_eq!(
top_level_key_names(&json),
["version", "parameters", "outlines", "qpdf"]
);
assert_eq!(pdf.repair_diagnostics().entries().len(), 1);
let repaired_catalog = pdf.resolve(crate::ObjectRef::new(1, 0)).unwrap().clone();
assert_eq!(
qpdf_object_value(&json, "obj:1 0 R"),
&pdf_object_to_json(&repaired_catalog).unwrap()
);
}
#[test]
fn selected_json_section_matrix_preserves_v2_order() {
let cases = vec![
(
vec![],
vec![
"version",
"parameters",
"pages",
"pagelabels",
"acroform",
"attachments",
"encrypt",
"outlines",
"qpdf",
],
),
(vec![JsonKey::Pages], vec!["version", "parameters", "pages"]),
(
vec![JsonKey::Pagelabels],
vec!["version", "parameters", "pagelabels"],
),
(
vec![JsonKey::Acroform],
vec!["version", "parameters", "acroform"],
),
(
vec![JsonKey::Attachments],
vec!["version", "parameters", "attachments"],
),
(
vec![JsonKey::Encrypt],
vec!["version", "parameters", "encrypt"],
),
(
vec![JsonKey::Outlines],
vec!["version", "parameters", "outlines"],
),
(vec![JsonKey::Qpdf], vec!["version", "parameters", "qpdf"]),
(
vec![JsonKey::Qpdf, JsonKey::Outlines, JsonKey::Qpdf],
vec!["version", "parameters", "outlines", "qpdf"],
),
];
for (keys, expected) in cases {
let mut pdf = load_one_page_pdf();
let json = build_qpdf_json_v2_selected_with_options(
&mut pdf,
DecodeLevel::Generalized,
&StreamDataMode::None,
&keys,
)
.unwrap();
assert_eq!(top_level_key_names(&json), expected, "keys={keys:?}");
}
}
fn selected_qpdf_metadata(json: &JsonValue) -> &JsonValue {
let JsonValue::Object(top) = json else {
panic!("top-level JSON must be an object"); };
let qpdf = top
.iter()
.find(|(key, _)| key == "qpdf")
.map(|(_, value)| value)
.expect("selected document must contain qpdf");
let JsonValue::Array(qpdf) = qpdf else {
panic!("qpdf must be an array"); };
qpdf.first().expect("qpdf metadata element")
}
#[test]
fn selected_json_metadata_reflects_actual_page_enumeration() {
let cases = [
("qpdf only", vec![JsonKey::Qpdf], false),
(
"attachments then qpdf",
vec![JsonKey::Attachments, JsonKey::Qpdf],
false,
),
(
"encrypt then qpdf",
vec![JsonKey::Encrypt, JsonKey::Qpdf],
false,
),
("pages then qpdf", vec![JsonKey::Pages, JsonKey::Qpdf], true),
(
"pagelabels then qpdf",
vec![JsonKey::Pagelabels, JsonKey::Qpdf],
true,
),
(
"acroform then qpdf",
vec![JsonKey::Acroform, JsonKey::Qpdf],
true,
),
(
"outlines then qpdf",
vec![JsonKey::Outlines, JsonKey::Qpdf],
true,
),
(
"request order does not change construction order",
vec![JsonKey::Qpdf, JsonKey::Attachments, JsonKey::Pages],
true,
),
("full document", vec![], true),
];
for (label, keys, called_get_all_pages) in cases {
let mut pdf = load_one_page_pdf();
let pdf_version = pdf.version().to_string();
let max_object_id = pdf
.object_refs()
.iter()
.map(|reference| reference.number)
.max()
.unwrap_or(0);
let json = build_qpdf_json_v2_selected_with_options(
&mut pdf,
DecodeLevel::Generalized,
&StreamDataMode::None,
&keys,
)
.unwrap();
assert_eq!(
selected_qpdf_metadata(&json),
&JsonValue::Object(vec![
("jsonversion".to_string(), JsonValue::Integer(2)),
("pdfversion".to_string(), JsonValue::String(pdf_version)),
(
"pushedinheritedpageresources".to_string(),
JsonValue::Bool(false),
),
(
"calledgetallpages".to_string(),
JsonValue::Bool(called_get_all_pages),
),
(
"maxobjectid".to_string(),
JsonValue::Integer(i64::from(max_object_id)),
),
]),
"{label}: keys={keys:?}"
);
}
}
#[test]
fn qpdf_dangling_body_reference_participates_in_maxobjectid_for_trailer_selection() {
let mut pdf = load_fixture_pdf("dangling-body-one-page.pdf");
let json = build_qpdf_json_v2_selected_with_options(
&mut pdf,
DecodeLevel::Generalized,
&StreamDataMode::None,
&[JsonKey::Qpdf],
)
.expect("build selected qpdf JSON");
assert_eq!(
selected_qpdf_metadata(&json),
&JsonValue::Object(vec![
("jsonversion".to_string(), JsonValue::Integer(2)),
(
"pdfversion".to_string(),
JsonValue::String("1.3".to_string()),
),
(
"pushedinheritedpageresources".to_string(),
JsonValue::Bool(false),
),
("calledgetallpages".to_string(), JsonValue::Bool(false),),
("maxobjectid".to_string(), JsonValue::Integer(99)),
])
);
}
fn build_qpdf_dangling_xref_pdf(
catalog_extra: &str,
extra_objects: &[(u32, u16, &str)],
free_entries: &[(u32, u16)],
size: u32,
) -> Vec<u8> {
build_qpdf_dangling_xref_pdf_with_trailer(
catalog_extra,
"",
extra_objects,
free_entries,
size,
)
}
fn build_qpdf_dangling_xref_pdf_with_trailer(
catalog_extra: &str,
trailer_extra: &str,
extra_objects: &[(u32, u16, &str)],
free_entries: &[(u32, u16)],
size: u32,
) -> Vec<u8> {
let mut bytes = b"%PDF-1.7\n".to_vec();
let mut entries = vec![
(
1u32,
0u16,
format!("<< /Type /Catalog /Pages 2 0 R {catalog_extra} >>"),
),
(
2,
0,
"<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_string(),
),
(
3,
0,
"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 10 10] >>".to_string(),
),
];
entries.extend(
extra_objects
.iter()
.map(|(number, generation, body)| (*number, *generation, (*body).to_string())),
);
entries.sort_by_key(|(number, generation, _)| (*number, *generation));
let mut offsets = Vec::new();
for (number, generation, body) in &entries {
offsets.push((*number, *generation, bytes.len()));
bytes.extend_from_slice(
format!("{number} {generation} obj\n{body}\nendobj\n").as_bytes(),
);
}
let xref = bytes.len();
bytes.extend_from_slice(b"xref\n0 1\n0000000000 65535 f \n");
for (number, generation, offset) in offsets {
bytes.extend_from_slice(
format!("{number} 1\n{offset:010} {generation:05} n \n").as_bytes(),
);
}
for (number, generation) in free_entries {
bytes.extend_from_slice(
format!("{number} 1\n0000000000 {generation:05} f \n").as_bytes(),
);
}
bytes.extend_from_slice(
format!(
"trailer\n<< /Size {size} /Root 1 0 R {trailer_extra} >>\nstartxref\n{xref}\n%%EOF\n"
)
.as_bytes(),
);
bytes
}
fn last_startxref(bytes: &[u8]) -> u64 {
let marker = b"startxref\n";
let start = bytes
.windows(marker.len())
.rposition(|window| window == marker)
.expect("startxref marker")
+ marker.len();
let end = bytes[start..]
.iter()
.position(|byte| *byte == b'\n')
.map(|length| start + length)
.expect("startxref newline");
std::str::from_utf8(&bytes[start..end])
.unwrap()
.parse()
.unwrap()
}
fn append_classic_increment(
bytes: &mut Vec<u8>,
objects: &[(u32, u16, &str)],
free_entries: &[(u32, u16)],
size: u32,
trailer_extra: &str,
previous_xref: u64,
) -> u64 {
let mut offsets = Vec::new();
for (number, generation, body) in objects {
offsets.push((*number, *generation, bytes.len()));
bytes.extend_from_slice(
format!("{number} {generation} obj\n{body}\nendobj\n").as_bytes(),
);
}
let xref = bytes.len() as u64;
bytes.extend_from_slice(b"xref\n");
for (number, generation, offset) in offsets {
bytes.extend_from_slice(
format!("{number} 1\n{offset:010} {generation:05} n \n").as_bytes(),
);
}
for (number, generation) in free_entries {
bytes.extend_from_slice(
format!("{number} 1\n0000000000 {generation:05} f \n").as_bytes(),
);
}
bytes.extend_from_slice(
format!(
"trailer\n<< /Size {size} /Root 1 0 R /Prev {previous_xref} {trailer_extra} >>\nstartxref\n{xref}\n%%EOF\n"
)
.as_bytes(),
);
xref
}
fn two_revision_historical_trailer_pdf() -> Vec<u8> {
let mut bytes = build_qpdf_dangling_xref_pdf_with_trailer("", "/Info 99 0 R", &[], &[], 4);
let previous = last_startxref(&bytes);
append_classic_increment(&mut bytes, &[(4, 0, "null")], &[], 5, "", previous);
bytes
}
fn three_revision_historical_trailer_pdf() -> Vec<u8> {
let mut bytes = build_qpdf_dangling_xref_pdf_with_trailer(
"",
"/Info 99 0 R /OldGen 88 4 R /Freed 20 7 R /Zero 0 0 R /BadGen 77 65535 R",
&[],
&[],
4,
);
let oldest = last_startxref(&bytes);
let middle = append_classic_increment(
&mut bytes,
&[(4, 0, "null")],
&[],
5,
"/Info 60 1 R /Middle 70 3 R",
oldest,
);
append_classic_increment(
&mut bytes,
&[(5, 0, "null")],
&[(20, 7), (200, 7)],
201,
"/Newest 50 2 R",
middle,
);
bytes
}
fn historical_xref_stream_trailer_pdf_with_free_generation(free_generation: u16) -> Vec<u8> {
let mut bytes = b"%PDF-1.7\n".to_vec();
let mut offsets = Vec::new();
for (number, body) in [
(1u32, "<< /Type /Catalog /Pages 2 0 R >>"),
(2, "<< /Type /Pages /Kids [3 0 R] /Count 1 >>"),
(3, "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 10 10] >>"),
] {
offsets.push(bytes.len() as u32);
bytes.extend_from_slice(format!("{number} 0 obj\n{body}\nendobj\n").as_bytes());
}
let xref_stream_offset = bytes.len() as u32;
let mut entries = Vec::new();
for (kind, offset, generation) in [
(0u8, 0u32, u16::MAX),
(1, offsets[0], 0),
(1, offsets[1], 0),
(1, offsets[2], 0),
(1, xref_stream_offset, 0),
] {
entries.push(kind);
entries.extend_from_slice(&offset.to_be_bytes());
entries.extend_from_slice(&generation.to_be_bytes());
}
bytes.extend_from_slice(
format!(
"4 0 obj\n<< /Type /XRef /Size 5 /Root 1 0 R /Info 99 0 R /Gen 88 4 R /W [1 4 2] /Index [0 5] /Length {} >>\nstream\n",
entries.len()
)
.as_bytes(),
);
bytes.extend_from_slice(&entries);
bytes.extend_from_slice(
format!("\nendstream\nendobj\nstartxref\n{xref_stream_offset}\n%%EOF\n").as_bytes(),
);
append_classic_increment(
&mut bytes,
&[(5, 0, "null")],
&[(4, free_generation)],
6,
"",
u64::from(xref_stream_offset),
);
bytes
}
fn historical_xref_stream_trailer_pdf() -> Vec<u8> {
historical_xref_stream_trailer_pdf_with_free_generation(1)
}
fn latest_xref_stream_pdf() -> Vec<u8> {
let bytes = historical_xref_stream_trailer_pdf();
let eof = bytes
.windows(b"%%EOF\n".len())
.position(|window| window == b"%%EOF\n")
.expect("first xref stream eof")
+ b"%%EOF\n".len();
bytes[..eof].to_vec()
}
fn reused_historical_xref_stream_pdf() -> Vec<u8> {
let mut bytes = latest_xref_stream_pdf();
let previous = last_startxref(&bytes);
append_classic_increment(
&mut bytes,
&[(4, 0, "<< /Marker /New >>"), (5, 0, "null")],
&[],
6,
"",
previous,
);
bytes
}
fn repeated_historical_xref_stream_pdf() -> Vec<u8> {
let mut bytes = b"%PDF-1.7\n".to_vec();
let mut offsets = Vec::new();
for (number, body) in [
(1u32, "<< /Type /Catalog /Pages 2 0 R >>"),
(2, "<< /Type /Pages /Kids [3 0 R] /Count 1 >>"),
(3, "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 10 10] >>"),
] {
offsets.push(bytes.len() as u32);
bytes.extend_from_slice(format!("{number} 0 obj\n{body}\nendobj\n").as_bytes());
}
let append_xref_stream = |bytes: &mut Vec<u8>,
marker: &str,
info: u32,
previous: Option<u64>| {
let xref_stream_offset = bytes.len() as u32;
let mut entries = Vec::new();
for (kind, offset, generation) in [
(0u8, 0u32, u16::MAX),
(1, offsets[0], 0),
(1, offsets[1], 0),
(1, offsets[2], 0),
(1, xref_stream_offset, 0),
] {
entries.push(kind);
entries.extend_from_slice(&offset.to_be_bytes());
entries.extend_from_slice(&generation.to_be_bytes());
}
let prev = previous.map_or_else(String::new, |value| format!("/Prev {value} "));
bytes.extend_from_slice(
format!(
"4 0 obj\n<< /Type /XRef /Size 5 /Root 1 0 R /Marker /{marker} /Info {info} 0 R {prev}/W [1 4 2] /Index [0 5] /Length {} >>\nstream\n",
entries.len()
)
.as_bytes(),
);
bytes.extend_from_slice(&entries);
bytes.extend_from_slice(
format!("\nendstream\nendobj\nstartxref\n{xref_stream_offset}\n%%EOF\n").as_bytes(),
);
u64::from(xref_stream_offset)
};
let oldest = append_xref_stream(&mut bytes, "Old", 91, None);
let nearest = append_xref_stream(&mut bytes, "Near", 92, Some(oldest));
append_classic_increment(&mut bytes, &[(5, 0, "null")], &[(4, 1)], 6, "", nearest);
bytes
}
fn circular_historical_trailer_pdf() -> Vec<u8> {
let mut bytes = build_qpdf_dangling_xref_pdf_with_trailer(
"",
"/Info 99 0 R /Prev 0000000000",
&[],
&[],
4,
);
let old_xref = last_startxref(&bytes);
let latest_xref =
append_classic_increment(&mut bytes, &[(4, 0, "null")], &[], 5, "", old_xref);
let marker = b"/Prev 0000000000";
let start = bytes
.windows(marker.len())
.position(|window| window == marker)
.expect("old /Prev placeholder")
+ b"/Prev ".len();
bytes[start..start + 10].copy_from_slice(format!("{latest_xref:010}").as_bytes());
bytes
}
#[test]
fn qpdf_dangling_preparation_does_not_leak_missing_refs_to_public_enumeration() {
let mut pdf = load_fixture_pdf("dangling-body-one-page.pdf");
let dangling = crate::ObjectRef::new(99, 0);
let prepared = pdf
.prepare_qpdf_json_objects()
.expect("prepare qpdf objects");
assert!(prepared.refs.contains(&dangling));
assert_eq!(prepared.max_object_id, 99);
assert!(!pdf.object_refs().contains(&dangling));
assert!(!pdf.live_object_refs().contains(&dangling));
}
#[test]
fn qpdf_dangling_preparation_excludes_unreferenced_high_free_xref_entry() {
let bytes = build_qpdf_dangling_xref_pdf("", &[], &[(200, 7)], 201);
let mut pdf = crate::Pdf::open_mem_owned(bytes).expect("open high-free fixture");
let prepared = pdf
.prepare_qpdf_json_objects()
.expect("prepare qpdf objects");
assert_eq!(prepared.max_object_id, 3);
assert!(!prepared
.refs
.iter()
.any(|reference| reference.number == 200));
assert!(pdf.object_refs().contains(&crate::ObjectRef::new(200, 7)));
}
#[test]
fn qpdf_dangling_preparation_includes_referenced_free_generation() {
let bytes = build_qpdf_dangling_xref_pdf("/Probe 200 7 R", &[], &[(200, 7)], 201);
let mut pdf = crate::Pdf::open_mem_owned(bytes).expect("open referenced-free fixture");
let prepared = pdf
.prepare_qpdf_json_objects()
.expect("prepare qpdf objects");
assert_eq!(prepared.max_object_id, 200);
assert!(prepared.refs.contains(&crate::ObjectRef::new(200, 7)));
assert!(!pdf
.live_object_refs()
.contains(&crate::ObjectRef::new(200, 7)));
}
#[test]
fn qpdf_dangling_preparation_keeps_live_and_dangling_generations_distinct() {
let bytes = build_qpdf_dangling_xref_pdf(
"/Live 8 1 R /Stale 8 0 R",
&[(8, 1, "<< /Value 1 >>")],
&[],
9,
);
let mut pdf = crate::Pdf::open_mem_owned(bytes).expect("open generation fixture");
let prepared = pdf
.prepare_qpdf_json_objects()
.expect("prepare qpdf objects");
assert!(prepared.refs.contains(&crate::ObjectRef::new(8, 0)));
assert!(prepared.refs.contains(&crate::ObjectRef::new(8, 1)));
assert!(!pdf
.live_object_refs()
.contains(&crate::ObjectRef::new(8, 0)));
assert!(pdf
.live_object_refs()
.contains(&crate::ObjectRef::new(8, 1)));
}
#[test]
fn qpdf_dangling_preparation_includes_valid_trailer_only_generations() {
let bytes = build_qpdf_dangling_xref_pdf_with_trailer(
"",
"/Info 99 0 R /Gen 88 4 R /Zero 0 0 R /BadGen 77 65535 R",
&[],
&[(200, 7)],
201,
);
let mut pdf = crate::Pdf::open_mem_owned(bytes).expect("open trailer-only fixture");
let prepared = pdf
.prepare_qpdf_json_objects()
.expect("prepare qpdf objects");
for dangling in [crate::ObjectRef::new(99, 0), crate::ObjectRef::new(88, 4)] {
assert!(prepared.refs.contains(&dangling), "{dangling:?}");
assert!(!pdf.object_refs().contains(&dangling), "{dangling:?}");
assert!(!pdf.live_object_refs().contains(&dangling), "{dangling:?}");
}
assert_eq!(prepared.max_object_id, 99);
assert!(!prepared.refs.contains(&crate::ObjectRef::new(0, 0)));
assert!(!prepared.refs.contains(&crate::ObjectRef::new(77, u16::MAX)));
assert!(!prepared
.refs
.iter()
.any(|reference| reference.number == 200));
assert!(pdf.object_refs().contains(&crate::ObjectRef::new(200, 7)));
}
#[test]
fn qpdf_preparation_collects_refs_from_an_older_omitted_trailer() {
let mut pdf = crate::Pdf::open_mem_owned(two_revision_historical_trailer_pdf())
.expect("open two-revision fixture");
assert!(pdf.trailer().get("Info").is_none());
let prepared = pdf
.prepare_qpdf_json_objects()
.expect("prepare qpdf objects");
let historical = crate::ObjectRef::new(99, 0);
assert_eq!(prepared.max_object_id, 99);
assert!(prepared.refs.contains(&historical));
assert!(!pdf.object_refs().contains(&historical));
assert!(!pdf.live_object_refs().contains(&historical));
}
#[test]
fn qpdf_preparation_unions_replaced_multigeneration_trailer_refs() {
let mut pdf = crate::Pdf::open_mem_owned(three_revision_historical_trailer_pdf())
.expect("open three-revision fixture");
assert!(pdf.trailer().get("Info").is_none());
assert_eq!(
pdf.trailer().get_ref("Newest"),
Some(crate::ObjectRef::new(50, 2))
);
let prepared = pdf
.prepare_qpdf_json_objects()
.expect("prepare qpdf objects");
for historical in [
crate::ObjectRef::new(99, 0),
crate::ObjectRef::new(88, 4),
crate::ObjectRef::new(20, 7),
crate::ObjectRef::new(60, 1),
crate::ObjectRef::new(70, 3),
crate::ObjectRef::new(50, 2),
] {
assert!(prepared.refs.contains(&historical), "{historical:?}");
assert!(
!pdf.live_object_refs().contains(&historical),
"{historical:?}"
);
}
assert_eq!(prepared.max_object_id, 99);
assert!(!prepared.refs.contains(&crate::ObjectRef::new(0, 0)));
assert!(!prepared.refs.contains(&crate::ObjectRef::new(77, u16::MAX)));
assert!(!prepared
.refs
.iter()
.any(|reference| reference.number == 200));
assert!(pdf.object_refs().contains(&crate::ObjectRef::new(200, 7)));
}
#[test]
fn qpdf_preparation_collects_refs_from_a_freed_old_xref_stream() {
let mut pdf = crate::Pdf::open_mem_owned(historical_xref_stream_trailer_pdf())
.expect("open mixed xref fixture");
assert!(pdf.trailer().get("Info").is_none());
let prepared = pdf
.prepare_qpdf_json_objects()
.expect("prepare qpdf objects");
assert_eq!(prepared.max_object_id, 99);
assert!(prepared.refs.contains(&crate::ObjectRef::new(99, 0)));
assert!(prepared.refs.contains(&crate::ObjectRef::new(88, 4)));
let stream_ref = crate::ObjectRef::new(4, 0);
assert!(prepared.refs.contains(&stream_ref));
assert!(!pdf.object_refs().contains(&stream_ref));
assert!(!pdf.live_object_refs().contains(&stream_ref));
assert_eq!(pdf.resolve(stream_ref).unwrap(), crate::Object::Null);
}
#[test]
fn qpdf_raw_stream_payload_uses_historical_view_and_rejects_non_streams() {
let mut pdf = crate::Pdf::open_mem_owned(historical_xref_stream_trailer_pdf())
.expect("open mixed xref fixture");
let payload = qpdf_raw_stream_payload(
&mut pdf,
crate::ObjectRef::new(4, 0),
DecodeLevel::Generalized,
)
.unwrap()
.unwrap();
assert_eq!(payload.len(), 35);
assert_eq!(
qpdf_raw_stream_payload(
&mut pdf,
crate::ObjectRef::new(99, 0),
DecodeLevel::Generalized,
)
.unwrap(),
None
);
}
#[test]
fn qpdf_preparation_keeps_old_xref_streams_freed_at_the_same_generation() {
let mut pdf =
crate::Pdf::open_mem_owned(historical_xref_stream_trailer_pdf_with_free_generation(0))
.expect("open same-generation free xref stream fixture");
let stream_ref = crate::ObjectRef::new(4, 0);
let prepared = pdf
.prepare_qpdf_json_objects()
.expect("prepare qpdf objects");
assert!(prepared.refs.contains(&stream_ref));
assert!(matches!(
qpdf_resolve_top_level_object(&mut pdf, stream_ref).unwrap(),
crate::Object::Stream(_)
));
assert_eq!(pdf.resolve(stream_ref).unwrap(), crate::Object::Null);
}
#[test]
fn qpdf_preparation_prefers_a_new_live_object_reusing_an_xref_stream_ref() {
let mut pdf = crate::Pdf::open_mem_owned(reused_historical_xref_stream_pdf())
.expect("open live-reused xref stream fixture");
let stream_ref = crate::ObjectRef::new(4, 0);
let prepared = pdf
.prepare_qpdf_json_objects()
.expect("prepare qpdf objects");
let replacement = qpdf_resolve_top_level_object(&mut pdf, stream_ref).unwrap();
assert_eq!(prepared.max_object_id, 99);
assert_eq!(
replacement.as_dict().and_then(|dict| dict.get("Marker")),
Some(&crate::Object::Name(b"New".to_vec()))
);
}
#[test]
fn qpdf_parsed_xref_streams_do_not_shadow_set_or_delete() {
for bytes in [
latest_xref_stream_pdf(),
historical_xref_stream_trailer_pdf(),
] {
let mut pdf = crate::Pdf::open_mem_owned(bytes).expect("open xref stream fixture");
let stream_ref = crate::ObjectRef::new(4, 0);
pdf.set_object(stream_ref, crate::Object::Name(b"Mutated".to_vec()));
assert_eq!(
qpdf_resolve_top_level_object(&mut pdf, stream_ref).unwrap(),
crate::Object::Name(b"Mutated".to_vec())
);
pdf.delete_object(stream_ref);
assert_eq!(
qpdf_resolve_top_level_object(&mut pdf, stream_ref).unwrap(),
crate::Object::Null
);
}
}
#[test]
fn qpdf_removed_refs_stay_removed_across_repeated_preparation_until_set() {
let cases = [
(
historical_xref_stream_trailer_pdf(),
crate::ObjectRef::new(4, 0),
),
(
historical_xref_stream_trailer_pdf(),
crate::ObjectRef::new(99, 0),
),
];
for (bytes, removed) in cases {
let mut pdf = crate::Pdf::open_mem_owned(bytes).expect("open historical fixture");
assert!(pdf
.prepare_qpdf_json_objects()
.unwrap()
.refs
.contains(&removed));
pdf.delete_object(removed);
for _ in 0..2 {
assert!(!pdf
.prepare_qpdf_json_objects()
.unwrap()
.refs
.contains(&removed));
}
pdf.set_object(removed, crate::Object::Name(b"Restored".to_vec()));
assert!(pdf
.prepare_qpdf_json_objects()
.unwrap()
.refs
.contains(&removed));
assert_eq!(
qpdf_resolve_top_level_object(&mut pdf, removed).unwrap(),
crate::Object::Name(b"Restored".to_vec())
);
}
}
#[test]
fn qpdf_removed_body_discovery_does_not_resurrect_a_missing_ref() {
let mut pdf = load_fixture_pdf("dangling-body-one-page.pdf");
let removed = crate::ObjectRef::new(99, 0);
assert!(pdf
.prepare_qpdf_json_objects()
.unwrap()
.refs
.contains(&removed));
pdf.delete_object(removed);
for _ in 0..2 {
assert!(!pdf
.prepare_qpdf_json_objects()
.unwrap()
.refs
.contains(&removed));
}
}
#[test]
fn qpdf_preparation_keeps_the_nearest_parsed_xref_stream_generation() {
let mut pdf = crate::Pdf::open_mem_owned(repeated_historical_xref_stream_pdf())
.expect("open repeated xref stream fixture");
let stream_ref = crate::ObjectRef::new(4, 0);
let prepared = pdf
.prepare_qpdf_json_objects()
.expect("prepare qpdf objects");
assert!(prepared.refs.contains(&stream_ref));
assert!(!pdf.object_refs().contains(&stream_ref));
assert!(!pdf.live_object_refs().contains(&stream_ref));
}
#[test]
fn qpdf_preparation_deduplicates_historical_refs_in_a_repaired_prev_cycle() {
let bytes = circular_historical_trailer_pdf();
assert!(crate::Pdf::open_mem_owned(bytes.clone()).is_err());
let mut pdf = crate::Pdf::open_mem_owned_with_options(
bytes,
crate::PdfOpenOptions {
repair: true,
..crate::PdfOpenOptions::default()
},
)
.expect("repair circular /Prev fixture");
assert!(pdf.trailer().get("Info").is_none());
let prepared = pdf
.prepare_qpdf_json_objects()
.expect("prepare qpdf objects");
assert_eq!(prepared.max_object_id, 99);
assert_eq!(
prepared
.refs
.iter()
.filter(|reference| **reference == crate::ObjectRef::new(99, 0))
.count(),
1
);
}
fn selected_qpdf_object_map(json: &JsonValue) -> &[(String, JsonValue)] {
let JsonValue::Object(top) = json else {
panic!("top-level JSON must be an object"); };
let JsonValue::Array(qpdf) = top
.iter()
.find(|(key, _)| key == "qpdf")
.map(|(_, value)| value)
.expect("qpdf section")
else {
panic!("qpdf section must be an array"); };
let JsonValue::Object(map) = &qpdf[1] else {
panic!("qpdf object map"); };
map
}
#[test]
fn qpdf_dangling_raw_projection_matches_qpdf_container_null_rules() {
let mut pdf = load_fixture_pdf("dangling-body-one-page.pdf");
let json = build_qpdf_json_v2_selected_with_options(
&mut pdf,
DecodeLevel::Generalized,
&StreamDataMode::None,
&[JsonKey::Qpdf],
)
.expect("build qpdf JSON");
let map = selected_qpdf_object_map(&json);
let obj4 = map
.iter()
.find(|(key, _)| key == "obj:4 0 R")
.map(|(_, value)| value)
.expect("catalog object");
assert_eq!(
obj4,
&JsonValue::Object(vec![(
"value".to_string(),
JsonValue::Object(vec![
(
"/ArrZero".to_string(),
JsonValue::Array(vec![JsonValue::Null]),
),
("/Nested".to_string(), JsonValue::Object(Vec::new()),),
(
"/PageMode".to_string(),
JsonValue::String("/UseNone".to_string()),
),
("/Pages".to_string(), JsonValue::String("6 0 R".to_string()),),
(
"/Type".to_string(),
JsonValue::String("/Catalog".to_string()),
),
]),
)])
);
assert_eq!(
map.iter()
.find(|(key, _)| key == "obj:99 0 R")
.map(|(_, value)| value),
Some(&JsonValue::Object(vec![(
"value".to_string(),
JsonValue::Null,
)]))
);
}
#[test]
fn qpdf_dangling_raw_selectors_filter_serialization_after_full_preparation() {
let cases = [
(
"trailer",
vec![JsonObjectSelector::Trailer],
vec!["trailer"],
),
(
"dangling generation",
vec![JsonObjectSelector::Object {
number: 99,
generation: 0,
}],
vec!["obj:99 0 R"],
),
];
for (label, selectors, expected_keys) in cases {
let mut pdf = load_fixture_pdf("dangling-body-one-page.pdf");
let json = build_qpdf_json_v2_selected_objects_with_options(
&mut pdf,
DecodeLevel::Generalized,
&StreamDataMode::None,
&[JsonKey::Qpdf],
&selectors,
)
.expect("build selected objects");
let JsonValue::Object(metadata) = selected_qpdf_metadata(&json) else {
panic!("qpdf metadata must be an object"); };
assert_eq!(
metadata
.iter()
.find(|(key, _)| key == "maxobjectid")
.map(|(_, value)| value),
Some(&JsonValue::Integer(99)),
"{label}"
);
assert_eq!(
selected_qpdf_object_map(&json)
.iter()
.map(|(key, _)| key.as_str())
.collect::<Vec<_>>(),
expected_keys,
"{label}"
);
}
}
#[test]
fn qpdf_json_helpers_cover_reference_cycles_nulls_and_nested_streams() {
let mut pdf = load_one_page_pdf();
let first = ObjectRef::new(80, 0);
let second = ObjectRef::new(81, 0);
pdf.set_object(first, Object::Reference(second));
pdf.set_object(second, Object::Reference(first));
assert!(crate::qpdf_null::reference_is_null(&mut pdf, first).unwrap());
assert_eq!(
qpdf_resolve_top_level_object(&mut pdf, first).unwrap(),
Object::Null
);
let mut nested_dict = Dictionary::new();
nested_dict.insert("Drop", Object::Null);
let nested_stream = Object::Stream(Stream::new(nested_dict, Vec::new()));
assert_eq!(
qpdf_pdf_object_to_json(&mut pdf, &nested_stream).unwrap(),
JsonValue::Object(vec![(
"stream".to_string(),
JsonValue::Object(vec![("dict".to_string(), JsonValue::Object(Vec::new()),)]),
)])
);
}
#[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 load_direct_outline_fixture() -> Pdf<std::io::Cursor<Vec<u8>>> {
let bytes = include_bytes!(concat!(
env!("CARGO_MANIFEST_DIR"),
"/../../tests/fixtures/json-diff/direct-outlines.pdf"
));
Pdf::open(std::io::Cursor::new(bytes.to_vec())).unwrap()
}
fn value_for_key<'a>(pairs: &'a [(String, JsonValue)], key: &str) -> &'a JsonValue {
&pairs.iter().find(|(name, _)| name == key).unwrap().1
}
fn json_array(value: &JsonValue) -> &[JsonValue] {
match value {
JsonValue::Array(items) => items,
_ => panic!("expected JSON array"), }
}
fn json_object(value: &JsonValue) -> &[(String, JsonValue)] {
match value {
JsonValue::Object(pairs) => pairs,
_ => panic!("expected JSON object"), }
}
#[test]
fn outline_json_v2_has_exact_qpdf_keys_and_values() {
let mut pdf = load_direct_outline_fixture();
let result = build_outlines_section(&mut pdf).unwrap();
let entries = json_array(&result);
let first = json_object(&entries[0]);
let keys: Vec<_> = first.iter().map(|(key, _)| key.as_str()).collect();
assert_eq!(
keys,
[
"dest",
"destpageposfrom1",
"kids",
"object",
"open",
"title"
]
);
assert_eq!(
value_for_key(first, "dest"),
&JsonValue::Array(vec![
JsonValue::String("8 0 R".into()),
JsonValue::String("/XYZ".into()),
JsonValue::Null,
JsonValue::Null,
JsonValue::Null,
])
);
assert_eq!(
value_for_key(first, "destpageposfrom1"),
&JsonValue::Integer(6)
);
assert_eq!(
value_for_key(first, "object"),
&JsonValue::String("96 0 R".into())
);
assert_eq!(value_for_key(first, "open"), &JsonValue::Bool(true));
assert_eq!(
value_for_key(first, "title"),
&JsonValue::String("Isís 1 -> 5: /XYZ null null null".into())
);
let kids = json_array(value_for_key(first, "kids"));
assert_eq!(kids.len(), 2);
let first_kid = json_object(&kids[0]);
let second_kid = json_object(&kids[1]);
assert_eq!(
value_for_key(first_kid, "title"),
&JsonValue::String("Amanda 1.1 -> 11: /Fit".into())
);
assert_eq!(value_for_key(first_kid, "open"), &JsonValue::Bool(false));
assert_eq!(
value_for_key(second_kid, "title"),
&JsonValue::String("Sandy ÷Σανδι÷ 1.2 -> 13: /FitH 792".into())
);
}
#[test]
fn outline_json_v2_projects_direct_items_exactly() {
let mut pdf = load_one_page_pdf();
let page_ref = crate::pages::page_refs(&mut pdf).unwrap()[0];
let mut next = Dictionary::new();
next.insert("Title", Object::String(b"Direct B".to_vec()));
let mut first = Dictionary::new();
first.insert("Count", Object::Integer(-1));
first.insert(
"Dest",
Object::Array(vec![
Object::Reference(page_ref),
Object::Name(b"Fit".to_vec()),
]),
);
first.insert("Next", Object::Dictionary(next));
first.insert("Title", Object::String(b"Direct A".to_vec()));
let mut outlines = Dictionary::new();
outlines.insert("First", Object::Dictionary(first));
let catalog_ref = pdf.root_ref().unwrap();
let mut catalog = pdf.resolve(catalog_ref).unwrap().as_dict().unwrap().clone();
catalog.insert("Outlines", Object::Dictionary(outlines));
pdf.set_object(catalog_ref, Object::Dictionary(catalog));
let result = build_outlines_section(&mut pdf).unwrap();
let entries = json_array(&result);
assert_eq!(entries.len(), 2);
let first = json_object(&entries[0]);
let second = json_object(&entries[1]);
assert_eq!(
value_for_key(first, "object"),
&JsonValue::Object(vec![
("/Count".into(), JsonValue::Integer(-1)),
(
"/Dest".into(),
JsonValue::Array(vec![
JsonValue::String(page_ref.to_string()),
JsonValue::String("/Fit".into()),
]),
),
(
"/Next".into(),
JsonValue::Object(vec![(
"/Title".into(),
JsonValue::String("u:Direct B".into()),
)]),
),
("/Title".into(), JsonValue::String("u:Direct A".into())),
])
);
assert_eq!(
value_for_key(first, "destpageposfrom1"),
&JsonValue::Integer(1)
);
assert_eq!(value_for_key(first, "open"), &JsonValue::Bool(false));
assert_eq!(
value_for_key(first, "title"),
&JsonValue::String("Direct A".into())
);
assert_eq!(value_for_key(second, "dest"), &JsonValue::Null);
assert_eq!(value_for_key(second, "destpageposfrom1"), &JsonValue::Null);
assert_eq!(
value_for_key(second, "object"),
&JsonValue::Object(vec![(
"/Title".into(),
JsonValue::String("u:Direct B".into()),
)])
);
assert_eq!(value_for_key(second, "open"), &JsonValue::Bool(true));
assert_eq!(
value_for_key(second, "title"),
&JsonValue::String("Direct B".into())
);
}
#[test]
fn outline_json_v2_stops_at_an_indirect_null_child() {
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 null_child_ref = crate::ObjectRef::new(102, 0);
let mut outline_root = Dictionary::new();
outline_root.insert("First", 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"Parent".to_vec()));
item.insert("First", Object::Reference(null_child_ref));
pdf.set_object(item_ref, Object::Dictionary(item));
pdf.set_object(null_child_ref, Object::Null);
let result = build_outlines_section(&mut pdf).unwrap();
let entries = json_array(&result);
let parent = json_object(&entries[0]);
assert_eq!(value_for_key(parent, "kids"), &JsonValue::Array(Vec::new()));
}
#[test]
fn outline_json_v2_resolves_a_multi_hop_catalog_dest_holder() {
let mut pdf = load_one_page_pdf();
let page_ref = crate::pages::page_refs(&mut pdf).unwrap()[0];
let outline_root_ref = crate::ObjectRef::new(100, 0);
let item_ref = crate::ObjectRef::new(101, 0);
let first_holder_ref = crate::ObjectRef::new(110, 0);
let dests_ref = crate::ObjectRef::new(111, 0);
let mut outline_root = Dictionary::new();
outline_root.insert("First", 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"Named".to_vec()));
item.insert("Dest", Object::Name(b"named".to_vec()));
pdf.set_object(item_ref, Object::Dictionary(item));
let mut dests = Dictionary::new();
dests.insert(
"named",
Object::Array(vec![
Object::Reference(page_ref),
Object::Name(b"Fit".to_vec()),
]),
);
pdf.set_object(first_holder_ref, Object::Reference(dests_ref));
pdf.set_object(dests_ref, Object::Dictionary(dests));
let catalog_ref = pdf.root_ref().unwrap();
let mut catalog = pdf.resolve(catalog_ref).unwrap().as_dict().unwrap().clone();
catalog.insert("Dests", Object::Reference(first_holder_ref));
pdf.set_object(catalog_ref, Object::Dictionary(catalog));
let result = build_outlines_section(&mut pdf).unwrap();
let entries = json_array(&result);
let item = json_object(&entries[0]);
assert_eq!(
value_for_key(item, "dest"),
&JsonValue::Array(vec![
JsonValue::String(page_ref.to_string()),
JsonValue::String("/Fit".into()),
])
);
assert_eq!(
value_for_key(item, "destpageposfrom1"),
&JsonValue::Integer(1)
);
}
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_borrowed(catalog_ref).expect("resolve catalog") {
Object::Dictionary(d) => d.clone(),
_ => 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![
"dest",
"destpageposfrom1",
"kids",
"object",
"open",
"title"
],
"key order must be alphabetical"
);
assert_eq!(entry[0].1, JsonValue::Null, "dest must be Null");
assert_eq!(entry[1].1, JsonValue::Null, "page position must be Null");
assert_eq!(entry[2].1, JsonValue::Array(vec![]), "kids must be empty");
assert_eq!(
entry[3].1,
JsonValue::String("101 0 R".to_string()),
"object mismatch"
);
assert_eq!(entry[4].1, JsonValue::Bool(true), "open must default true");
assert_eq!(
entry[5].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_nested_child_next_cycle_guard_prevents_infinite_loop() {
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 child_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(parent_ref));
outline_root.insert("Last", Object::Reference(parent_ref));
patch_outline_root(&mut pdf, outline_root_ref, outline_root);
let mut parent = Dictionary::new();
parent.insert("Title", Object::String(b"Parent".to_vec()));
parent.insert("Parent", Object::Reference(outline_root_ref));
parent.insert("First", Object::Reference(child_ref));
parent.insert("Last", Object::Reference(child_ref));
parent.insert("Count", Object::Integer(1));
pdf.set_object(parent_ref, Object::Dictionary(parent));
let mut child = Dictionary::new();
child.insert("Title", Object::String(b"Loop".to_vec()));
child.insert("Parent", Object::Reference(parent_ref));
child.insert("Next", Object::Reference(child_ref));
pdf.set_object(child_ref, Object::Dictionary(child));
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, "root chain must contain the parent");
let JsonValue::Object(parent_entry) = &entries[0] else {
panic!("parent entry is not an Object"); };
let kids = parent_entry
.iter()
.find(|(key, _)| key == "kids")
.map(|(_, value)| value)
.expect("parent must contain kids");
let JsonValue::Array(kids) = kids else {
panic!("kids is not an Array"); };
assert_eq!(
kids.len(),
1,
"nested /Next cycle guard must stop before a duplicate child"
);
}
#[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_non_goto_action_yields_null_dest() {
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");
};
assert_eq!(value_for_key(entry, "dest"), &JsonValue::Null);
assert_eq!(
value_for_key(entry, "object"),
&JsonValue::String("101 0 R".to_string())
);
assert!(entry.iter().all(|(key, _)| key != "action"));
}
#[test]
fn outlines_goto_action_without_destination_yields_null_dest() {
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");
};
assert_eq!(value_for_key(entry, "dest"), &JsonValue::Null);
assert_eq!(
value_for_key(entry, "object"),
&JsonValue::String("101 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_borrowed(catalog_ref).expect("resolve catalog") {
Object::Dictionary(d) => d.clone(),
_ => 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_borrowed(catalog_ref).expect("resolve catalog") {
Object::Dictionary(d) => d.clone(),
_ => 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_names_without_embedded_files_returns_empty() {
let mut pdf = load_one_page_pdf();
let catalog_ref = pdf.root_ref().expect("no /Root");
let mut catalog = pdf
.resolve_borrowed(catalog_ref)
.expect("resolve catalog")
.as_dict()
.expect("catalog dict")
.clone();
let mut names = Dictionary::new();
names.insert("Dests", Object::Dictionary(Dictionary::new()));
catalog.insert("Names", Object::Dictionary(names));
pdf.set_object(catalog_ref, Object::Dictionary(catalog));
let result = build_attachments_section(&mut pdf).expect("build_attachments_section failed");
assert_eq!(result, JsonValue::Object(vec![]), "expected empty object");
}
#[test]
fn attachments_non_ref_non_dict_value_skipped() {
let mut pdf = load_one_page_pdf();
let ef_root_ref = crate::ObjectRef::new(901, 0);
let mut ef_root = Dictionary::new();
ef_root.insert(
"Names",
Object::Array(vec![Object::String(b"weird".to_vec()), Object::Integer(7)]),
);
pdf.set_object(ef_root_ref, Object::Dictionary(ef_root));
let names_ref = crate::ObjectRef::new(902, 0);
let mut names = Dictionary::new();
names.insert("EmbeddedFiles", Object::Reference(ef_root_ref));
pdf.set_object(names_ref, Object::Dictionary(names));
let catalog_ref = pdf.root_ref().expect("no /Root");
let mut catalog = pdf
.resolve_borrowed(catalog_ref)
.expect("resolve catalog")
.as_dict()
.expect("catalog dict")
.clone();
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");
assert_eq!(
result,
JsonValue::Object(vec![]),
"non-ref/non-dict leaf value must be skipped"
);
}
#[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_borrowed(catalog_ref).unwrap() {
Object::Dictionary(d) => d.clone(),
_ => 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>>>,
decode_level: DecodeLevel,
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, decode_level, 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, DecodeLevel::Generalized, &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 inner = get_obj7_stream_inner(&mut pdf, DecodeLevel::None, &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'");
assert!(
matches!(&inner[0].1, JsonValue::String(_)),
"data must be a base64 String"
);
}
#[test]
fn stream_data_mode_inline_decode_level_none_emits_raw_bytes() {
let mut pdf = load_one_page_pdf();
let oref = crate::ObjectRef::new(7, 0);
let raw_bytes = match pdf.resolve(oref).expect("resolve obj:7") {
Object::Stream(s) => s.data.clone(),
other => panic!("obj:7 is not a Stream: {other:?}"),
};
let inner = get_obj7_stream_inner(&mut pdf, DecodeLevel::None, &StreamDataMode::Inline);
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,
"DecodeLevel::None must emit the raw filter-encoded stream bytes"
);
}
#[test]
fn stream_data_mode_inline_decode_level_generalized_emits_decoded_bytes() {
let mut pdf = load_one_page_pdf();
let inner =
get_obj7_stream_inner(&mut pdf, DecodeLevel::Generalized, &StreamDataMode::Inline);
let JsonValue::String(b64) = &inner[0].1 else {
panic!("data is not a String");
};
let decoded = base64_decode_test_helper(b64);
let expected_prefix: &[u8] =
b"1 0 0 1 0 0 cm BT /F1 12 Tf 14.4 TL ET\nBT 1 0 0 1 72 720 Tm";
assert!(
decoded.starts_with(expected_prefix),
"DecodeLevel::Generalized must emit filter-decoded content; got {:?}",
String::from_utf8_lossy(&decoded[..decoded.len().min(64)])
);
}
#[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,
DecodeLevel::Generalized,
&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-7".to_string()));
}
#[test]
fn format_json_side_file_path_uses_bare_object_number() {
assert_eq!(format_json_side_file_path("qp", 7), "qp-7");
assert_eq!(format_json_side_file_path("qp", 42), "qp-42");
assert_eq!(format_json_side_file_path("qp", 100), "qp-100");
}
#[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, DecodeLevel::Generalized, 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 build_qpdf_json_v2_with_options_threads_decode_level_to_qpdf_key() {
fn obj7_inline_data(decode_level: DecodeLevel) -> String {
let mut pdf = load_one_page_pdf();
let v2 =
build_qpdf_json_v2_with_options(&mut pdf, decode_level, &StreamDataMode::Inline)
.expect("build failed");
let JsonValue::Object(top) = &v2 else {
panic!("top is not Object");
};
let qpdf = top
.iter()
.find(|(k, _)| k == "qpdf")
.map(|(_, v)| v)
.expect("qpdf key");
let JsonValue::Array(arr) = qpdf else {
panic!("qpdf not Array");
};
let JsonValue::Object(obj_map) = &arr[1] else {
panic!("qpdf[1] not Object");
};
let obj7 = obj_map
.iter()
.find(|(k, _)| k == "obj:7 0 R")
.map(|(_, v)| v)
.expect("obj:7");
let JsonValue::Object(obj7_pairs) = obj7 else {
panic!("obj:7 not Object");
};
let JsonValue::Object(stream_inner) = &obj7_pairs[0].1 else {
panic!("stream not Object");
};
let JsonValue::String(b64) = &stream_inner[0].1 else {
panic!("data not String");
};
b64.clone()
}
let none_b64 = obj7_inline_data(DecodeLevel::None);
let generalized_b64 = obj7_inline_data(DecodeLevel::Generalized);
assert_ne!(
none_b64, generalized_b64,
"DecodeLevel must reach the qpdf key: None and Generalized must differ \
for a filtered stream"
);
let generalized = base64_decode_test_helper(&generalized_b64);
assert!(
generalized.starts_with(b"1 0 0 1 0 0 cm BT /F1 12 Tf"),
"Generalized must emit filter-decoded content via build_qpdf_json_v2_with_options"
);
}
#[test]
fn stream_payload_decode_level_none_returns_raw() {
let mut dict = Dictionary::new();
dict.insert("Filter", Object::Name(b"FlateDecode".to_vec()));
let raw_payload = b"raw payload";
let encoded = crate::filters::encode_stream_data(&dict, raw_payload).expect("encode");
let stream = Stream::new(dict, encoded.clone());
let payload = stream_payload_for_decode_level(&stream, DecodeLevel::None);
assert!(
matches!(payload, Cow::Borrowed(_)),
"DecodeLevel::None must borrow stream.data, not allocate a copy"
);
assert_eq!(
&*payload,
&encoded[..],
"DecodeLevel::None must return the raw filter-encoded bytes verbatim"
);
}
#[test]
fn stream_payload_decode_level_generalized_decodes_filters() {
let mut dict = Dictionary::new();
dict.insert("Filter", Object::Name(b"FlateDecode".to_vec()));
let raw_payload = b"decode me through the filter pipeline";
let encoded = crate::filters::encode_stream_data(&dict, raw_payload).expect("encode");
let stream = Stream::new(dict, encoded);
assert_eq!(
&*stream_payload_for_decode_level(&stream, DecodeLevel::Generalized),
raw_payload,
"DecodeLevel::Generalized must return filter-decoded content"
);
}
#[test]
fn stream_payload_unsupported_filter_falls_back_to_raw() {
let mut dict = Dictionary::new();
dict.insert("Filter", Object::Name(b"DCTDecode".to_vec()));
let raw_payload = b"\xff\xd8\xff\xe0 not really a jpeg";
let stream = Stream::new(dict, raw_payload.to_vec());
let payload = stream_payload_for_decode_level(&stream, DecodeLevel::Generalized);
assert!(
matches!(payload, Cow::Borrowed(_)),
"an undecodable filter must fall back to a borrow of the raw bytes"
);
assert_eq!(
&*payload, raw_payload,
"an undecodable filter must fall back to the raw stream bytes"
);
}
#[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("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("objectinfo"), None);
assert_eq!(JsonKey::from_str("objects"), 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], "outlines");
assert_eq!(JsonKey::ALL_NAMES[4], "pagelabels");
assert_eq!(JsonKey::ALL_NAMES[5], "pages");
assert_eq!(JsonKey::ALL_NAMES[6], "qpdf");
assert_eq!(JsonKey::ALL_NAMES.len(), 7);
}
#[test]
fn json_key_output_key_name_is_direct() {
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_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_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_preserves_malformed_envelope_shapes() {
let selector = [JsonObjectSelector::Trailer];
assert_eq!(
filter_json_objects(JsonValue::Null, &selector),
JsonValue::Null
);
let scalar_qpdf = JsonValue::Object(vec![("qpdf".to_string(), JsonValue::Integer(7))]);
assert_eq!(
filter_json_objects(scalar_qpdf.clone(), &selector),
scalar_qpdf
);
let scalar_map = JsonValue::Object(vec![(
"qpdf".to_string(),
JsonValue::Array(vec![JsonValue::Null, JsonValue::Integer(9)]),
)]);
assert_eq!(
filter_json_objects(scalar_map.clone(), &selector),
scalar_map
);
}
#[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"]);
}
}