Emit native PDF page resources and named transparency states
This commit is contained in:
1 parent
2bced813a2
commit
4f4a4567ea
23 files changed
+791
-37
No files matched your search
@@ -9,6 +9,7 @@ pub struct PdfColorProgram {
|
||||
literal: String,
|
||||
pub(crate) fill: Option<[u8; 3]>,
|
||||
pub(crate) stroke: Option<[u8; 3]>,
|
||||
pub(crate) graphics_states: Vec<Vec<u8>>,
|
||||
}
|
||||
|
||||
impl PdfColorProgram {
|
||||
@@ -16,8 +17,16 @@ impl PdfColorProgram {
|
||||
let mut fill = None;
|
||||
let mut stroke = None;
|
||||
let mut operands = Vec::with_capacity(4);
|
||||
let mut graphics_states = Vec::new();
|
||||
let mut name = None;
|
||||
for token in literal.split_ascii_whitespace() {
|
||||
if matches!(token, "g" | "G" | "rg" | "RG" | "k" | "K") {
|
||||
if token == "gs" && operands.is_empty() {
|
||||
graphics_states.push(name.take().ok_or("PDF gs requires a resource name")?);
|
||||
} else if name.is_some() {
|
||||
return Err("PDF resource name must be followed by gs".into());
|
||||
} else if token.starts_with('/') && operands.is_empty() {
|
||||
name = Some(super::page_resources::parse_name(token.as_bytes())?);
|
||||
} else if matches!(token, "g" | "G" | "rg" | "RG" | "k" | "K") {
|
||||
let rgb = match (token, operands.as_slice()) {
|
||||
("g" | "G", [gray]) => [*gray; 3],
|
||||
("rg" | "RG", [r, g, b]) => [*r, *g, *b],
|
||||
@@ -53,13 +62,14 @@ impl PdfColorProgram {
|
||||
operands.push(number.clamp(0.0, 1.0));
|
||||
}
|
||||
}
|
||||
if !operands.is_empty() {
|
||||
if !operands.is_empty() || name.is_some() {
|
||||
return Err("PDF color program ends with unconsumed operands".into());
|
||||
}
|
||||
Ok(Self {
|
||||
literal,
|
||||
fill,
|
||||
stroke,
|
||||
graphics_states,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -108,6 +118,7 @@ impl Default for PdfColorStacks {
|
||||
literal: "0 g 0 G".into(),
|
||||
fill: Some([0; 3]),
|
||||
stroke: Some([0; 3]),
|
||||
graphics_states: Vec::new(),
|
||||
}),
|
||||
saved: Vec::new(),
|
||||
}])
|
||||
|
||||
@@ -0,0 +1,422 @@
|
||||
//! Native PDF objects and extra resources captured at page shipout.
|
||||
use lopdf::{
|
||||
Dictionary, Object, Stream,
|
||||
content::{Content, Operation},
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::{
|
||||
collections::{BTreeMap, BTreeSet},
|
||||
sync::Arc,
|
||||
};
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
pub(crate) enum ObjectBody {
|
||||
Direct(Vec<u8>),
|
||||
Stream { attributes: Vec<u8>, bytes: Vec<u8> },
|
||||
}
|
||||
|
||||
impl ObjectBody {
|
||||
fn len(&self) -> usize {
|
||||
match self {
|
||||
Self::Direct(bytes) => bytes.len(),
|
||||
Self::Stream { attributes, bytes } => attributes.len().saturating_add(bytes.len()),
|
||||
}
|
||||
}
|
||||
|
||||
fn parse(&self) -> Result<Object, String> {
|
||||
match self {
|
||||
Self::Direct(bytes) => parse_value(bytes),
|
||||
Self::Stream { attributes, bytes } => {
|
||||
let mut dictionary = parse_entries(attributes)?;
|
||||
if dictionary.has(b"Length") {
|
||||
return Err("native PDF stream attributes supply their own Length".into());
|
||||
}
|
||||
dictionary.set("Length", bytes.len() as i64);
|
||||
Ok(Object::Stream(Stream::new(dictionary, bytes.clone())))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
pub struct PdfObjects {
|
||||
values: Vec<Option<Arc<ObjectBody>>>,
|
||||
written: BTreeSet<u32>,
|
||||
last: i32,
|
||||
bytes: usize,
|
||||
}
|
||||
|
||||
impl PdfObjects {
|
||||
pub(crate) fn last(&self) -> i32 {
|
||||
self.last
|
||||
}
|
||||
|
||||
pub(crate) fn contains(&self, number: u32) -> bool {
|
||||
number > 0 && number as usize <= self.values.len()
|
||||
}
|
||||
|
||||
pub(crate) fn is_reserved(&self, number: u32) -> bool {
|
||||
self.contains(number) && self.values[number as usize - 1].is_none()
|
||||
}
|
||||
|
||||
pub(crate) fn reserve(&mut self, limit: usize) -> Result<u32, String> {
|
||||
if self.values.len() >= limit.min(i32::MAX as usize) {
|
||||
return Err("native PDF object capacity exceeded".into());
|
||||
}
|
||||
self.values.push(None);
|
||||
self.last = self.values.len() as i32;
|
||||
Ok(self.last as u32)
|
||||
}
|
||||
|
||||
pub(crate) fn define(
|
||||
&mut self,
|
||||
requested: Option<u32>,
|
||||
value: ObjectBody,
|
||||
limit: usize,
|
||||
) -> Result<u32, String> {
|
||||
let bytes = self.bytes.saturating_add(value.len());
|
||||
if bytes > limit {
|
||||
return Err("native PDF object payload capacity exceeded".into());
|
||||
}
|
||||
let number = match requested {
|
||||
Some(number) if self.is_reserved(number) => number,
|
||||
Some(_) => return Err("native PDF object was already defined".into()),
|
||||
None => self.reserve(limit)?,
|
||||
};
|
||||
self.values[number as usize - 1] = Some(Arc::new(value));
|
||||
self.bytes = bytes;
|
||||
self.last = number as i32;
|
||||
Ok(number)
|
||||
}
|
||||
|
||||
pub(crate) fn write(&mut self, number: u32) -> Result<(), String> {
|
||||
self.body(number)?;
|
||||
self.written.insert(number);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn written_body(&self, number: u32) -> Result<&ObjectBody, String> {
|
||||
if !self.written.contains(&number) {
|
||||
return Err(format!(
|
||||
"PDF reference uses object {number} before it was written"
|
||||
));
|
||||
}
|
||||
self.body(number)
|
||||
}
|
||||
|
||||
fn body(&self, number: u32) -> Result<&ObjectBody, String> {
|
||||
number
|
||||
.checked_sub(1)
|
||||
.and_then(|index| self.values.get(index as usize))
|
||||
.and_then(Option::as_deref)
|
||||
.ok_or_else(|| format!("undefined native PDF object {number}"))
|
||||
}
|
||||
}
|
||||
|
||||
fn check_pdf_nesting(bytes: &[u8]) -> Result<(), String> {
|
||||
let mut input = bytes.iter().copied().peekable();
|
||||
let mut depth = 0usize;
|
||||
let mut literal = 0usize;
|
||||
let mut hexadecimal = false;
|
||||
while let Some(byte) = input.next() {
|
||||
if literal != 0 {
|
||||
match byte {
|
||||
b'\\' => {
|
||||
input.next();
|
||||
}
|
||||
b'(' => literal += 1,
|
||||
b')' => literal -= 1,
|
||||
_ => {}
|
||||
}
|
||||
} else if hexadecimal {
|
||||
hexadecimal = byte != b'>';
|
||||
} else {
|
||||
match byte {
|
||||
b'%' => while input.next().is_some_and(|c| !matches!(c, b'\n' | b'\r')) {},
|
||||
b'(' => literal = 1,
|
||||
b'<' if input.next_if_eq(&b'<').is_some() => depth += 1,
|
||||
b'<' => hexadecimal = true,
|
||||
b'>' if input.next_if_eq(&b'>').is_some() => depth = depth.saturating_sub(1),
|
||||
b'[' => depth += 1,
|
||||
b']' => depth = depth.saturating_sub(1),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
if depth.saturating_add(literal) > 64 {
|
||||
return Err("native PDF object nesting limit exceeded".into());
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn parse_value(bytes: &[u8]) -> Result<Object, String> {
|
||||
check_pdf_nesting(bytes)?;
|
||||
// The content parser accepts complete PDF arrays, including references
|
||||
// inside them. Requiring the final operator also rejects a partially
|
||||
// parsed object or extra syntax after the value.
|
||||
let mut wrapped = b"[ ".to_vec();
|
||||
wrapped.extend_from_slice(bytes);
|
||||
wrapped.extend_from_slice(b"\n] EndValue");
|
||||
let Content { operations } =
|
||||
Content::decode(&wrapped).map_err(|_| "invalid native PDF object syntax")?;
|
||||
if let [operation] = operations.as_slice()
|
||||
&& operation.operator == "EndValue"
|
||||
&& let [Object::Array(values)] = operation.operands.as_slice()
|
||||
&& let [value] = values.as_slice()
|
||||
{
|
||||
return Ok(value.clone());
|
||||
}
|
||||
Err("expected one native PDF object value".into())
|
||||
}
|
||||
|
||||
pub(crate) fn parse_name(bytes: &[u8]) -> Result<Vec<u8>, String> {
|
||||
match parse_value(bytes)? {
|
||||
Object::Name(name) => Ok(name),
|
||||
_ => Err("expected a PDF resource name".into()),
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_entries(bytes: &[u8]) -> Result<Dictionary, String> {
|
||||
let mut wrapped = b"<< ".to_vec();
|
||||
wrapped.extend_from_slice(bytes);
|
||||
wrapped.extend_from_slice(b"\n>>");
|
||||
match parse_value(&wrapped)? {
|
||||
Object::Dictionary(dictionary) => Ok(dictionary),
|
||||
_ => Err("invalid native PDF resource dictionary".into()),
|
||||
}
|
||||
}
|
||||
|
||||
fn encode_value(object: Object) -> Result<Vec<u8>, String> {
|
||||
if let Object::Stream(stream) = object {
|
||||
let mut output = encode_value(Object::Dictionary(stream.dict))?;
|
||||
output.extend_from_slice(b"\nstream\n");
|
||||
output.extend_from_slice(&stream.content);
|
||||
output.extend_from_slice(b"\nendstream");
|
||||
return Ok(output);
|
||||
}
|
||||
let mut bytes = Content {
|
||||
operations: [Operation::new("", vec![object])],
|
||||
}
|
||||
.encode()
|
||||
.map_err(|error| format!("cannot encode native PDF object: {error}"))?;
|
||||
bytes.truncate(bytes.len() - 2);
|
||||
Ok(bytes)
|
||||
}
|
||||
|
||||
/// Referenced names affect SVG painting only when they are used by the page.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct PageResources {
|
||||
pub(crate) entries: Arc<[u8]>,
|
||||
pub(crate) opacity: BTreeMap<Vec<u8>, Transparency>,
|
||||
pub(crate) needs_pdf_for_preview: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub(crate) struct Transparency {
|
||||
pub fill: Option<String>,
|
||||
pub stroke: Option<String>,
|
||||
}
|
||||
|
||||
fn resolve_dictionary(entry: Object, objects: &PdfObjects) -> Result<Dictionary, String> {
|
||||
let mut entry = entry;
|
||||
let mut seen = BTreeSet::new();
|
||||
loop {
|
||||
match entry {
|
||||
Object::Dictionary(dictionary) => return Ok(dictionary),
|
||||
Object::Reference((number, 0)) if seen.insert(number) => {
|
||||
entry = objects.written_body(number)?.parse()?;
|
||||
}
|
||||
_ => return Err("PDF resource must refer to a dictionary".into()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn alpha(dictionary: &Dictionary, key: &[u8]) -> Result<Option<String>, String> {
|
||||
let Ok(value) = dictionary.get(key) else {
|
||||
return Ok(None);
|
||||
};
|
||||
let n = match value {
|
||||
Object::Integer(n) => *n as f64,
|
||||
Object::Real(n) => *n,
|
||||
_ => return Err("PDF alpha must be numeric".into()),
|
||||
};
|
||||
if !(0.0..=1.0).contains(&n) {
|
||||
return Err("PDF alpha must be between zero and one".into());
|
||||
}
|
||||
Ok(Some(n.to_string()))
|
||||
}
|
||||
|
||||
impl PageResources {
|
||||
pub(crate) fn from_page(
|
||||
bytes: Arc<[u8]>,
|
||||
names: &BTreeSet<Vec<u8>>,
|
||||
objects: &PdfObjects,
|
||||
) -> Result<Self, String> {
|
||||
if names.is_empty() {
|
||||
return Ok(Self {
|
||||
entries: bytes,
|
||||
..Self::default()
|
||||
});
|
||||
}
|
||||
let entries = parse_entries(&bytes)?;
|
||||
let definitions = entries
|
||||
.get(b"ExtGState")
|
||||
.map_err(|_| "PDF graphics state used without an ExtGState resource")?;
|
||||
let definitions = resolve_dictionary(definitions.clone(), objects)?;
|
||||
let mut resources = Self {
|
||||
entries: bytes,
|
||||
..Self::default()
|
||||
};
|
||||
for name in names {
|
||||
let definition = definitions.get(name).map_err(|_| {
|
||||
format!(
|
||||
"undefined PDF graphics state /{}",
|
||||
String::from_utf8_lossy(name)
|
||||
)
|
||||
})?;
|
||||
let attributes = resolve_dictionary(definition.clone(), objects)?;
|
||||
resources.needs_pdf_for_preview |= attributes.iter().any(|(key, value)| {
|
||||
!matches!(key.as_slice(), b"Type" | b"ca" | b"CA")
|
||||
&& !(key == b"BM" && value.as_name().is_ok_and(|name| name == b"Normal"))
|
||||
});
|
||||
resources.opacity.insert(
|
||||
name.clone(),
|
||||
Transparency {
|
||||
fill: alpha(&attributes, b"ca")?,
|
||||
stroke: alpha(&attributes, b"CA")?,
|
||||
},
|
||||
);
|
||||
}
|
||||
Ok(resources)
|
||||
}
|
||||
}
|
||||
|
||||
/// Validated values prior to choosing the exporter's physical object numbers.
|
||||
pub(crate) struct ResourceOutput {
|
||||
values: BTreeMap<u32, Object>,
|
||||
page_entries: Vec<Dictionary>,
|
||||
catalog: Option<Dictionary>,
|
||||
info: Option<Dictionary>,
|
||||
}
|
||||
|
||||
pub(crate) struct RemappedResources {
|
||||
pub pages: Vec<Vec<u8>>,
|
||||
pub catalog: Option<Vec<u8>>,
|
||||
pub info: Option<Vec<u8>>,
|
||||
}
|
||||
|
||||
impl ResourceOutput {
|
||||
pub(crate) fn prepare(
|
||||
pages: &[crate::render::DisplayList],
|
||||
objects: Option<&PdfObjects>,
|
||||
catalog: Option<&[u8]>,
|
||||
info: Option<&[u8]>,
|
||||
) -> Result<Self, String> {
|
||||
let empty = PdfObjects::default();
|
||||
let objects = objects.unwrap_or(&empty);
|
||||
let page_entries = pages
|
||||
.iter()
|
||||
.map(|page| {
|
||||
let entries = parse_entries(&page.pdf_resources.entries)?;
|
||||
if entries.has(b"Font") || entries.has(b"XObject") {
|
||||
return Err(
|
||||
"additional PDF resources overlap generated Font or XObject entries".into(),
|
||||
);
|
||||
}
|
||||
Ok(entries)
|
||||
})
|
||||
.collect::<Result<Vec<_>, String>>()?;
|
||||
let catalog = catalog.map(parse_entries).transpose()?;
|
||||
let info = info.map(parse_entries).transpose()?;
|
||||
let mut pending = objects.written.clone();
|
||||
for dictionary in page_entries.iter().chain(catalog.iter()).chain(info.iter()) {
|
||||
for (_, entry) in dictionary.iter() {
|
||||
references(entry, &mut pending)?;
|
||||
}
|
||||
}
|
||||
let mut values = BTreeMap::new();
|
||||
while let Some(number) = pending.pop_first() {
|
||||
if values.contains_key(&number) {
|
||||
continue;
|
||||
}
|
||||
let value = objects.written_body(number)?.parse()?;
|
||||
references(&value, &mut pending)?;
|
||||
values.insert(number, value);
|
||||
}
|
||||
Ok(Self {
|
||||
values,
|
||||
page_entries,
|
||||
catalog,
|
||||
info,
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn append(self, output: &mut Vec<Vec<u8>>) -> RemappedResources {
|
||||
let ids: BTreeMap<_, _> = self
|
||||
.values
|
||||
.keys()
|
||||
.copied()
|
||||
.enumerate()
|
||||
.map(|(i, number)| (number, (output.len() + i + 1) as u32))
|
||||
.collect();
|
||||
for (_, mut object) in self.values {
|
||||
remap(&mut object, &ids);
|
||||
output.push(encode_value(object).expect("valid PDF object in memory"));
|
||||
}
|
||||
let encode = |dictionary: Dictionary| {
|
||||
if dictionary.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
let mut object = Object::Dictionary(dictionary);
|
||||
remap(&mut object, &ids);
|
||||
let bytes = encode_value(object).expect("valid PDF resource dictionary in memory");
|
||||
bytes[2..bytes.len() - 2].to_vec()
|
||||
};
|
||||
RemappedResources {
|
||||
pages: self.page_entries.into_iter().map(&encode).collect(),
|
||||
catalog: self.catalog.map(&encode),
|
||||
info: self.info.map(encode),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn references(object: &Object, pending: &mut BTreeSet<u32>) -> Result<(), String> {
|
||||
match object {
|
||||
Object::Reference((number, 0)) if *number > 0 => {
|
||||
pending.insert(*number);
|
||||
}
|
||||
Object::Reference(_) => return Err("unsupported native PDF object generation".into()),
|
||||
Object::Array(values) => {
|
||||
for value in values {
|
||||
references(value, pending)?;
|
||||
}
|
||||
}
|
||||
Object::Dictionary(dictionary) => {
|
||||
for (_, value) in dictionary.iter() {
|
||||
references(value, pending)?;
|
||||
}
|
||||
}
|
||||
Object::Stream(stream) => {
|
||||
for (_, value) in stream.dict.iter() {
|
||||
references(value, pending)?;
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn remap(object: &mut Object, ids: &BTreeMap<u32, u32>) {
|
||||
match object {
|
||||
Object::Reference((number, _)) => *number = ids[number],
|
||||
Object::Array(values) => values.iter_mut().for_each(|value| remap(value, ids)),
|
||||
Object::Dictionary(dictionary) => dictionary
|
||||
.iter_mut()
|
||||
.for_each(|(_, value)| remap(value, ids)),
|
||||
Object::Stream(stream) => stream
|
||||
.dict
|
||||
.iter_mut()
|
||||
.for_each(|(_, value)| remap(value, ids)),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user