298 lines
11 KiB
Rust
298 lines
11 KiB
Rust
//! A minimal PDF object writer (R4.5, streaming since R4.6): numbered objects written as
|
|
//! they come, streams, a classic xref table and the trailer, with the string forms pdf-lib used (UTF-16BE hex with a BOM for text,
|
|
//! literal dates `D:YYYYMMDDHHmmSSZ`, hex ASCII for URIs). pdf-writer was planned here; a
|
|
//! writer of this size (the document holds a dozen object kinds) spells every number through
|
|
//! `numberToString` and keeps the dictionaries under our control, so the B5 precision
|
|
//! difference the plan allowed never arises and no dependency enters the module.
|
|
|
|
use super::content::number_to_string;
|
|
|
|
/// The file as it is written (R4.6, OD-2): every object lands in the file the moment it
|
|
/// is added, in chunks that are never reallocated (an object larger than the chunk's
|
|
/// target gets a chunk of its own), so the image streams never wait in a second structure
|
|
/// for `finish` and no growing buffer copies the file over itself. The chunk target starts
|
|
/// at [`CHUNK_FIRST`] and doubles per chunk up to [`CHUNK_MAX`]: a small file pays little
|
|
/// slack, a large one makes few long-lived allocations between the decode transients
|
|
/// (measured: 1 MiB chunks cost 0.12 MB of fragmentation per view, 8 MiB none). The chunks
|
|
/// are handed out one by one at the end (a `Blob` takes parts), so the file is never held
|
|
/// twice. A reserved object (the catalog, the page tree) is written where `set` is
|
|
/// called, at the end; the xref maps every number to its offset wherever the object lies.
|
|
pub struct Objects {
|
|
sealed: Vec<Vec<u8>>,
|
|
current: Vec<u8>,
|
|
target: usize,
|
|
/// Bytes in the sealed chunks and the current one.
|
|
total: usize,
|
|
/// Offset of each object by number, `None` while reserved.
|
|
offsets: Vec<Option<usize>>,
|
|
}
|
|
|
|
pub const CHUNK_FIRST: usize = 1 << 20;
|
|
pub const CHUNK_MAX: usize = 8 << 20;
|
|
|
|
/// `n 0 R`.
|
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
pub struct Ref(pub usize);
|
|
|
|
impl Ref {
|
|
pub fn text(self) -> String {
|
|
format!("{} 0 R", self.0)
|
|
}
|
|
}
|
|
|
|
const HEADER: &[u8] = b"%PDF-1.7\n%\xE2\xE3\xCF\xD3\n\n";
|
|
|
|
impl Objects {
|
|
pub fn new() -> Self {
|
|
let mut objects = Self {
|
|
sealed: Vec::new(),
|
|
current: Vec::new(),
|
|
target: CHUNK_FIRST,
|
|
total: 0,
|
|
offsets: Vec::new(),
|
|
};
|
|
objects.open_for(HEADER.len());
|
|
objects.write(HEADER);
|
|
objects
|
|
}
|
|
|
|
/// Bytes written so far (the file's size before the xref).
|
|
pub fn written(&self) -> usize {
|
|
self.total
|
|
}
|
|
|
|
/// Closes the current chunk; the next object starts a new one.
|
|
fn seal(&mut self) {
|
|
if !self.current.is_empty() {
|
|
let mut chunk = std::mem::take(&mut self.current);
|
|
// The slack of the target is given back: a sealed chunk costs its bytes.
|
|
chunk.shrink_to_fit();
|
|
self.sealed.push(chunk);
|
|
self.target = (self.target * 2).min(CHUNK_MAX);
|
|
}
|
|
}
|
|
|
|
/// Makes room for an object of `size` bytes in one chunk: the current one when it
|
|
/// fits, else a new one of the target size (or the object's, when larger).
|
|
fn open_for(&mut self, size: usize) {
|
|
if self.current.len() + size > self.current.capacity() {
|
|
self.seal();
|
|
}
|
|
if self.current.capacity() == 0 {
|
|
self.current.reserve_exact(size.max(self.target));
|
|
}
|
|
}
|
|
|
|
/// The chunk and the offset in it of the file offset `at` (an object's xref offset),
|
|
/// once the file is finished.
|
|
fn locate(sealed: &[Vec<u8>], at: usize) -> (usize, usize) {
|
|
let mut start = 0;
|
|
for (index, chunk) in sealed.iter().enumerate() {
|
|
if at < start + chunk.len() {
|
|
return (index, at - start);
|
|
}
|
|
start += chunk.len();
|
|
}
|
|
(sealed.len(), 0)
|
|
}
|
|
|
|
/// The xref offset of an object already written.
|
|
pub fn offset_of(&self, at: Ref) -> Option<usize> {
|
|
at.0.checked_sub(1)
|
|
.and_then(|i| self.offsets.get(i).copied().flatten())
|
|
}
|
|
|
|
fn write(&mut self, bytes: &[u8]) {
|
|
self.current.extend_from_slice(bytes);
|
|
self.total += bytes.len();
|
|
}
|
|
|
|
/// Reserves the next object number; its body comes later with [`Objects::set`].
|
|
pub fn reserve(&mut self) -> Ref {
|
|
self.offsets.push(None);
|
|
Ref(self.offsets.len())
|
|
}
|
|
|
|
/// Writes the body of a reserved object; a second `set` or an unknown number is ignored.
|
|
pub fn set(&mut self, at: Ref, body: &[u8]) {
|
|
let Some(slot) = at.0.checked_sub(1).and_then(|i| self.offsets.get(i)) else {
|
|
return;
|
|
};
|
|
if slot.is_some() {
|
|
return;
|
|
}
|
|
let offset = self.write_object(at.0, &[body]);
|
|
self.offsets[at.0 - 1] = Some(offset);
|
|
}
|
|
|
|
pub fn add(&mut self, body: &[u8]) -> Ref {
|
|
let number = self.offsets.len() + 1;
|
|
let offset = self.write_object(number, &[body]);
|
|
self.offsets.push(Some(offset));
|
|
Ref(number)
|
|
}
|
|
|
|
/// A stream object: the dictionary entries (without `/Length`) and the data.
|
|
pub fn add_stream(&mut self, entries: &[(&str, String)], data: &[u8]) -> Ref {
|
|
let number = self.offsets.len() + 1;
|
|
let mut head = String::from("<<");
|
|
for (key, value) in entries {
|
|
head.push_str(&format!(" /{key} {value}"));
|
|
}
|
|
head.push_str(&format!(" /Length {} >>\nstream\n", data.len()));
|
|
let offset = self.write_object(number, &[head.as_bytes(), data, b"\nendstream"]);
|
|
self.offsets.push(Some(offset));
|
|
Ref(number)
|
|
}
|
|
|
|
/// `n 0 obj`, the parts, `endobj`, in one chunk.
|
|
fn write_object(&mut self, number: usize, parts: &[&[u8]]) -> usize {
|
|
let head = format!("{number} 0 obj\n");
|
|
let size = head.len() + parts.iter().map(|p| p.len()).sum::<usize>() + 9;
|
|
self.open_for(size);
|
|
let offset = self.total;
|
|
self.write(head.as_bytes());
|
|
for part in parts {
|
|
self.write(part);
|
|
}
|
|
self.write(b"\nendobj\n\n");
|
|
offset
|
|
}
|
|
|
|
/// The whole file as its chunks: the objects as written, then the xref and the
|
|
/// trailer. A number still reserved is a free entry. `attachment` is the file offset
|
|
/// of the attachment stream object, located in the chunks for the self-check.
|
|
pub fn finish(mut self, root: Ref, info: Ref, attachment: usize) -> Chunks {
|
|
let xref = self.total;
|
|
let mut tail = format!("xref\n0 {}\n0000000000 65535 f \n", self.offsets.len() + 1);
|
|
for offset in &self.offsets {
|
|
match offset {
|
|
Some(offset) => tail.push_str(&format!("{offset:010} 00000 n \n")),
|
|
None => tail.push_str("0000000000 65535 f \n"),
|
|
}
|
|
}
|
|
tail.push_str(&format!(
|
|
"trailer\n<< /Size {} /Root {} /Info {} >>\nstartxref\n{xref}\n%%EOF\n",
|
|
self.offsets.len() + 1,
|
|
root.text(),
|
|
info.text()
|
|
));
|
|
self.open_for(tail.len());
|
|
self.write(tail.as_bytes());
|
|
self.seal();
|
|
let attachment = Self::locate(&self.sealed, attachment);
|
|
Chunks {
|
|
chunks: self.sealed,
|
|
attachment,
|
|
}
|
|
}
|
|
}
|
|
|
|
/// A finished file: its chunks in order, and where the attachment stream object starts.
|
|
pub struct Chunks {
|
|
pub chunks: Vec<Vec<u8>>,
|
|
/// `(chunk index, offset in the chunk)`.
|
|
pub attachment: (usize, usize),
|
|
}
|
|
|
|
impl Default for Objects {
|
|
fn default() -> Self {
|
|
Self::new()
|
|
}
|
|
}
|
|
|
|
/// The header alone, what a chunk needs in front of it for the reader to scan it.
|
|
pub fn header() -> &'static [u8] {
|
|
HEADER
|
|
}
|
|
|
|
/// `<< /K v … >>` from entries already spelt as PDF syntax.
|
|
pub fn dict(entries: &[(&str, String)]) -> String {
|
|
let mut out = String::from("<<");
|
|
for (key, value) in entries {
|
|
out.push_str(&format!(" /{key} {value}"));
|
|
}
|
|
out.push_str(" >>");
|
|
out
|
|
}
|
|
|
|
/// A name object: `#xx` for the bytes a name cannot carry bare (`/application#2fjson`).
|
|
pub fn name(text: &str) -> String {
|
|
let mut out = String::from("/");
|
|
for byte in text.bytes() {
|
|
let bare = byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.' | b'+');
|
|
if bare {
|
|
out.push(char::from(byte));
|
|
} else {
|
|
out.push_str(&format!("#{byte:02x}"));
|
|
}
|
|
}
|
|
out
|
|
}
|
|
|
|
/// `PDFHexString.fromText`: UTF-16BE with a BOM, upper-case hex as pdf-lib printed it.
|
|
pub fn hex_text(text: &str) -> String {
|
|
let mut out = String::from("<FEFF");
|
|
for unit in text.encode_utf16() {
|
|
out.push_str(&format!("{unit:04X}"));
|
|
}
|
|
out.push('>');
|
|
out
|
|
}
|
|
|
|
/// The hex form of ASCII bytes, one byte per character (`linkAnnotation.ts` `asciiHexOf`).
|
|
pub fn hex_ascii(text: &str) -> String {
|
|
let mut out = String::from("<");
|
|
for byte in text.bytes() {
|
|
out.push_str(&format!("{byte:02x}"));
|
|
}
|
|
out.push('>');
|
|
out
|
|
}
|
|
|
|
/// A literal string, the three delimiters escaped (pdf-lib did not escape; a fixed ASCII
|
|
/// name never needs it, the escape only guards the form).
|
|
pub fn literal(text: &str) -> String {
|
|
let mut out = String::from("(");
|
|
for c in text.chars() {
|
|
if matches!(c, '(' | ')' | '\\') {
|
|
out.push('\\');
|
|
}
|
|
out.push(c);
|
|
}
|
|
out.push(')');
|
|
out
|
|
}
|
|
|
|
/// An array of numbers in pdf-lib's spelling.
|
|
pub fn numbers(values: &[f64]) -> String {
|
|
let items: Vec<String> = values.iter().map(|v| number_to_string(*v)).collect();
|
|
format!("[{}]", items.join(" "))
|
|
}
|
|
|
|
/// `PDFString.fromDate`: `(D:YYYYMMDDHHmmSSZ)` from the UTC fields of an ISO timestamp
|
|
/// (`YYYY-MM-DDTHH:MM:SS[.sss]Z`, what `Date.prototype.toISOString` writes); `None` when
|
|
/// the text is not one.
|
|
pub fn pdf_date(iso: &str) -> Option<String> {
|
|
let bytes = iso.as_bytes();
|
|
let digits = |range: std::ops::Range<usize>| {
|
|
bytes
|
|
.get(range.clone())
|
|
.filter(|part| part.iter().all(u8::is_ascii_digit))
|
|
.map(|_| &iso[range])
|
|
};
|
|
let (year, month, day) = (digits(0..4)?, digits(5..7)?, digits(8..10)?);
|
|
let (hours, minutes, seconds) = (digits(11..13)?, digits(14..16)?, digits(17..19)?);
|
|
let separators = bytes.get(4) == Some(&b'-')
|
|
&& bytes.get(7) == Some(&b'-')
|
|
&& bytes.get(10) == Some(&b'T')
|
|
&& bytes.get(13) == Some(&b':')
|
|
&& bytes.get(16) == Some(&b':');
|
|
let tail = &iso[19..];
|
|
let tail_ok = tail == "Z"
|
|
|| (tail.starts_with('.')
|
|
&& tail.ends_with('Z')
|
|
&& tail[1..tail.len() - 1].bytes().all(|b| b.is_ascii_digit()));
|
|
(separators && tail_ok).then(|| format!("(D:{year}{month}{day}{hours}{minutes}{seconds}Z)"))
|
|
}
|