use crate::filters::{decode_stream_data, encode_stream_data};
use crate::object::{Dictionary, Object, Stream};
use crate::{Error, ObjectRef, Pdf, Result};
use md5::{Digest, Md5};
use std::io::{Read, Seek, Write};
use std::path::Path;
pub struct EmbeddedFileStream<'a, R: Read + Seek> {
stream: Stream,
params: Option<Dictionary>,
#[allow(dead_code)]
pdf: &'a mut Pdf<R>,
}
impl<'a, R: Read + Seek> EmbeddedFileStream<'a, R> {
fn new(stream: Stream, pdf: &'a mut Pdf<R>) -> Result<Self> {
let params = match stream.dict.get("Params") {
Some(Object::Dictionary(d)) => Some(d.clone()),
Some(Object::Reference(r)) => {
let r = *r;
match pdf.resolve(r)? {
Object::Dictionary(d) => Some(d),
_ => None,
}
}
_ => None,
};
Ok(Self {
stream,
params,
pdf,
})
}
pub fn payload(&self) -> Result<Vec<u8>> {
decode_stream_data(&self.stream.dict, &self.stream.data)
}
pub fn mimetype(&self) -> Result<Option<Vec<u8>>> {
Ok(self
.stream
.dict
.get("Subtype")
.and_then(Object::as_name)
.map(ToOwned::to_owned))
}
fn params(&self) -> Option<&Dictionary> {
self.params.as_ref()
}
pub fn creation_date(&self) -> Result<Option<Vec<u8>>> {
Ok(self
.params()
.and_then(|p| p.get("CreationDate"))
.and_then(Object::as_string)
.map(ToOwned::to_owned))
}
pub fn modification_date(&self) -> Result<Option<Vec<u8>>> {
Ok(self
.params()
.and_then(|p| p.get("ModDate"))
.and_then(Object::as_string)
.map(ToOwned::to_owned))
}
pub fn checksum(&self) -> Result<Option<Vec<u8>>> {
Ok(self
.params()
.and_then(|p| p.get("CheckSum"))
.and_then(Object::as_string)
.map(ToOwned::to_owned))
}
pub fn size(&self) -> Result<Option<i64>> {
Ok(self
.params()
.and_then(|p| p.get("Size"))
.and_then(Object::as_integer))
}
}
pub struct FileSpec<'a, R: Read + Seek> {
filespec_ref: ObjectRef,
pdf: &'a mut Pdf<R>,
}
impl<'a, R: Read + Seek> FileSpec<'a, R> {
pub fn new(filespec_ref: ObjectRef, pdf: &'a mut Pdf<R>) -> Self {
Self { filespec_ref, pdf }
}
fn resolve_dict(&mut self) -> Result<Dictionary> {
match self.pdf.resolve(self.filespec_ref)? {
Object::Dictionary(d) => Ok(d),
_ => Err(Error::Unsupported(format!(
"expected /Filespec dictionary at {}, got a non-dictionary object",
self.filespec_ref
))),
}
}
pub fn filename(&mut self) -> Result<Option<Vec<u8>>> {
let dict = self.resolve_dict()?;
Ok(dict
.get("F")
.and_then(Object::as_string)
.map(ToOwned::to_owned))
}
pub fn uf(&mut self) -> Result<Option<Vec<u8>>> {
let dict = self.resolve_dict()?;
Ok(dict
.get("UF")
.and_then(Object::as_string)
.map(ToOwned::to_owned))
}
pub fn description(&mut self) -> Result<Option<Vec<u8>>> {
let dict = self.resolve_dict()?;
Ok(dict
.get("Desc")
.and_then(Object::as_string)
.map(ToOwned::to_owned))
}
pub fn af_relationship(&mut self) -> Result<Option<Vec<u8>>> {
let dict = self.resolve_dict()?;
Ok(dict
.get("AFRelationship")
.and_then(Object::as_name)
.map(ToOwned::to_owned))
}
pub fn embedded_file(&mut self) -> Result<Option<EmbeddedFileStream<'_, R>>> {
let dict = self.resolve_dict()?;
let ef_dict: Dictionary = match dict.get("EF") {
Some(Object::Dictionary(d)) => d.clone(),
Some(Object::Reference(r)) => {
let r = *r;
match self.pdf.resolve(r)? {
Object::Dictionary(d) => d,
_ => return Ok(None),
}
}
_ => return Ok(None),
};
let candidates: Vec<ObjectRef> = ["UF", "F", "Unix", "Mac", "DOS"]
.iter()
.filter_map(|k| ef_dict.get(k).and_then(Object::as_ref_id))
.collect();
for ef_ref in candidates {
if let Object::Stream(stream) = self.pdf.resolve(ef_ref)? {
return EmbeddedFileStream::new(stream, self.pdf).map(Some);
}
}
Ok(None)
}
}
pub fn encode_utf16be(s: &str) -> Vec<u8> {
let mut out = vec![0xFE_u8, 0xFF]; for unit in s.encode_utf16() {
out.push((unit >> 8) as u8);
out.push((unit & 0xFF) as u8);
}
out
}
pub fn format_pdf_date(year: u16, month: u8, day: u8, hour: u8, minute: u8, second: u8) -> Vec<u8> {
format!(
"D:{:04}{:02}{:02}{:02}{:02}{:02}Z",
year, month, day, hour, minute, second
)
.into_bytes()
}
pub fn md5_checksum(data: &[u8]) -> Vec<u8> {
let mut hasher = Md5::new();
hasher.update(data);
hasher.finalize().to_vec()
}
#[derive(Debug, Clone, Default)]
pub struct FileParamDates {
pub creation: Option<(u16, u8, u8, u8, u8, u8)>,
pub modification: Option<(u16, u8, u8, u8, u8, u8)>,
}
pub struct FileSpecBuilder {
filename: Vec<u8>,
uf_filename: Option<String>,
payload: Vec<u8>,
mimetype: Option<Vec<u8>>,
description: Option<Vec<u8>>,
af_relationship: Option<Vec<u8>>,
dates: FileParamDates,
compress: bool,
}
impl FileSpecBuilder {
pub fn new(filename: impl AsRef<[u8]>, payload: impl Into<Vec<u8>>) -> Self {
Self {
filename: filename.as_ref().to_vec(),
uf_filename: None,
payload: payload.into(),
mimetype: None,
description: None,
af_relationship: None,
dates: FileParamDates::default(),
compress: false,
}
}
pub fn compress(mut self, compress: bool) -> Self {
self.compress = compress;
self
}
pub fn uf_filename(mut self, filename: impl AsRef<str>) -> Self {
self.uf_filename = Some(filename.as_ref().to_string());
self
}
pub fn mimetype(mut self, mime: impl AsRef<[u8]>) -> Self {
self.mimetype = Some(mime.as_ref().to_vec());
self
}
pub fn description(mut self, desc: impl AsRef<[u8]>) -> Self {
self.description = Some(desc.as_ref().to_vec());
self
}
pub fn af_relationship(mut self, rel: impl AsRef<[u8]>) -> Self {
self.af_relationship = Some(rel.as_ref().to_vec());
self
}
pub fn dates(mut self, dates: FileParamDates) -> Self {
self.dates = dates;
self
}
pub fn build<R: Read + Seek>(self, pdf: &mut Pdf<R>) -> Result<ObjectRef> {
let next = pdf
.object_refs()
.iter()
.map(|r| r.number)
.max()
.unwrap_or(0);
let stream_ref = ObjectRef::new(next + 1, 0);
let filespec_ref = ObjectRef::new(next + 2, 0);
let checksum = md5_checksum(&self.payload);
let size = self.payload.len() as i64;
let mut params = Dictionary::new();
params.insert("Size", Object::Integer(size));
params.insert("CheckSum", Object::String(checksum));
if let Some((y, mo, d, h, mi, s)) = self.dates.creation {
params.insert(
"CreationDate",
Object::String(format_pdf_date(y, mo, d, h, mi, s)),
);
}
if let Some((y, mo, d, h, mi, s)) = self.dates.modification {
params.insert(
"ModDate",
Object::String(format_pdf_date(y, mo, d, h, mi, s)),
);
}
let mut ef_dict = Dictionary::new();
ef_dict.insert("Type", Object::Name(b"EmbeddedFile".to_vec()));
if let Some(ref mime) = self.mimetype {
ef_dict.insert("Subtype", Object::Name(mime.clone()));
}
let (stream_payload, stored_length) = if self.compress {
let mut enc_dict = Dictionary::new();
enc_dict.insert("Filter", Object::Name(b"FlateDecode".to_vec()));
let encoded = encode_stream_data(&enc_dict, &self.payload)?;
ef_dict.insert("Filter", Object::Name(b"FlateDecode".to_vec()));
let encoded_len = encoded.len() as i64;
(encoded, encoded_len)
} else {
(self.payload, size)
};
ef_dict.insert("Length", Object::Integer(stored_length));
ef_dict.insert("Params", Object::Dictionary(params));
let ef_stream = Stream::new(ef_dict, stream_payload);
pdf.set_object(stream_ref, Object::Stream(ef_stream));
let mut ef_sub = Dictionary::new();
ef_sub.insert("F", Object::Reference(stream_ref));
ef_sub.insert("UF", Object::Reference(stream_ref));
let uf_filename = match self.uf_filename {
Some(filename) => filename,
None => std::str::from_utf8(&self.filename)
.map_err(|_| {
Error::Unsupported(
"FileSpecBuilder: filename is not valid UTF-8; cannot encode /UF"
.to_string(),
)
})?
.to_string(),
};
let uf_bytes = encode_utf16be(&uf_filename);
let mut fs_dict = Dictionary::new();
fs_dict.insert("Type", Object::Name(b"Filespec".to_vec()));
fs_dict.insert("F", Object::String(self.filename));
fs_dict.insert("UF", Object::String(uf_bytes));
fs_dict.insert("EF", Object::Dictionary(ef_sub));
if let Some(desc) = self.description {
fs_dict.insert("Desc", Object::String(desc));
}
if let Some(rel) = self.af_relationship {
fs_dict.insert("AFRelationship", Object::Name(rel));
}
pdf.set_object(filespec_ref, Object::Dictionary(fs_dict));
Ok(filespec_ref)
}
}
pub fn add_attachment_from_path<R, P>(pdf: &mut Pdf<R>, key: &[u8], path: P) -> Result<ObjectRef>
where
R: Read + Seek,
P: AsRef<Path>,
{
let path = path.as_ref();
let basename = path
.file_name()
.ok_or_else(|| {
Error::Unsupported(format!(
"add_attachment_from_path: path has no basename: {}",
path.display()
))
})?
.to_str()
.ok_or_else(|| {
Error::Unsupported(format!(
"add_attachment_from_path: basename is not valid UTF-8: {}",
path.display()
))
})?;
let raw = std::fs::read(path)?;
let filespec_ref = FileSpecBuilder::new(ascii_filename_fallback(basename), raw)
.uf_filename(basename)
.compress(true)
.build(pdf)?;
crate::embedded_files::insert_embedded_file(pdf, key, filespec_ref)?;
Ok(filespec_ref)
}
pub fn ascii_filename_fallback(filename: &str) -> Vec<u8> {
let fallback: String = filename
.chars()
.map(|ch| {
if ch.is_ascii_alphanumeric() || matches!(ch, '.' | '_' | '-') {
ch
} else {
'_'
}
})
.collect();
if fallback.is_empty() || fallback.bytes().all(|b| b == b'.' || b == b'_') {
b"attachment".to_vec()
} else {
fallback.into_bytes()
}
}
pub fn extract_attachment<R: Read + Seek>(pdf: &mut Pdf<R>, key: &[u8]) -> Result<Vec<u8>> {
let entries = crate::embedded_files::list_embedded_files(pdf)?;
let filespec_ref = match entries.iter().find(|(k, _)| k.as_slice() == key) {
Some((_, r)) => *r,
None => {
let mut available: Vec<String> = entries
.iter()
.map(|(k, _)| String::from_utf8_lossy(k).into_owned())
.collect();
available.sort_unstable();
let hint = if available.is_empty() {
" (no attachments present)".to_string()
} else {
format!(" (available keys: {})", available.join(", "))
};
return Err(Error::Unsupported(format!(
"extract_attachment: key {:?} not found{}",
String::from_utf8_lossy(key),
hint,
)));
}
};
let mut fs = FileSpec::new(filespec_ref, pdf);
let ef = fs.embedded_file()?.ok_or_else(|| {
Error::Unsupported(format!(
"extract_attachment: key {:?} has no resolvable /EmbeddedFile stream \
(the /EF sub-dictionary may be absent or malformed)",
String::from_utf8_lossy(key),
))
})?;
ef.payload()
}
pub fn write_attachment<R: Read + Seek, W: Write>(
pdf: &mut Pdf<R>,
key: &[u8],
out: &mut W,
) -> Result<()> {
let bytes = extract_attachment(pdf, key)?;
out.write_all(&bytes)?;
Ok(())
}
pub fn extract_attachment_to_path<R, P>(pdf: &mut Pdf<R>, key: &[u8], path: P) -> Result<()>
where
R: Read + Seek,
P: AsRef<Path>,
{
let bytes = extract_attachment(pdf, key)?;
std::fs::write(path, &bytes)?;
Ok(())
}
fn sanitize_imported_object<R: Read + Seek>(
source: &mut Pdf<R>,
value: &mut Object,
visited: &mut std::collections::BTreeSet<ObjectRef>,
depth: usize,
max_depth: usize,
) -> Result<bool> {
if depth >= max_depth {
return Ok(false);
}
match value {
Object::Reference(r) => {
let r = *r;
if !visited.insert(r) {
return Ok(false);
}
let resolved = match source.resolve(r) {
Ok(o) => o,
Err(_) => {
visited.remove(&r);
return Ok(false);
}
};
let keep = match resolved {
Object::Stream(_) | Object::Reference(_) => false,
mut inner => {
let ok = sanitize_imported_object(
source,
&mut inner,
visited,
depth + 1,
max_depth,
)?;
if ok {
*value = inner;
}
ok
}
};
visited.remove(&r);
Ok(keep)
}
Object::Dictionary(dict) => {
let keys: Vec<Vec<u8>> = dict.iter().map(|(k, _)| k.to_vec()).collect();
for k in keys {
let Some(slot) = dict.get(k.as_slice()).cloned() else {
continue;
};
let mut v = slot;
if sanitize_imported_object(source, &mut v, visited, depth + 1, max_depth)? {
dict.insert(k.as_slice(), v);
} else {
dict.remove(k.as_slice());
}
}
Ok(true)
}
Object::Array(arr) => {
let mut out = Vec::with_capacity(arr.len());
for elem in arr.iter() {
let mut v = elem.clone();
if sanitize_imported_object(source, &mut v, visited, depth + 1, max_depth)? {
out.push(v);
}
}
*arr = out;
Ok(true)
}
_ => Ok(true),
}
}
pub fn copy_attachments_from<R1: Read + Seek, R2: Read + Seek>(
target: &mut Pdf<R1>,
source: &mut Pdf<R2>,
prefix: Option<&[u8]>,
) -> Result<usize> {
use crate::embedded_files::{
collect_embedded_file_pairs_raw, insert_embedded_file, DEFAULT_MAX_EMBEDDED_FILES_DEPTH,
};
let entries = collect_embedded_file_pairs_raw(source, DEFAULT_MAX_EMBEDDED_FILES_DEPTH)?;
if entries.is_empty() {
return Ok(0);
}
let mut count = 0usize;
for (key, value) in entries {
let fs_dict: Dictionary = match value {
Object::Reference(r) => match source.resolve(r) {
Ok(Object::Dictionary(d)) => d,
_ => continue, },
Object::Dictionary(d) => d,
_ => continue, };
let ef_dict: Dictionary = match fs_dict.get("EF") {
Some(Object::Dictionary(d)) => d.clone(),
Some(Object::Reference(r)) => {
let r = *r;
match source.resolve(r) {
Ok(Object::Dictionary(d)) => d,
_ => continue, }
}
_ => continue, };
let mut ef_stream: Stream = {
let mut found = None;
for k in &["UF", "F", "Unix", "Mac", "DOS"] {
if let Some(Object::Reference(r)) = ef_dict.get(k) {
let r = *r;
if let Ok(Object::Stream(s)) = source.resolve(r) {
found = Some(s);
break;
}
}
}
match found {
Some(s) => s,
None => continue, }
};
{
let mut dict_obj = Object::Dictionary(std::mem::take(&mut ef_stream.dict));
let mut visited = std::collections::BTreeSet::new();
sanitize_imported_object(
source,
&mut dict_obj,
&mut visited,
0,
DEFAULT_MAX_EMBEDDED_FILES_DEPTH,
)?;
if let Some(d) = dict_obj.into_dict() {
ef_stream.dict = d;
}
}
let base: u32 = target
.object_refs()
.iter()
.map(|r| r.number)
.max()
.unwrap_or(0);
let new_stream_ref = ObjectRef::new(base + 1, 0);
let new_fs_ref = ObjectRef::new(base + 2, 0);
target.set_object(new_stream_ref, Object::Stream(ef_stream));
let mut new_fs = Dictionary::new();
if let Some(t) = fs_dict.get("Type") {
new_fs.insert("Type", t.clone());
}
if let Some(f) = fs_dict.get("F") {
new_fs.insert("F", f.clone());
}
if let Some(uf) = fs_dict.get("UF") {
new_fs.insert("UF", uf.clone());
}
if let Some(desc) = fs_dict.get("Desc") {
new_fs.insert("Desc", desc.clone());
}
if let Some(rel) = fs_dict.get("AFRelationship") {
new_fs.insert("AFRelationship", rel.clone());
}
{
let mut fs_obj = Object::Dictionary(std::mem::take(&mut new_fs));
let mut visited = std::collections::BTreeSet::new();
sanitize_imported_object(
source,
&mut fs_obj,
&mut visited,
0,
DEFAULT_MAX_EMBEDDED_FILES_DEPTH,
)?;
if let Some(d) = fs_obj.into_dict() {
new_fs = d;
}
}
let mut new_ef_sub = Dictionary::new();
new_ef_sub.insert("F", Object::Reference(new_stream_ref));
new_ef_sub.insert("UF", Object::Reference(new_stream_ref));
new_fs.insert("EF", Object::Dictionary(new_ef_sub));
target.set_object(new_fs_ref, Object::Dictionary(new_fs));
let new_key: Vec<u8> = match prefix {
Some(p) => p.iter().chain(key.iter()).copied().collect(),
None => key,
};
insert_embedded_file(target, &new_key, new_fs_ref)?;
count += 1;
}
Ok(count)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::embedded_files::{insert_embedded_file, list_embedded_files};
use crate::filters::decode_stream_data;
use crate::{Object, ObjectRef, Pdf};
use std::io::Cursor;
fn minimal_pdf_bytes() -> Vec<u8> {
let mut pdf = Vec::new();
pdf.extend_from_slice(b"%PDF-1.4\n");
let off1 = pdf.len() as u64;
pdf.extend_from_slice(b"1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n");
let off2 = pdf.len() as u64;
pdf.extend_from_slice(b"2 0 obj\n<< /Type /Pages /Kids [3 0 R] /Count 1 >>\nendobj\n");
let off3 = pdf.len() as u64;
pdf.extend_from_slice(
b"3 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] >>\nendobj\n",
);
let xref_start = pdf.len() as u64;
let xref = format!(
"xref\n0 4\n0000000000 65535 f \n{:010} 00000 n \n{:010} 00000 n \n{:010} 00000 n \n",
off1, off2, off3,
);
pdf.extend_from_slice(xref.as_bytes());
let trailer =
format!("trailer\n<< /Size 4 /Root 1 0 R >>\nstartxref\n{xref_start}\n%%EOF\n");
pdf.extend_from_slice(trailer.as_bytes());
pdf
}
fn open_minimal() -> Pdf<Cursor<Vec<u8>>> {
Pdf::open(Cursor::new(minimal_pdf_bytes())).expect("open minimal PDF")
}
fn resolve_ef_stream(
pdf: &mut Pdf<Cursor<Vec<u8>>>,
fs_ref: ObjectRef,
) -> crate::object::Stream {
let fs_obj = pdf.resolve(fs_ref).expect("resolve filespec");
let Some(fs_dict) = fs_obj.into_dict() else {
panic!("expected dictionary");
};
let ef_sub = match fs_dict.get("EF") {
Some(Object::Dictionary(d)) => d.clone(),
_ => panic!("missing /EF"),
};
let stream_ref = match ef_sub.get("F") {
Some(Object::Reference(r)) => *r,
_ => panic!("missing /EF /F ref"),
};
match pdf.resolve(stream_ref).expect("resolve stream") {
Object::Stream(s) => s,
_ => panic!("expected stream"),
}
}
#[test]
fn builder_uncompressed_round_trip() {
let mut pdf = open_minimal();
let raw = b"hello world";
let fs_ref = FileSpecBuilder::new("test.txt", raw.as_ref())
.build(&mut pdf)
.expect("build");
let stream = resolve_ef_stream(&mut pdf, fs_ref);
assert!(
stream.dict.get("Filter").is_none(),
"uncompressed stream must have no /Filter"
);
let decoded = decode_stream_data(&stream.dict, &stream.data).expect("decode");
assert_eq!(decoded, raw);
}
#[test]
fn builder_compressed_has_flatedecode_filter() {
let mut pdf = open_minimal();
let raw = b"compressed payload data";
let fs_ref = FileSpecBuilder::new("data.bin", raw.as_ref())
.compress(true)
.build(&mut pdf)
.expect("build");
let stream = resolve_ef_stream(&mut pdf, fs_ref);
assert_eq!(
stream.dict.get("Filter"),
Some(&Object::Name(b"FlateDecode".to_vec())),
"/Filter must be /FlateDecode"
);
}
#[test]
fn builder_compressed_round_trip() {
let mut pdf = open_minimal();
let raw = b"The quick brown fox jumps over the lazy dog.";
let fs_ref = FileSpecBuilder::new("fox.txt", raw.as_ref())
.compress(true)
.build(&mut pdf)
.expect("build");
let stream = resolve_ef_stream(&mut pdf, fs_ref);
let decoded = decode_stream_data(&stream.dict, &stream.data).expect("decode");
assert_eq!(
decoded.as_slice(),
raw.as_ref(),
"round-trip must restore original bytes"
);
}
#[test]
fn builder_compressed_params_size_is_raw_length() {
let mut pdf = open_minimal();
let raw = b"some raw bytes for size check";
let fs_ref = FileSpecBuilder::new("size.bin", raw.as_ref())
.compress(true)
.build(&mut pdf)
.expect("build");
let stream = resolve_ef_stream(&mut pdf, fs_ref);
let params = match stream.dict.get("Params") {
Some(Object::Dictionary(d)) => d.clone(),
_ => panic!("missing /Params"),
};
let stored_size = match params.get("Size") {
Some(Object::Integer(n)) => *n,
_ => panic!("missing /Params /Size"),
};
assert_eq!(
stored_size,
raw.len() as i64,
"/Params /Size must equal raw byte length, not compressed length"
);
assert_ne!(
stream.data.len(),
raw.len(),
"compressed data length should differ from raw (sanity)"
);
}
#[test]
fn builder_compressed_params_checksum_is_md5_of_raw() {
let mut pdf = open_minimal();
let raw = b"checksum test data 12345";
let fs_ref = FileSpecBuilder::new("chk.bin", raw.as_ref())
.compress(true)
.build(&mut pdf)
.expect("build");
let stream = resolve_ef_stream(&mut pdf, fs_ref);
let params = match stream.dict.get("Params") {
Some(Object::Dictionary(d)) => d.clone(),
_ => panic!("missing /Params"),
};
let stored_checksum = match params.get("CheckSum") {
Some(Object::String(b)) => b.clone(),
_ => panic!("missing /Params /CheckSum"),
};
let expected = md5_checksum(raw);
assert_eq!(
stored_checksum, expected,
"/Params /CheckSum must be MD5 of raw bytes"
);
}
#[test]
fn builder_compressed_f_and_uf_are_basename() {
let mut pdf = open_minimal();
let raw = b"payload";
let fs_ref = FileSpecBuilder::new("myfile.txt", raw.as_ref())
.compress(true)
.build(&mut pdf)
.expect("build");
let fs_obj = pdf.resolve(fs_ref).expect("resolve filespec");
let Some(fs_dict) = fs_obj.into_dict() else {
panic!("expected dictionary");
};
let f = match fs_dict.get("F") {
Some(Object::String(b)) => b.clone(),
_ => panic!("missing /F"),
};
let uf = match fs_dict.get("UF") {
Some(Object::String(b)) => b.clone(),
_ => panic!("missing /UF"),
};
assert_eq!(f, b"myfile.txt", "/F must be the filename");
let expected_uf = encode_utf16be("myfile.txt");
assert_eq!(uf, expected_uf, "/UF must be UTF-16BE encoded filename");
}
#[test]
fn builder_allows_distinct_ascii_f_and_unicode_uf() {
let mut pdf = open_minimal();
let raw = b"payload";
let fs_ref = FileSpecBuilder::new("____.pdf", raw.as_ref())
.uf_filename("レポート.pdf")
.build(&mut pdf)
.expect("build");
let fs_obj = pdf.resolve(fs_ref).expect("resolve filespec");
let Some(fs_dict) = fs_obj.into_dict() else {
panic!("expected dictionary");
};
let f = match fs_dict.get("F") {
Some(Object::String(b)) => b.clone(),
_ => panic!("missing /F"),
};
let uf = match fs_dict.get("UF") {
Some(Object::String(b)) => b.clone(),
_ => panic!("missing /UF"),
};
assert_eq!(f, b"____.pdf", "/F must be ASCII fallback");
assert_eq!(
uf,
encode_utf16be("レポート.pdf"),
"/UF must preserve the Unicode filename"
);
}
#[test]
fn compressed_filespec_retrievable_via_list() {
let mut pdf = open_minimal();
let raw = b"retrievable payload";
let fs_ref = FileSpecBuilder::new("list-test.txt", raw.as_ref())
.compress(true)
.build(&mut pdf)
.expect("build");
insert_embedded_file(&mut pdf, b"list-test.txt", fs_ref).expect("insert");
let entries = list_embedded_files(&mut pdf).expect("list");
assert_eq!(entries.len(), 1);
assert_eq!(entries[0].0, b"list-test.txt");
assert_eq!(entries[0].1, fs_ref);
}
#[test]
fn existing_attachment_survives_second_insertion() {
let mut pdf = open_minimal();
let raw1 = b"first attachment";
let fs1 = FileSpecBuilder::new("first.txt", raw1.as_ref())
.build(&mut pdf)
.expect("build first");
insert_embedded_file(&mut pdf, b"first.txt", fs1).expect("insert first");
let raw2 = b"second attachment with more data";
let fs2 = FileSpecBuilder::new("second.txt", raw2.as_ref())
.compress(true)
.build(&mut pdf)
.expect("build second");
insert_embedded_file(&mut pdf, b"second.txt", fs2).expect("insert second");
let entries = list_embedded_files(&mut pdf).expect("list");
assert_eq!(entries.len(), 2, "both attachments must survive");
let keys: Vec<&[u8]> = entries.iter().map(|(k, _)| k.as_slice()).collect();
assert!(
keys.contains(&b"first.txt".as_ref()),
"first.txt must be present"
);
assert!(
keys.contains(&b"second.txt".as_ref()),
"second.txt must be present"
);
}
#[test]
fn add_attachment_from_path_round_trip() {
let mut pdf = open_minimal();
let dir = tempfile::tempdir().expect("tempdir");
let file_path = dir.path().join("hello.txt");
let raw = b"Hello from disk!";
std::fs::write(&file_path, raw).expect("write temp file");
let fs_ref = add_attachment_from_path(&mut pdf, b"hello.txt", &file_path).expect("attach");
let entries = list_embedded_files(&mut pdf).expect("list");
assert_eq!(entries.len(), 1);
assert_eq!(entries[0].0, b"hello.txt");
assert_eq!(entries[0].1, fs_ref);
let stream = resolve_ef_stream(&mut pdf, fs_ref);
assert_eq!(
stream.dict.get("Filter"),
Some(&Object::Name(b"FlateDecode".to_vec())),
"must use FlateDecode"
);
let decoded = decode_stream_data(&stream.dict, &stream.data).expect("decode");
assert_eq!(
decoded.as_slice(),
raw.as_ref(),
"round-trip must restore original bytes"
);
}
#[test]
fn add_attachment_from_path_checksum_and_size() {
let mut pdf = open_minimal();
let dir = tempfile::tempdir().expect("tempdir");
let file_path = dir.path().join("data.bin");
let raw = b"deterministic checksum test data";
std::fs::write(&file_path, raw).expect("write");
let fs_ref = add_attachment_from_path(&mut pdf, b"data.bin", &file_path).expect("attach");
let stream = resolve_ef_stream(&mut pdf, fs_ref);
let params = match stream.dict.get("Params") {
Some(Object::Dictionary(d)) => d.clone(),
_ => panic!("missing /Params"),
};
let size = match params.get("Size") {
Some(Object::Integer(n)) => *n,
_ => panic!("missing /Params /Size"),
};
let checksum = match params.get("CheckSum") {
Some(Object::String(b)) => b.clone(),
_ => panic!("missing /Params /CheckSum"),
};
assert_eq!(
size,
raw.len() as i64,
"/Params /Size must match raw length"
);
assert_eq!(
checksum,
md5_checksum(raw),
"/Params /CheckSum must match MD5 of raw bytes"
);
}
#[test]
fn add_attachment_from_path_f_and_uf_are_basename() {
let mut pdf = open_minimal();
let dir = tempfile::tempdir().expect("tempdir");
let file_path = dir.path().join("report.pdf");
std::fs::write(&file_path, b"fake pdf content").expect("write");
let fs_ref = add_attachment_from_path(&mut pdf, b"report.pdf", &file_path).expect("attach");
let fs_obj = pdf.resolve(fs_ref).expect("resolve");
let Some(fs_dict) = fs_obj.into_dict() else {
panic!("expected dict");
};
let f = match fs_dict.get("F") {
Some(Object::String(b)) => b.clone(),
_ => panic!("missing /F"),
};
let uf = match fs_dict.get("UF") {
Some(Object::String(b)) => b.clone(),
_ => panic!("missing /UF"),
};
assert_eq!(f, b"report.pdf", "/F must be basename");
assert_eq!(
uf,
encode_utf16be("report.pdf"),
"/UF must be UTF-16BE basename"
);
}
#[test]
fn add_attachment_from_path_errors_on_missing_file() {
let mut pdf = open_minimal();
let result =
add_attachment_from_path(&mut pdf, b"missing.txt", "/this/does/not/exist/missing.txt");
assert!(result.is_err(), "must error when file does not exist");
let err = result.unwrap_err();
assert!(
matches!(err, crate::Error::Io(_)),
"expected Io error, got: {err:?}"
);
}
#[test]
fn add_attachment_from_path_accepts_non_ascii_basename() {
let mut pdf = open_minimal();
let dir = tempfile::tempdir().expect("tempdir");
let file_path = dir.path().join("レポート.pdf");
std::fs::write(&file_path, b"payload").expect("write temp file");
let fs_ref = add_attachment_from_path(&mut pdf, "レポート.pdf".as_bytes(), &file_path)
.expect("attach non-ASCII basename");
let fs_obj = pdf.resolve(fs_ref).expect("resolve");
let Some(fs_dict) = fs_obj.into_dict() else {
panic!("expected dict");
};
let f = match fs_dict.get("F") {
Some(Object::String(b)) => b.clone(),
_ => panic!("missing /F"),
};
let uf = match fs_dict.get("UF") {
Some(Object::String(b)) => b.clone(),
_ => panic!("missing /UF"),
};
assert_eq!(f, b"____.pdf", "/F must be ASCII-safe fallback");
assert_eq!(
uf,
encode_utf16be("レポート.pdf"),
"/UF must preserve the Unicode basename"
);
}
#[test]
fn extract_attachment_small_round_trip() {
let mut pdf = open_minimal();
let dir = tempfile::tempdir().expect("tempdir");
let path = dir.path().join("small.txt");
let raw = b"Hello, world!";
std::fs::write(&path, raw).expect("write");
add_attachment_from_path(&mut pdf, b"small.txt", &path).expect("attach");
let extracted = extract_attachment(&mut pdf, b"small.txt").expect("extract");
assert_eq!(
extracted.as_slice(),
raw.as_ref(),
"small file round-trip must match"
);
}
#[test]
fn extract_attachment_large_round_trip() {
let raw: Vec<u8> = (0u8..=255).cycle().take(128 * 1024).collect();
let mut pdf = open_minimal();
let dir = tempfile::tempdir().expect("tempdir");
let path = dir.path().join("large.bin");
std::fs::write(&path, &raw).expect("write");
add_attachment_from_path(&mut pdf, b"large.bin", &path).expect("attach");
let extracted = extract_attachment(&mut pdf, b"large.bin").expect("extract");
assert_eq!(extracted, raw, "large file round-trip must match");
}
#[test]
fn extract_attachment_binary_with_nuls_round_trip() {
let raw: Vec<u8> = (0u8..=255).cycle().take(4096).collect();
let mut pdf = open_minimal();
let dir = tempfile::tempdir().expect("tempdir");
let path = dir.path().join("binary.bin");
std::fs::write(&path, &raw).expect("write");
add_attachment_from_path(&mut pdf, b"binary.bin", &path).expect("attach");
let extracted = extract_attachment(&mut pdf, b"binary.bin").expect("extract");
assert_eq!(extracted, raw, "binary file round-trip must match");
}
#[test]
fn write_attachment_to_vec_matches_extract() {
let mut pdf = open_minimal();
let dir = tempfile::tempdir().expect("tempdir");
let path = dir.path().join("vec-test.txt");
let raw = b"write_attachment test payload";
std::fs::write(&path, raw).expect("write");
add_attachment_from_path(&mut pdf, b"vec-test.txt", &path).expect("attach");
let mut buf = Vec::new();
write_attachment(&mut pdf, b"vec-test.txt", &mut buf).expect("write_attachment");
assert_eq!(
buf.as_slice(),
raw.as_ref(),
"write_attachment output must match raw"
);
}
#[test]
fn extract_attachment_to_path_round_trip() {
let mut pdf = open_minimal();
let dir = tempfile::tempdir().expect("tempdir");
let src_path = dir.path().join("source.bin");
let raw: Vec<u8> = (0u8..=255).cycle().take(2048).collect();
std::fs::write(&src_path, &raw).expect("write source");
add_attachment_from_path(&mut pdf, b"source.bin", &src_path).expect("attach");
let out_path = dir.path().join("extracted.bin");
extract_attachment_to_path(&mut pdf, b"source.bin", &out_path)
.expect("extract_attachment_to_path");
let read_back = std::fs::read(&out_path).expect("read back");
assert_eq!(read_back, raw, "extract_to_path round-trip must match");
}
#[test]
fn extract_attachment_missing_key_is_actionable_error() {
let mut pdf = open_minimal();
let dir = tempfile::tempdir().expect("tempdir");
let path = dir.path().join("real.txt");
std::fs::write(&path, b"real content").expect("write");
add_attachment_from_path(&mut pdf, b"real.txt", &path).expect("attach");
let err =
extract_attachment(&mut pdf, b"missing-key").expect_err("must error for absent key");
let msg = err.to_string();
assert!(
msg.contains("missing-key"),
"error message must contain the missing key name, got: {msg}"
);
assert!(
msg.contains("real.txt"),
"error message must list available keys, got: {msg}"
);
}
#[test]
fn extract_attachment_from_compat_fixture() {
let path = concat!(
env!("CARGO_MANIFEST_DIR"),
"/../..",
"/tests/fixtures/compat/attachment-two-page.pdf"
);
let file = std::fs::File::open(path)
.expect("compat fixture missing: tests/fixtures/compat/attachment-two-page.pdf");
let mut pdf = crate::Pdf::open(std::io::BufReader::new(file)).expect("open compat fixture");
let entries = crate::embedded_files::list_embedded_files(&mut pdf).expect("list");
assert!(
!entries.is_empty(),
"fixture must have at least one attachment"
);
let key = entries[0].0.clone();
let extracted = extract_attachment(&mut pdf, &key).expect("extract from compat fixture");
assert!(!extracted.is_empty(), "extracted bytes must be non-empty");
let mut fs = FileSpec::new(entries[0].1, &mut pdf);
let ef = fs
.embedded_file()
.expect("embedded_file")
.expect("must have embedded file");
let reported_size = ef.size().expect("size").expect("size must be present");
assert_eq!(
extracted.len() as i64,
reported_size,
"extracted length must equal /Params /Size"
);
}
#[test]
fn copy_attachments_two_files_round_trip() {
let mut source = open_minimal();
let dir = tempfile::tempdir().expect("tempdir");
let path_a = dir.path().join("alpha.txt");
let path_b = dir.path().join("beta.txt");
let raw_a = b"attachment alpha payload";
let raw_b = b"attachment beta payload";
std::fs::write(&path_a, raw_a).unwrap();
std::fs::write(&path_b, raw_b).unwrap();
add_attachment_from_path(&mut source, b"alpha.txt", &path_a).expect("add alpha");
add_attachment_from_path(&mut source, b"beta.txt", &path_b).expect("add beta");
let mut target = open_minimal();
let count = copy_attachments_from(&mut target, &mut source, None).expect("copy");
assert_eq!(count, 2, "must copy 2 attachments");
let got_a = extract_attachment(&mut target, b"alpha.txt").expect("extract alpha");
let got_b = extract_attachment(&mut target, b"beta.txt").expect("extract beta");
assert_eq!(got_a, raw_a, "alpha payload must match");
assert_eq!(got_b, raw_b, "beta payload must match");
}
#[test]
fn copy_attachments_filter_and_bytes_preserved() {
let mut source = open_minimal();
let dir = tempfile::tempdir().expect("tempdir");
let path = dir.path().join("compressed.txt");
let raw = b"some data for compression test";
std::fs::write(&path, raw).unwrap();
add_attachment_from_path(&mut source, b"compressed.txt", &path).expect("add");
let src_entries =
crate::embedded_files::list_embedded_files(&mut source).expect("list source");
let src_fs_ref = src_entries[0].1;
let src_stream = resolve_ef_stream(&mut source, src_fs_ref);
let src_filter = src_stream.dict.get("Filter").cloned();
let src_data = src_stream.data.clone();
let mut target = open_minimal();
copy_attachments_from(&mut target, &mut source, None).expect("copy");
let tgt_entries =
crate::embedded_files::list_embedded_files(&mut target).expect("list target");
assert_eq!(tgt_entries.len(), 1);
let tgt_fs_ref = tgt_entries[0].1;
let tgt_stream = resolve_ef_stream(&mut target, tgt_fs_ref);
assert_eq!(
tgt_stream.dict.get("Filter").cloned(),
src_filter,
"target /Filter must equal source /Filter"
);
assert_eq!(
tgt_stream.data, src_data,
"target stream data must be byte-identical to source"
);
let decoded =
crate::filters::decode_stream_data(&tgt_stream.dict, &tgt_stream.data).expect("decode");
assert_eq!(
decoded.as_slice(),
raw.as_ref(),
"decoded payload must match original"
);
}
#[test]
fn copy_attachments_prefix_avoids_collision() {
let mut source = open_minimal();
let dir = tempfile::tempdir().expect("tempdir");
let src_path = dir.path().join("data.txt");
std::fs::write(&src_path, b"source data").unwrap();
add_attachment_from_path(&mut source, b"data.txt", &src_path).expect("add source");
let mut target = open_minimal();
let tgt_path = dir.path().join("target_data.txt");
let original_target_content = b"target original data";
std::fs::write(&tgt_path, original_target_content).unwrap();
add_attachment_from_path(&mut target, b"data.txt", &tgt_path).expect("add target pre");
let count = copy_attachments_from(&mut target, &mut source, Some(b"src-")).expect("copy");
assert_eq!(count, 1);
let entries = crate::embedded_files::list_embedded_files(&mut target).expect("list");
assert_eq!(entries.len(), 2, "both keys must exist");
let keys: Vec<&[u8]> = entries.iter().map(|(k, _)| k.as_slice()).collect();
assert!(
keys.contains(&b"data.txt".as_ref()),
"original key must survive"
);
assert!(
keys.contains(&b"src-data.txt".as_ref()),
"prefixed key must be present"
);
let original = extract_attachment(&mut target, b"data.txt").expect("extract original");
assert_eq!(
original, original_target_content,
"original content must be intact"
);
let prefixed = extract_attachment(&mut target, b"src-data.txt").expect("extract prefixed");
assert_eq!(
prefixed, b"source data",
"prefixed entry must contain source content"
);
}
#[test]
fn copy_attachments_return_value_is_count() {
let mut source = open_minimal();
let dir = tempfile::tempdir().expect("tempdir");
for name in &["one.txt", "two.txt", "three.txt"] {
let p = dir.path().join(name);
std::fs::write(&p, name.as_bytes()).unwrap();
add_attachment_from_path(&mut source, name.as_bytes(), &p).expect("add");
}
let mut target = open_minimal();
let count = copy_attachments_from(&mut target, &mut source, None).expect("copy");
assert_eq!(
count, 3,
"return value must equal number of attachments copied"
);
}
#[test]
fn copy_attachments_empty_source_returns_zero() {
let mut source = open_minimal(); let mut target = open_minimal();
let count = copy_attachments_from(&mut target, &mut source, None).expect("copy");
assert_eq!(count, 0, "empty source must return 0");
let entries = crate::embedded_files::list_embedded_files(&mut target).expect("list");
assert_eq!(entries.len(), 0, "target must remain empty");
}
#[test]
fn copy_attachments_encrypted_source_password_open() {
let path = concat!(
env!("CARGO_MANIFEST_DIR"),
"/../..",
"/tests/fixtures/encrypted/v4-aes-128-r4.pdf"
);
let file = std::fs::File::open(path)
.expect("encrypted fixture missing: tests/fixtures/encrypted/v4-aes-128-r4.pdf");
let opts = crate::PdfOpenOptions {
password: b"user-v4-aes".to_vec(),
..crate::PdfOpenOptions::default()
};
let mut source = crate::Pdf::open_with_options(std::io::BufReader::new(file), opts)
.expect("open encrypted source");
let mut target = open_minimal();
let count =
copy_attachments_from(&mut target, &mut source, None).expect("copy from encrypted");
assert_eq!(
count, 0,
"encrypted fixture has no attachments; copy must return 0"
);
}
fn assert_no_refs(o: &Object, ctx: &str) {
match o {
Object::Reference(r) => panic!("unexpected indirect reference {r} in {ctx}"),
Object::Array(a) => a.iter().for_each(|e| assert_no_refs(e, ctx)),
Object::Dictionary(d) => d.iter().for_each(|(_, v)| assert_no_refs(v, ctx)),
Object::Stream(s) => s.dict.iter().for_each(|(_, v)| assert_no_refs(v, ctx)),
_ => {}
}
}
#[test]
fn copy_attachments_sanitizes_foreign_and_dangling_refs() {
let mut source = open_minimal();
let base = source
.object_refs()
.iter()
.map(|r| r.number)
.max()
.unwrap_or(0);
let date_ref = ObjectRef::new(base + 1, 0);
let params_ref = ObjectRef::new(base + 2, 0);
let filter_ref = ObjectRef::new(base + 3, 0);
let stream_ref = ObjectRef::new(base + 4, 0);
let fs_ref = ObjectRef::new(base + 5, 0);
let dangling = ObjectRef::new(base + 999, 0);
source.set_object(date_ref, Object::String(b"D:20260101000000Z".to_vec()));
let mut params = Dictionary::new();
params.insert("Size", Object::Integer(5));
params.insert("CreationDate", Object::Reference(date_ref)); source.set_object(params_ref, Object::Dictionary(params));
source.set_object(filter_ref, Object::Name(b"FlateDecode".to_vec()));
let raw = b"hello sanitize";
let mut enc_dict = Dictionary::new();
enc_dict.insert("Filter", Object::Name(b"FlateDecode".to_vec()));
let encoded = encode_stream_data(&enc_dict, raw).expect("encode");
let mut sdict = Dictionary::new();
sdict.insert("Type", Object::Name(b"EmbeddedFile".to_vec()));
sdict.insert("Filter", Object::Reference(filter_ref)); sdict.insert("Params", Object::Reference(params_ref)); sdict.insert("Length", Object::Integer(encoded.len() as i64));
sdict.insert("DanglingKey", Object::Reference(dangling)); source.set_object(stream_ref, Object::Stream(Stream::new(sdict, encoded)));
let mut efsub = Dictionary::new();
efsub.insert("F", Object::Reference(stream_ref));
efsub.insert("UF", Object::Reference(stream_ref));
let mut fs = Dictionary::new();
fs.insert("Type", Object::Name(b"Filespec".to_vec()));
fs.insert("F", Object::String(b"s.bin".to_vec()));
fs.insert("UF", Object::String(b"s.bin".to_vec()));
fs.insert("EF", Object::Dictionary(efsub));
source.set_object(fs_ref, Object::Dictionary(fs));
insert_embedded_file(&mut source, b"s.bin", fs_ref).expect("insert source");
let mut target = open_minimal();
let n = copy_attachments_from(&mut target, &mut source, None).expect("copy");
assert_eq!(n, 1);
let tgt_entries = list_embedded_files(&mut target).expect("list target");
assert_eq!(tgt_entries.len(), 1);
let tgt_fs_ref = tgt_entries[0].1;
let Object::Dictionary(tgt_fs) = target.resolve(tgt_fs_ref).expect("resolve tgt fs") else {
panic!("filespec not a dict");
};
for (k, v) in tgt_fs.iter() {
if k == b"EF" {
continue; }
assert_no_refs(v, "target filespec (non-/EF)");
}
let tgt_stream = resolve_ef_stream(&mut target, tgt_fs_ref);
assert_no_refs(
&Object::Dictionary(tgt_stream.dict.clone()),
"target stream dict",
);
match tgt_stream.dict.get("Params") {
Some(Object::Dictionary(p)) => {
assert_eq!(
p.get("CreationDate").cloned(),
Some(Object::String(b"D:20260101000000Z".to_vec())),
"nested /CreationDate must be inlined"
);
}
other => panic!("/Params must be an inlined dict, got {other:?}"),
}
assert_eq!(
tgt_stream.dict.get("Filter").cloned(),
Some(Object::Name(b"FlateDecode".to_vec())),
"/Filter must be inlined as a Name"
);
match tgt_stream.dict.get("DanglingKey") {
None | Some(Object::Null) => {}
other => panic!("unresolvable ref must become null/absent, got {other:?}"),
}
let decoded =
crate::filters::decode_stream_data(&tgt_stream.dict, &tgt_stream.data).expect("decode");
assert_eq!(decoded.as_slice(), raw.as_ref());
}
}