Restore PDF Forms from native formats

This commit is contained in:
gloamxun committed 2026-11-27 15:31:24 +08:00
1 parent c2d3312e5a
commit 57a7097857
12 files changed
+300 -87

No files matched your search

+24 -1
View File
@@ -1,7 +1,8 @@
//! Geometry and captured contents of a native PDF Form XObject.
use crate::{execution::NativeShipout, render::DisplayList};
use crate::{execution::{NativeBox, NativeShipout, Token}, render::DisplayList};
use serde::{Deserialize, Serialize};
use std::sync::Arc;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct FormUse {
@@ -11,9 +12,30 @@ pub struct FormUse {
pub depth: i64,
}
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub(crate) struct RegisteredForm {
pub form: FormUse,
pub contents: FormContents,
}
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub(crate) enum FormContents {
Pending(Arc<FormBody>),
Shipped,
DiscardedAtDump,
}
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub(crate) struct FormBody {
pub box_node: NativeBox,
pub attributes: Vec<Token>,
pub resources: Vec<Token>,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ShippedForm {
pub form: FormUse,
pub resource_number: u32,
pub attributes: Vec<u8>,
pub canvas: NativeShipout,
}
@@ -21,5 +43,6 @@ pub struct ShippedForm {
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct FormDisplay {
pub form: FormUse,
pub resource_number: u32,
pub list: DisplayList,
}
@@ -16,6 +16,8 @@ pub(crate) enum ObjectBody {
Link,
FormatLink,
Form,
FormResources,
DiscardedAtDump,
Direct(Vec<u8>),
Stream {
attributes: Vec<u8>,
@@ -31,7 +33,8 @@ pub(crate) enum ObjectBody {
impl ObjectBody {
fn len(&self) -> usize {
match self {
Self::Page | Self::Link | Self::FormatLink | Self::Form => 0,
Self::Page | Self::Link | Self::FormatLink | Self::Form
| Self::FormResources | Self::DiscardedAtDump => 0,
Self::Direct(bytes) => bytes.len(),
Self::Stream { attributes, bytes } => attributes.len().saturating_add(bytes.len()),
Self::File {
@@ -48,7 +51,10 @@ impl ObjectBody {
fn parse(&self) -> Result<Object, String> {
match self {
Self::Page | Self::Link | Self::FormatLink | Self::Form => Err("expected a generic native PDF object".into()),
Self::Page | Self::Link | Self::FormatLink | Self::Form | Self::FormResources => {
Err("expected a generic native PDF object".into())
}
Self::DiscardedAtDump => Err("PDF object belongs to the format job and cannot be reused".into()),
Self::Direct(bytes) => parse_value(bytes),
Self::File { .. } => Err("PDF object file payload was not read before export".into()),
Self::Stream { attributes, bytes } => {
@@ -85,10 +91,12 @@ impl PdfObjects {
}
pub(crate) fn contains(&self, number: u32) -> bool {
self.entry(number)
.is_some_and(|entry| {
!matches!(entry.as_deref(), Some(ObjectBody::Page | ObjectBody::Link | ObjectBody::FormatLink | ObjectBody::Form))
})
matches!(self.entry(number).map(Option::as_deref),
Some(None | Some(ObjectBody::Direct(_) | ObjectBody::Stream { .. } | ObjectBody::File { .. })))
}
pub(crate) fn is_discarded_at_dump(&self, number: u32) -> bool {
matches!(self.entry(number).and_then(Option::as_deref), Some(ObjectBody::DiscardedAtDump))
}
pub(crate) fn is_reserved(&self, number: u32) -> bool {
@@ -113,6 +121,16 @@ impl PdfObjects {
self.allocate(Some(Arc::new(ObjectBody::Form)), limit)
}
pub(crate) fn reserve_form_resources(&mut self, limit: usize) -> Result<u32, String> {
self.allocate(Some(Arc::new(ObjectBody::FormResources)), limit)
}
pub(crate) fn form_numbers(&self) -> impl Iterator<Item = u32> + '_ {
self.values.iter().enumerate().filter_map(|(index, entry)| {
matches!(entry.as_deref(), Some(ObjectBody::Form)).then_some(index as u32 + 1)
})
}
pub(crate) fn reserve_link(&mut self, limit: usize) -> Result<u32, String> {
self.allocate(Some(Arc::new(ObjectBody::Link)), limit)
}
@@ -125,27 +143,23 @@ impl PdfObjects {
self.last_link.unwrap_or_default() as i32
}
pub(crate) fn retain_format_links(&mut self) -> bool {
let Some(last_link) = self
.values
.iter()
.rposition(|entry| matches!(entry.as_deref(), Some(ObjectBody::Link)))
else {
return false;
};
// The reservation survives the format, but pdfTeX assigns a new
// object to the annotation when it ships the restored whatsit.
self.values.truncate(last_link + 1);
for entry in &mut self.values {
*entry = matches!(entry.as_deref(), Some(ObjectBody::Link))
.then(|| Arc::new(ObjectBody::FormatLink));
pub(crate) fn retain_format_objects(&mut self) -> bool {
for (index, entry) in self.values.iter_mut().enumerate() {
let number = index as u32 + 1;
let replacement = match entry.as_deref() {
// A restored link whatsit gets its own annotation object when shipped.
Some(ObjectBody::Link) => ObjectBody::FormatLink,
Some(ObjectBody::Page | ObjectBody::FormResources) => ObjectBody::DiscardedAtDump,
_ if self.written.contains(&number) => ObjectBody::DiscardedAtDump,
_ => continue,
};
*entry = Some(Arc::new(replacement));
}
self.written.clear();
self.last = 0;
self.last_link = None;
self.bytes = 0;
self.bytes = self.values.iter().flatten().map(|body| body.len()).sum();
self.page_references.clear();
true
!self.values.is_empty()
}
fn is_link(&self, number: u32) -> bool {
@@ -530,6 +544,9 @@ impl ResourceOutput {
}
}
let page_objects: BTreeSet<_> = objects.page_references.values().copied().collect();
let form_objects: BTreeSet<_> = pages.iter().flat_map(|page| {
page.forms.iter().flat_map(|form| [form.form.number, form.resource_number])
}).collect();
let annotation_entries = pages
.iter()
.map(|page| {
@@ -583,9 +600,12 @@ impl ResourceOutput {
link_references.entry(number).or_insert(None);
continue;
}
if values.contains_key(&number) || page_objects.contains(&number) {
if values.contains_key(&number) || page_objects.contains(&number) || form_objects.contains(&number) {
continue;
}
if objects.is_discarded_at_dump(number) {
return Err(format!("PDF object {number} belongs to the format job and cannot be reused"));
}
let value = objects.written_body(number)?.parse()?;
references(&value, &mut pending)?;
values.insert(number, value);
@@ -622,8 +642,8 @@ impl ResourceOutput {
self,
output: &mut Vec<Vec<u8>>,
diagnostics: &mut Vec<String>,
mut ids: BTreeMap<u32, u32>,
) -> Result<RemappedResources, String> {
let mut ids = BTreeMap::new();
let mut page_objects = BTreeMap::new();
for (page, number) in self.page_references {
// The real Page dictionary fills this slot at export. A missing