Emit native PDF page resources and named transparency states

This commit is contained in:
gloamxun committed 2026-11-21 00:53:46 +08:00
1 parent 2bced813a2
commit 4f4a4567ea
23 files changed
+791 -37

No files matched your search

@@ -25,9 +25,15 @@ pub struct NativeShipout {
pub(super) pdf_color_steps: Vec<Option<Arc<PdfColorProgram>>>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub(super) pdf_graphics_steps: Vec<PdfGraphics>,
#[serde(default, skip_serializing_if = "pdf_resource_entries_empty")]
pub(super) pdf_resource_entries: Arc<[u8]>,
#[serde(default, skip_serializing_if = "crate::pdf_device::links::PageLinks::is_empty")]
pub(super) pdf_links: crate::pdf_device::links::PageLinks,
}
fn pdf_resource_entries_empty(entries: &Arc<[u8]>) -> bool {
entries.is_empty()
}
impl NativeShipout {
pub fn display_list(&self) -> Result<crate::render::DisplayList, String> {
let mut page = crate::render::DisplayList {
@@ -37,6 +43,10 @@ impl NativeShipout {
units: crate::render::DisplayUnits::TeX,
pdf: self.device.pdf.clone(),
pdf_links: self.pdf_links.clone(),
pdf_resources: crate::pdf_device::page_resources::PageResources {
entries: self.pdf_resource_entries.clone(),
..Default::default()
},
..Default::default()
};
use crate::{math_engine_tex::MathItem, render::DisplayItem};
@@ -596,6 +596,10 @@ impl Printer<'_> {
self.literal(&format!(" {{{}}}", program.literal()));
}
}
OutputOperation::PdfObject(number) => {
self.command("pdfrefobj");
self.literal(&format!(" {number}"));
}
OutputOperation::PdfImage { image, .. } => {
self.command("pdfrefximage");
self.literal(&format!(" {}", image.id));
@@ -25,6 +25,7 @@ mod pdf_catalog;
mod pdf_color;
mod pdf_graphics;
mod pdf_image;
mod pdf_objects;
mod pdf_links;
#[cfg(all(target_os = "linux", target_env = "gnu"))]
pub(super) mod pdf_match;
@@ -2097,6 +2098,10 @@ impl Executor {
Meaning::Primitive(Primitive::Interactionmode) => Ok(self.interaction_mode_value()),
Meaning::Primitive(Primitive::Pdftexversion) => Ok(Self::PDFTEX_VERSION),
Meaning::Primitive(Primitive::Pdfshellescape) => Ok(Self::SHELL_ESCAPE),
Meaning::Primitive(Primitive::Pdflastobj) => {
self.reads.insert(Dependency::PdfObjects);
Ok(self.state.pdf_objects.as_deref().map_or(0, |objects| objects.last()))
}
Meaning::Primitive(
p @ (Primitive::Pdflastximage
| Primitive::Pdflastximagepages
@@ -2664,6 +2669,7 @@ impl Executor {
if immediate {
let next = self.required_expanded(files)?;
match self.primitive(&next.token) {
Some(Primitive::Pdfobj) => return self.scan_pdf_object(true, files),
Some(Primitive::Pdfximage) => return self.scan_pdf_image(&next.token, true, files),
Some(p @ (Primitive::Openout | Primitive::Closeout | Primitive::Write)) => {
primitive = p
@@ -2741,6 +2747,7 @@ impl Executor {
self.current = node.span;
self.tick()?;
match &node.operation {
OutputOperation::PdfObject(number) => return self.write_pdf_object(*number),
OutputOperation::PdfImage { image, .. } => {
return self.declare_pdf_image(image.id);
}
@@ -3708,6 +3715,8 @@ impl Executor {
Pdfstartlink | Pdfendlink | Pdfdest => {
self.scan_pdf_link(primitive, token.span, files)?;
}
Pdfobj => self.scan_pdf_object(false, files)?,
Pdfrefobj => self.scan_pdf_object_reference(token.span, files)?,
Pdfcatalog => self.scan_pdf_catalog(files)?,
Pdfoutline => self.scan_pdf_outline(files)?,
Pdfinfo => self.scan_pdf_info(files)?,
@@ -264,6 +264,17 @@ impl Executor {
};
self.trace_shipout(&b, files)?;
let current = self.current;
let pdf_resource_entries = if device.pdf.is_some() {
let parameter = TokenParameter::Pdfpageresources;
self.reads.insert(Dependency::TokenParameter(parameter));
if let Some(tokens) = self.state.token_parameter(parameter).cloned() {
self.pdf_token_bytes(&tokens)?.into()
} else {
Default::default()
}
} else {
Default::default()
};
let pdf_color_start = if device.pdf.is_some() {
self.pdf_colors.start_page()
} else {
@@ -367,6 +378,7 @@ impl Executor {
pdf_color_start,
pdf_color_steps,
pdf_graphics_steps,
pdf_resource_entries,
pdf_links,
})));
self.statistics_after_shipout(before, files)?;
@@ -26,7 +26,7 @@ impl Executor {
Ok(number)
}
fn pdf_token_bytes(&mut self, tokens: &[Token]) -> Result<Vec<u8>, Error> {
pub(super) fn pdf_token_bytes(&mut self, tokens: &[Token]) -> Result<Vec<u8>, Error> {
let text = self.token_list_text(tokens);
if text.len() > self.limits.tokens {
return self.fail("native PDF token output limit exceeded");
@@ -0,0 +1,113 @@
use super::*;
use crate::pdf_device::page_resources::ObjectBody;
impl Executor {
pub(super) fn scan_pdf_object(
&mut self,
immediate: bool,
files: &mut impl SourceProvider,
) -> Result<(), Error> {
if self.read_parameter(Parameter::Pdfoutput).width() <= 0 {
return self.fail("\\pdfobj not allowed in DVI mode");
}
self.reads.insert(Dependency::PdfObjects);
if self.keyword("reserveobjnum", files)? {
self.optional_space(files)?;
if immediate {
return self.fail("\\pdfobj reserveobjnum cannot be used with \\immediate");
}
return self
.state
.pdf_objects
.get_or_insert_with(Default::default)
.reserve(self.limits.tokens)
.map(|_| ())
.map_err(|error| self.error(error, self.current));
}
let requested = if self.keyword("useobjnum", files)? {
let number = self.integer(files)?;
let reserved = u32::try_from(number).ok().filter(|number| {
self.state
.pdf_objects
.as_deref()
.is_some_and(|objects| objects.is_reserved(*number))
});
if reserved.is_none() {
let warning = "pdfTeX warning (\\pdfobj): invalid object number being ignored\n";
files
.observe_message(warning)
.map_err(|error| self.error(error, self.current))?;
self.events.push(Event::Message {
text: warning.into(),
span: self.current,
});
}
reserved
} else {
None
};
let attributes = if self.keyword("stream", files)? {
Some(if self.keyword("attr", files)? {
self.scan_pdf_bytes(files)?
} else {
Vec::new()
})
} else {
None
};
if self.keyword("file", files)? {
return self.fail("file-backed \\pdfobj payloads are unsupported in native PDF output");
}
let bytes = self.scan_pdf_bytes(files)?;
let value = match attributes {
Some(attributes) => ObjectBody::Stream { attributes, bytes },
None => ObjectBody::Direct(bytes),
};
let number = self
.state
.pdf_objects
.get_or_insert_with(Default::default)
.define(requested, value, self.limits.tokens)
.map_err(|error| self.error(error, self.current))?;
if immediate {
self.pdf_page_data(files)?;
self.write_pdf_object(number)?;
}
Ok(())
}
pub(super) fn scan_pdf_object_reference(
&mut self,
span: Span,
files: &mut impl SourceProvider,
) -> Result<(), Error> {
if self.read_parameter(Parameter::Pdfoutput).width() <= 0 {
return self.fail("\\pdfrefobj not allowed in DVI mode");
}
self.reads.insert(Dependency::PdfObjects);
let number = self.positive_pdf_number("object reference", files)? as u32;
if !self
.state
.pdf_objects
.as_deref()
.is_some_and(|objects| objects.contains(number))
{
return self.fail("cannot find referenced PDF object");
}
self.defer_output(OutputNode {
span,
operation: OutputOperation::PdfObject(number),
})
}
pub(super) fn write_pdf_object(&mut self, number: u32) -> Result<(), Error> {
self.reads.insert(Dependency::PdfObjects);
self.state
.pdf_objects
.as_deref_mut()
.ok_or_else(|| String::from("unknown native PDF object"))
.and_then(|objects| objects.write(number))
.map_err(|error| self.error(error, self.current))
}
}
@@ -207,6 +207,7 @@ impl Executor {
| Primitive::Month
| Primitive::Year
| Primitive::Inputlineno
| Primitive::Pdflastobj
| Primitive::Pdflastximage
| Primitive::Pdflastximagepages
| Primitive::Pdflastximagecolordepth
@@ -8,8 +8,8 @@ use std::{
sync::{Arc, Mutex, OnceLock, Weak},
};
const SCHEMA: u32 = 33;
const COMPATIBLE_SCHEMAS: [u32; 5] = [27, 28, 31, 32, SCHEMA];
const SCHEMA: u32 = 34;
const COMPATIBLE_SCHEMAS: [u32; 6] = [27, 28, 31, 32, 33, SCHEMA];
const ENGINE: &str = concat!("texrra-native/", env!("CARGO_PKG_VERSION"));
#[derive(serde::Serialize, serde::Deserialize)]
@@ -15,6 +15,7 @@ pub enum TokenParameter {
Output,
Errhelp,
Everycr,
Pdfpageresources,
}
impl TokenParameter {
pub const ALL: &'static [Self] = &[
@@ -28,6 +29,7 @@ impl TokenParameter {
Self::Output,
Self::Errhelp,
Self::Everycr,
Self::Pdfpageresources,
];
pub fn name(self) -> String {
format!("{self:?}").to_ascii_lowercase()
@@ -228,6 +228,7 @@ pub enum OutputOperation {
stack: usize,
action: crate::pdf_device::PdfColorStackAction,
},
PdfObject(u32),
PdfSave,
PdfSetMatrix(Vec<Token>),
PdfRestore,
@@ -367,6 +367,7 @@ pub enum Dependency {
MagnificationState,
PdfFileState,
PdfCatalogState,
PdfObjects,
PdfImages,
GlyphUnicode,
ResourceStatistics,
@@ -674,6 +675,7 @@ impl Execution {
})?);
}
}
self.resolve_page_graphics_resources(&mut pages)?;
if let Some(first) = pages.first_mut() {
first.items.extend(
image_objects
@@ -683,6 +685,28 @@ impl Execution {
}
Ok(pages)
}
fn resolve_page_graphics_resources(
&self,
pages: &mut [crate::render::DisplayList],
) -> Result<(), Error> {
use crate::pdf_device::page_resources::{PdfObjects, PageResources};
use crate::render::DisplayItem;
let empty = PdfObjects::default();
let objects = self.state.pdf_objects.as_deref().unwrap_or(&empty);
for page in pages {
let states = page.items.iter().filter_map(|item| match item {
DisplayItem::PdfColor(program) => Some(&program.graphics_states),
_ => None,
}).flatten().cloned().collect();
page.pdf_resources = PageResources::from_page(
page.pdf_resources.entries.clone(), &states, objects,
).map_err(|message| Error::at(
&self.sources, self.state.input_profile(), message, Span::default(),
))?;
}
Ok(())
}
/// Export the paragraphs already measured during token execution. No text
/// concatenation, source parser or final-state restyling participates.
pub fn document(&self) -> Result<crate::Document, Error> {
@@ -319,6 +319,9 @@ pub enum Primitive {
Rpcode,
Efcode,
Pdffontexpand,
Pdfobj,
Pdfrefobj,
Pdflastobj,
}
impl Primitive {
@@ -611,6 +614,8 @@ pub struct State {
pub(super) pdf_file_options: Option<crate::pdf_device::PdfFileOptions>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub(super) pdf_catalog: Option<Box<crate::pdf_device::catalog::PdfCatalog>>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub(super) pdf_objects: Option<Box<crate::pdf_device::page_resources::PdfObjects>>,
pub(super) pdf_info: Vec<u8>,
pub(super) glyph_unicode: crate::pdf_unicode::GlyphUnicodeMap,
pub(super) hyphenation: super::hyphenation::HyphenationData,
@@ -712,6 +717,7 @@ impl Default for State {
output_mode_set: None,
pdf_file_options: None,
pdf_catalog: None,
pdf_objects: None,
pdf_info: Vec::new(),
glyph_unicode: crate::pdf_unicode::GlyphUnicodeMap::default(),
hyphenation: super::hyphenation::HyphenationData::default(),
@@ -937,6 +943,9 @@ impl Default for State {
#[cfg(all(target_os = "linux", target_env = "gnu"))]
("pdflastmatch", Pdflastmatch),
("pdfcolorstackinit", Pdfcolorstackinit),
("pdfobj", Pdfobj),
("pdfrefobj", Pdfrefobj),
("pdflastobj", Pdflastobj),
("pdfcolorstack", Pdfcolorstack),
("pdfsave", Pdfsave),
("pdfstartlink", Pdfstartlink),
@@ -1334,6 +1343,7 @@ impl State {
self.output_mode_set = None;
self.pdf_file_options = None;
self.pdf_catalog = None;
self.pdf_objects = None;
self.pdf_info.clear();
self
}
@@ -1348,6 +1358,7 @@ impl State {
generate_unicode: self.parameter(Parameter::Pdfgentounicode).width(),
glyph_unicode: &self.glyph_unicode,
catalog: self.pdf_catalog.as_deref(),
objects: self.pdf_objects.as_deref(),
info: crate::pdf_device::PdfInfo {
entries: &self.pdf_info,
date: (self.parameter(Parameter::Pdfinfoomitdate).width() == 0)
@@ -292,6 +292,7 @@ pub(super) fn expand_pages(
magnification: page.magnification,
units: page.units,
pdf: page.pdf.clone(),
pdf_resources: page.pdf_resources.clone(),
images: page.images.clone(),
..DisplayList::default()
};
+50 -12
View File
@@ -1098,6 +1098,7 @@ pub fn display_lists_to_pdf_with_paper(
&PdfMetadata::default(),
None,
None,
None,
&mut Vec::new(),
)
}
@@ -1130,6 +1131,7 @@ pub fn display_lists_to_pdf_with_cm_type1(
&PdfMetadata::default(),
None,
None,
None,
&mut Vec::new(),
)
}
@@ -1249,6 +1251,24 @@ fn native_pdf(
{
return Err("invalid native PDF final stream compression level".into());
}
let raw_objects = unicode.and_then(|options| options.objects);
let resources = if raw_objects.is_some()
|| pages.iter().any(|page| !page.pdf_resources.entries.is_empty())
{
let (catalog, info) = if raw_objects.is_some() {
(
unicode.and_then(|options| options.catalog).map(|catalog| catalog.entries.as_slice()),
unicode.map(|options| options.info.entries),
)
} else {
(None, None)
};
Some(crate::pdf_device::page_resources::ResourceOutput::prepare(
pages, raw_objects, catalog, info,
)?)
} else {
None
};
let mut diagnostics = Vec::new();
let bytes = write_pdf(
pages,
@@ -1259,6 +1279,7 @@ fn native_pdf(
&PdfMetadata::default(),
final_compression,
unicode,
resources,
&mut diagnostics,
);
Ok(NativePdfDocument { bytes, diagnostics })
@@ -1281,6 +1302,7 @@ pub fn display_lists_to_pdf_with_truetype_and_metadata(
metadata,
None,
None,
None,
&mut Vec::new(),
)
}
@@ -1302,6 +1324,7 @@ pub fn display_lists_to_pdf_with_cm_type1_and_metadata(
metadata,
None,
None,
None,
&mut Vec::new(),
)
}
@@ -1745,6 +1768,7 @@ fn write_pdf(
metadata: &PdfMetadata,
final_compression: Option<i32>,
unicode: Option<crate::pdf_unicode::PdfFinalOptions<'_>>,
resources: Option<crate::pdf_device::page_resources::ResourceOutput>,
diagnostics: &mut Vec<String>,
) -> Vec<u8> {
let width = page_width;
@@ -1991,6 +2015,7 @@ fn write_pdf(
font_ids[slot] = write_type0_font(&mut objects, face, slot, &used_chars[slot]);
}
let remapped = resources.map(|resources| resources.append(&mut objects));
let mut kids = Vec::new();
let mut page_ids: Vec<usize> = Vec::new();
let mut destinations = BTreeMap::new();
@@ -2017,7 +2042,7 @@ fn write_pdf(
}
}
}
for list in pages {
for (page_index, list) in pages.iter().enumerate() {
let width = if final_compression.is_some() {
list.width
} else {
@@ -2118,14 +2143,21 @@ fn write_pdf(
};
page_ids.push(page_id);
kids.push(format!("{page_id} 0 R"));
objects.push(
format!(
"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 {} {}] /Resources {resources}{annots} /Contents {content_id} 0 R >>",
physical(width),
physical(height)
)
.into_bytes(),
);
let mut page = format!(
"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 {} {}] /Resources ",
physical(width), physical(height),
).into_bytes();
if let Some(additional) = remapped.as_ref().map(|resources| &resources.pages[page_index])
&& !additional.is_empty()
{
page.extend_from_slice(&resources.as_bytes()[..resources.len() - 2]);
page.extend_from_slice(additional);
page.extend_from_slice(b" >>");
} else {
page.extend_from_slice(resources.as_bytes());
}
page.extend_from_slice(format!("{annots} /Contents {content_id} 0 R >>").as_bytes());
objects.push(page);
let mut names = BTreeMap::new();
for (index, slot) in &used {
@@ -2352,9 +2384,11 @@ fn write_pdf(
}
let mut catalog = catalog.into_bytes();
if let Some(extra) = extra {
if !extra.entries.is_empty() {
let entries = remapped.as_ref().and_then(|resources| resources.catalog.as_deref())
.unwrap_or(&extra.entries);
if !entries.is_empty() {
catalog.push(b'\n');
catalog.extend_from_slice(&extra.entries);
catalog.extend_from_slice(entries);
catalog.push(b'\n');
}
if let Some(id) = action {
@@ -2366,7 +2400,11 @@ fn write_pdf(
if let Some(level) = final_compression {
let info = match unicode {
Some(options) => native_information_dictionary(options.info),
Some(options) => native_information_dictionary(crate::pdf_device::PdfInfo {
entries: remapped.as_ref().and_then(|resources| resources.info.as_deref())
.unwrap_or(options.info.entries),
date: options.info.date,
}),
None => metadata_object(metadata)
.map(String::into_bytes)
.unwrap_or_else(|| b"<< /Producer (texrra Route-D native) >>".to_vec()),
+3
View File
@@ -82,3 +82,6 @@ pub(crate) use graphics::Affine;
pub use graphics::{PdfGraphics, PdfMatrix};
pub mod catalog;
pub mod links;
#[doc(hidden)]
pub mod page_resources;
+13 -2
View File
@@ -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)),
_ => {}
}
}
@@ -129,6 +129,7 @@ pub struct PdfFinalOptions<'a> {
pub generate_unicode: i32,
pub glyph_unicode: &'a GlyphUnicodeMap,
pub catalog: Option<&'a crate::pdf_device::catalog::PdfCatalog>,
pub objects: Option<&'a crate::pdf_device::page_resources::PdfObjects>,
pub info: crate::pdf_device::PdfInfo<'a>,
}
+82 -17
View File
@@ -247,6 +247,7 @@ pub struct DisplayList {
pub units: DisplayUnits,
pub pdf: Option<crate::pdf_device::PdfPageData>,
pub pdf_links: crate::pdf_device::links::PageLinks,
pub pdf_resources: crate::pdf_device::page_resources::PageResources,
}
impl Default for DisplayList {
fn default() -> Self {
@@ -260,6 +261,35 @@ impl Default for DisplayList {
units: DisplayUnits::PostScript,
pdf: None,
pdf_links: Default::default(),
pdf_resources: Default::default(),
}
}
}
#[derive(Clone, Default)]
struct SvgTransparency {
fill: String,
stroke: String,
rule_stroke: String,
image: String,
}
impl SvgTransparency {
fn apply(&mut self, transparency: &crate::pdf_device::page_resources::Transparency) {
let attribute = |name, alpha: &str| {
if alpha == "1" {
String::new()
} else {
format!(" {name}=\"{alpha}\"")
}
};
if let Some(alpha) = &transparency.fill {
self.fill = attribute("fill-opacity", alpha);
self.image = attribute("opacity", alpha);
}
if let Some(alpha) = &transparency.stroke {
self.stroke = attribute("stroke-opacity", alpha);
self.rule_stroke = attribute("fill-opacity", alpha);
}
}
}
@@ -267,9 +297,11 @@ impl Default for DisplayList {
impl DisplayList {
/// Whether this page needs the complete PDF device output for SVG preview.
pub fn has_embedded_pdf(&self) -> bool {
self.items
.iter()
.any(|item| matches!(item, DisplayItem::PdfImage { .. }))
self.pdf_resources.needs_pdf_for_preview
|| self
.items
.iter()
.any(|item| matches!(item, DisplayItem::PdfImage { .. }))
}
/// Compare the inputs consumed by SVG rendering. Font data for glyphs not
@@ -280,6 +312,8 @@ impl DisplayList {
&& self.units == other.units
&& self.magnification == other.magnification
&& self.images == other.images
&& self.pdf_resources.opacity == other.pdf_resources.opacity
&& self.pdf_resources.needs_pdf_for_preview == other.pdf_resources.needs_pdf_for_preview
&& self.items.len() == other.items.len()
&& self.items.iter().zip(&other.items).all(|(left, right)| {
match (left.native_svg_glyph(), right.native_svg_glyph()) {
@@ -357,9 +391,17 @@ impl DisplayList {
if !(1..=32768).contains(&self.magnification) {
return Err("invalid display-list magnification".into());
}
if self.has_embedded_pdf() {
return Err("this page requires a PDF renderer".into());
}
for item in &self.items {
if matches!(item, DisplayItem::PdfImage { .. }) {
return Err("embedded PDF page requires a PDF renderer".into());
if let DisplayItem::PdfColor(program) = item
&& program
.graphics_states
.iter()
.any(|name| !self.pdf_resources.opacity.contains_key(name))
{
return Err("unresolved PDF graphics state in SVG page".into());
}
if let Some(glyph) = item.native_svg_glyph() {
glyph?;
@@ -405,9 +447,12 @@ impl DisplayList {
let mut fill = [0u8, 0, 0];
let mut rule_fill = [0u8; 3];
let mut stroke = [0u8; 3];
let mut transparency = SvgTransparency::default();
let mut graphics = Vec::new();
let mut open_transforms = 0;
for item in &self.items {
let fill_opacity = &transparency.fill;
let stroke_opacity = &transparency.stroke;
match item {
DisplayItem::NativeGlyph { .. } => {
let NativeSvgGlyph {
@@ -436,7 +481,7 @@ impl DisplayList {
} else {
String::new()
};
out.push_str(&format!("<g data-font=\"{}\" data-glyph=\"{}\" data-slot=\"{slot}\" aria-label=\"{}\"><path d=\"{}\" transform=\"translate({x:.5} {y:.5}) scale({horizontal_scale:.8} -{scale:.8})\" fill=\"#{:02x}{:02x}{:02x}\"/></g>\n", escape(font), escape(glyph), escape(&label), path, fill[0],fill[1],fill[2]));
out.push_str(&format!("<g data-font=\"{}\" data-glyph=\"{}\" data-slot=\"{slot}\" aria-label=\"{}\"><path d=\"{}\" transform=\"translate({x:.5} {y:.5}) scale({horizontal_scale:.8} -{scale:.8})\" fill=\"#{:02x}{:02x}{:02x}\"{fill_opacity}/></g>\n", escape(font), escape(glyph), escape(&label), path, fill[0],fill[1],fill[2]));
}
DisplayItem::MathGlyph {
x,
@@ -450,7 +495,7 @@ impl DisplayList {
let y = *y as f64 / 65_536.0;
let scale = *size as f64 / 65_536_000.0;
out.push_str(&format!(
"<g data-font=\"{}\" data-slot=\"{slot}\" aria-label=\"{}\"><use href=\"#math-{}-{slot}\" transform=\"translate({x:.5} {y:.5}) scale({scale:.8} -{scale:.8})\" fill=\"#{:02x}{:02x}{:02x}\"/><text x=\"{x:.5}\" y=\"{y:.5}\" opacity=\"0\" aria-hidden=\"true\">{}</text></g>\n",
"<g data-font=\"{}\" data-slot=\"{slot}\" aria-label=\"{}\"><use href=\"#math-{}-{slot}\" transform=\"translate({x:.5} {y:.5}) scale({scale:.8} -{scale:.8})\" fill=\"#{:02x}{:02x}{:02x}\"{fill_opacity}/><text x=\"{x:.5}\" y=\"{y:.5}\" opacity=\"0\" aria-hidden=\"true\">{}</text></g>\n",
face.name(), escape(&character.to_string()), face.0,
fill[0], fill[1], fill[2], escape(&character.to_string())
));
@@ -515,7 +560,7 @@ impl DisplayList {
format!(" fill=\"#{:02x}{:02x}{:02x}\"", fill[0], fill[1], fill[2])
};
out.push_str(&format!(
"<text x=\"{x:.3}\" y=\"{y:.3}\" font-size=\"{size:.3}\" font-family=\"{family}\"{weight}{style}{fill_attr}>{}</text>\n",
"<text x=\"{x:.3}\" y=\"{y:.3}\" font-size=\"{size:.3}\" font-family=\"{family}\"{weight}{style}{fill_attr}{fill_opacity}>{}</text>\n",
escape(text)
));
}
@@ -527,7 +572,7 @@ impl DisplayList {
color,
} => {
out.push_str(&format!(
"<rect x=\"{:.3}\" y=\"{:.3}\" width=\"{:.3}\" height=\"{:.3}\" fill=\"#{:02x}{:02x}{:02x}\"/>\n",
"<rect x=\"{:.3}\" y=\"{:.3}\" width=\"{:.3}\" height=\"{:.3}\" fill=\"#{:02x}{:02x}{:02x}\"{fill_opacity}/>\n",
*x as f64 / 65_536.0,
*y as f64 / 65_536.0,
*width as f64 / 65_536.0,
@@ -547,14 +592,21 @@ impl DisplayList {
let y = *y as f64 / 65_536.0;
let width = *width as f64 / 65_536.0;
let height = *height as f64 / 65_536.0;
let color = if rule_fill == [0; 3] {
let stroked = self.units == DisplayUnits::TeX
&& (height <= 65_782.0 / 65_536.0 || width <= 65_782.0 / 65_536.0);
let (rgb, rule_alpha) = if stroked {
(stroke, &transparency.rule_stroke)
} else {
(rule_fill, fill_opacity)
};
let color = if rgb == [0; 3] {
"black".to_owned()
} else {
let [r, g, b] = rule_fill;
let [r, g, b] = rgb;
format!("#{r:02x}{g:02x}{b:02x}")
};
out.push_str(&format!(
"<rect x=\"{x:.3}\" y=\"{y:.3}\" width=\"{width:.3}\" height=\"{height:.3}\" fill=\"{color}\"/>\n"
"<rect x=\"{x:.3}\" y=\"{y:.3}\" width=\"{width:.3}\" height=\"{height:.3}\" fill=\"{color}\"{rule_alpha}/>\n"
));
}
// Link annotations are PDF metadata; the SVG preview omits them.
@@ -567,7 +619,7 @@ impl DisplayList {
thickness,
} => {
out.push_str(&format!(
"<rect x=\"{:.3}\" y=\"{:.3}\" width=\"{:.3}\" height=\"{:.3}\" fill=\"none\" stroke=\"#{:02x}{:02x}{:02x}\" stroke-width=\"{:.3}\"/>\n",
"<rect x=\"{:.3}\" y=\"{:.3}\" width=\"{:.3}\" height=\"{:.3}\" fill=\"none\" stroke=\"#{:02x}{:02x}{:02x}\" stroke-width=\"{:.3}\"{stroke_opacity}/>\n",
*x as f64 / 65_536.0,
(*y - *height) as f64 / 65_536.0,
*width as f64 / 65_536.0,
@@ -594,12 +646,21 @@ impl DisplayList {
if let Some(rgb) = program.stroke {
stroke = rgb;
}
for name in &program.graphics_states {
transparency.apply(&self.pdf_resources.opacity[name]);
}
}
DisplayItem::PdfGraphics { x, y, operation } => {
use crate::pdf_device::PdfGraphics;
match operation {
PdfGraphics::Save => {
graphics.push((open_transforms, fill, rule_fill, stroke));
graphics.push((
open_transforms,
fill,
rule_fill,
stroke,
transparency.clone(),
));
}
PdfGraphics::Matrix(matrix) => {
let [a, b, c, d, e, f] = matrix
@@ -611,12 +672,15 @@ impl DisplayList {
open_transforms += 1;
}
PdfGraphics::Restore { shift: [dx, dy] } => {
if let Some((depth, old_fill, old_rule, old_stroke)) = graphics.pop() {
if let Some((depth, old_fill, old_rule, old_stroke, old_alpha)) =
graphics.pop()
{
for _ in depth..open_transforms {
out.push_str("</g>\n");
}
(open_transforms, fill, rule_fill, stroke) =
(depth, old_fill, old_rule, old_stroke);
transparency = old_alpha;
}
if *dx != 0 || *dy != 0 {
let dx = *dx as f64 / 65_536.0;
@@ -641,7 +705,7 @@ impl DisplayList {
let width = *width as f64 / 65_536.0;
let [r, g, b] = stroke;
out.push_str(&format!(
"<line x1=\"{x1:.3}\" y1=\"{y1:.3}\" x2=\"{x2:.3}\" y2=\"{y2:.3}\" stroke=\"#{r:02x}{g:02x}{b:02x}\" stroke-width=\"{width:.3}\"/>\n"
"<line x1=\"{x1:.3}\" y1=\"{y1:.3}\" x2=\"{x2:.3}\" y2=\"{y2:.3}\" stroke=\"#{r:02x}{g:02x}{b:02x}\" stroke-width=\"{width:.3}\"{stroke_opacity}/>\n"
));
}
DisplayItem::PdfImage { .. } => unreachable!("checked before SVG export"),
@@ -661,8 +725,9 @@ impl DisplayList {
&& image.width as u64 * image.height as u64 <= 4_000_000
{
let uri = png_data_uri(image);
let image_opacity = &transparency.image;
out.push_str(&format!(
"<image x=\"{x:.3}\" y=\"{y:.3}\" width=\"{width:.3}\" height=\"{height:.3}\" href=\"{uri}\"/>\n"
"<image x=\"{x:.3}\" y=\"{y:.3}\" width=\"{width:.3}\" height=\"{height:.3}\" href=\"{uri}\"{image_opacity}/>\n"
));
} else {
out.push_str(&format!(
@@ -246,7 +246,7 @@ fn genuine_fraction_primitives_and_retained_boxes_survive_format_roundtrip() {
let envelope: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
let payload: serde_json::Value =
serde_json::from_str(envelope["payload"].as_str().unwrap()).unwrap();
assert_eq!(payload["schema"], 33);
assert_eq!(payload["schema"], 34);
let state = State::initex().with_etex();
let loaded = FormatImage::decode(&bytes)
.unwrap()
@@ -334,7 +334,7 @@ fn old_schema_and_missing_unicode_state_are_rejected_even_with_valid_checksums()
let envelope: serde_json::Value = serde_json::from_slice(&encoded).unwrap();
let original: serde_json::Value =
serde_json::from_str(envelope["payload"].as_str().unwrap()).unwrap();
assert_eq!(original["schema"], 33);
assert_eq!(original["schema"], 34);
for (schema, expected) in [
(1, "incompatible native format"),
(2, "incompatible native format"),
@@ -164,7 +164,7 @@ fn new_format_owns_vcenter_and_boxed_math_without_reinjecting_old_meanings() {
let envelope: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
let payload: serde_json::Value =
serde_json::from_str(envelope["payload"].as_str().unwrap()).unwrap();
assert_eq!(payload["schema"], 33);
assert_eq!(payload["schema"], 34);
let executor = FormatImage::decode(&bytes)
.unwrap()
.new_job(
+26
View File
@@ -1126,6 +1126,32 @@ schema28 更新。schema 1至26和29仍拒绝,27与28缺少必需 Unicode
[原样模板记录](PUBLISHER_TEMPLATE_MATRIX.md#aps-revtex-原样双栏样稿)
[pdfTeX 的重音布局](https://github.com/TeX-Live/texlive-source/blob/trunk/texk/web2c/pdftexdir/pdftex.web#L28084-L28143)
### 原生 PDF 页面资源与透明度
`\pdfpageresources` 使用 TeX 的 token 参数和分组恢复。每次出页
捕获当时的资源字典,最后解析直接或间接的图形状态。`\pdfobj`、
`\pdflastobj` 和 `\pdfrefobj` 实际保存、写入或延迟写入对象。
对象及资源、目录、信息字典的间接引用在 PDF 写出时统一编号。
页面颜色栈保存 `gs` 命令;SVG 从相同定义分别绘制填充和描边透明度,
涉及其他图形状态的页面使用实际原生 PDF 进行合成。schema34
保存新增语义。文件型对象、用户资源和自动字体或图像资源的名称
合并,以及其他 PDF 字典入口的引用仍待接齐。
[pdfTeX 的出页资源字典](https://github.com/TeX-Live/texlive-source/blob/trunk/texk/web2c/pdftexdir/pdftex.web)
独立 pdfTeX 对照中,固定样例一页及迟定义对象样例两页的144 DPI灰度图
逐像素一致。第二个样例核对组内资源只作用于一页、细规则的描边透明度,
以及延迟流对象和目录中的实际引用。既有目录和颜色栈共17项定向检查通过。
实时编辑将第一种填充透明度从0.25改为0.5,实际复用95步并替换一页。
改后 SVG 和 PDF 与独立零复用编译完全一致;来源映射仅归一化测试目录
和会话修订号,来源及几何一致。第一次探测的编辑序号冲突、原始会话地图
差异和临时目录冲突均保留日志。这个样例只用于正确性对照。
`target/p3-pdf-page-graphics-state-native` 的回执:
- `directed/receipt.json` 为 `f9e6681b3d977aa6d784f4ae1a196264bf34ea530e19d23cd87ca05494b5d16f`。
- `late-objects/receipt.json` 为 `5921924488c3970584db61872af99961b24efb5c00487042781e71869f2640ab`。
- `regression.log` 为 `9dd038475f57182020feeb500788a81a39f92bbef53aef581496f8d3052b5c71`。
### 宏展开调度与实际浮点表达式
将 `\expandafter` 的暂存 token 留在同一次展开调度。执行第二个 token