Skip to main content

quillmark_pdfform/
lib.rs

1//! A Typst-free Quillmark backend that fills existing PDF forms. A `pdfform`
2//! quill ships two assets: `form.pdf`, the stripped background (the normalized
3//! form with its `/AcroForm`, widget annotations, and page `/Annots` removed),
4//! and `form.json`, the value-free field spec. The backend binds document
5//! values against `compile_data` and writes a fresh AcroForm onto the
6//! background via the `quillmark-pdf` stamping spine; it never reads or
7//! reconciles a foreign AcroForm.
8
9mod bind;
10mod flatten;
11mod form;
12mod resolve;
13mod typography;
14
15use bind::BoundWidget;
16use flatten::flatten as flatten_to_pdf;
17use form::FormSpec;
18use quillmark_core::quill::QuillConfig;
19use quillmark_core::session::SessionHandle;
20use quillmark_core::{
21    Artifact, Backend, ChangeSet, LiveSession, OutputFormat, Quill, RenderError, RenderOptions,
22    RenderResult, RenderedRegion,
23};
24use quillmark_pdf::regions_of;
25use quillmark_pdf::{stamp, FieldSpec, StampOptions};
26
27use {
28    hayro::hayro_interpret::{font::FontQuery, InterpreterSettings},
29    hayro::hayro_syntax::Pdf as HayroPdf,
30    hayro::{render as hayro_render, RenderCache, RenderSettings},
31    hayro_svg::{convert as hayro_svg_convert, RenderCache as SvgCache, SvgRenderSettings},
32    std::sync::Arc,
33};
34
35const FORM_PDF: &str = "form.pdf";
36const FORM_JSON: &str = "form.json";
37
38/// 2× at 72 pt/in, matching the core `RenderOptions::ppi` default.
39const DEFAULT_PPI: f32 = 144.0;
40
41const SUPPORTED_FORMATS: &[OutputFormat] =
42    &[OutputFormat::Pdf, OutputFormat::Svg, OutputFormat::Png];
43
44/// The PDF-form backend.
45#[derive(Debug, Default)]
46pub struct PdfformBackend;
47
48impl quillmark_core::backend::sealed::Sealed for PdfformBackend {}
49
50impl Backend for PdfformBackend {
51    fn id(&self) -> &'static str {
52        "pdfform"
53    }
54
55    fn supported_formats(&self) -> &'static [OutputFormat] {
56        SUPPORTED_FORMATS
57    }
58
59    fn open(
60        &self,
61        source: &Quill,
62        json_data: &serde_json::Value,
63    ) -> Result<LiveSession, RenderError> {
64        let files = source.files();
65        let base_pdf = files
66            .get_file(FORM_PDF)
67            .ok_or_else(|| {
68                RenderError::coded(
69                    "pdfform::missing_form_pdf",
70                    format!("pdfform quill is missing its `{FORM_PDF}` background"),
71                )
72            })?
73            .to_vec();
74        let form_json = files.get_file(FORM_JSON).ok_or_else(|| {
75            RenderError::coded(
76                "pdfform::missing_form_json",
77                format!("pdfform quill is missing its `{FORM_JSON}` field spec"),
78            )
79        })?;
80
81        let spec = FormSpec::parse(form_json)
82            .map_err(|e| RenderError::coded(e.code(), e.to_string()))?;
83
84        // Page boxes drive the top-left → bottom-left flip (honouring a
85        // non-zero page origin), and reading them surfaces a malformed base early.
86        let page_boxes = quillmark_pdf::page_media_boxes(&base_pdf)?;
87
88        let bound = bind::bind_widgets(&spec, source.config(), &page_boxes)
89            .map_err(|e| RenderError::coded(e.code(), e.to_string()))?;
90
91        let field_specs = resolve_field_specs(&bound, json_data);
92
93        let flat = flatten_and_parse(&base_pdf, &field_specs)?;
94
95        Ok(LiveSession::new(
96            Box::new(PdfformSession {
97                base_pdf,
98                bound,
99                field_specs,
100                page_boxes,
101                flat,
102            }),
103            source.config().clone(),
104        ))
105    }
106}
107
108/// Whether `path` resolves against `config` as a schema address.
109///
110/// Binding a widget needs more: the resolved field must also project to a widget
111/// shape. The grammar alone is what the Typst helper's `_qm-known-path` states a
112/// second time, so `quillmark/tests/address_grammar.rs` compares the two here.
113#[doc(hidden)]
114pub fn resolves_schema_address(config: &QuillConfig, path: &str) -> bool {
115    bind::bind(config, "", path).is_ok()
116}
117
118fn resolve_field_specs(bound: &[BoundWidget], json_data: &serde_json::Value) -> Vec<FieldSpec> {
119    bound
120        .iter()
121        .map(|widget| resolve::field_spec(widget, json_data))
122        .collect()
123}
124
125/// Bake `field_specs` into the base as content-stream operators, then parse the
126/// result for hayro. Both halves happen here so the two places `field_specs`
127/// are set are the two places the derived PDF moves.
128///
129/// A parse failure is this crate flattening to something malformed, never a
130/// property of the output format asking for it.
131fn flatten_and_parse(base_pdf: &[u8], field_specs: &[FieldSpec]) -> Result<HayroPdf, RenderError> {
132    let flat = flatten_to_pdf(base_pdf.to_vec(), field_specs)?;
133    HayroPdf::new(flat).map_err(|_| {
134        RenderError::coded(
135            "pdfform::flat_parse_failed",
136            "failed to parse the flattened PDF for rasterisation",
137        )
138    })
139}
140
141struct PdfformSession {
142    base_pdf: Vec<u8>,
143    bound: Vec<BoundWidget>,
144    field_specs: Vec<FieldSpec>,
145    /// Cached so `page_size_pt` need not reparse.
146    page_boxes: Vec<[f32; 4]>,
147    /// The base with `field_specs` baked in, parsed: the render paths hold
148    /// pages rather than bytes to reparse per paint.
149    flat: HayroPdf,
150}
151
152impl SessionHandle for PdfformSession {
153    fn render(&self, opts: &RenderOptions) -> Result<RenderResult, RenderError> {
154        let format = opts.output_format.unwrap_or(OutputFormat::Pdf);
155        if !SUPPORTED_FORMATS.contains(&format) {
156            return Err(quillmark_core::unsupported_format(
157                format,
158                "pdfform",
159                SUPPORTED_FORMATS,
160            ));
161        }
162
163        if format == OutputFormat::Svg {
164            return self.render_svg();
165        }
166        if format == OutputFormat::Png {
167            let scale = opts.ppi.unwrap_or(DEFAULT_PPI) / 72.0;
168            return self.render_png(scale);
169        }
170
171        // PDF output is always an interactive AcroForm; value-flattening backs
172        // only the raster paths, never a PDF deliverable.
173        let producer = opts.producer.clone().unwrap_or_else(default_producer);
174        let stamp_opts = StampOptions::default().with_producer(producer);
175        let stamped = stamp(self.base_pdf.clone(), &self.field_specs, &stamp_opts)?;
176
177        Ok(RenderResult::new(
178            vec![Artifact::new(stamped, OutputFormat::Pdf)],
179            OutputFormat::Pdf,
180        ))
181    }
182
183    fn page_count(&self) -> usize {
184        self.page_boxes.len()
185    }
186
187    fn page_size_pt(&self, page: usize) -> Option<(f32, f32)> {
188        let [x0, y0, x1, y1] = *self.page_boxes.get(page)?;
189        Some((x1 - x0, y1 - y0))
190    }
191
192    fn render_rgba(&self, page: usize, scale: f32) -> Option<(u32, u32, Vec<u8>)> {
193        let p = self.flat.pages().get(page)?;
194        let cache = RenderCache::new();
195        let interp = standard_font_settings();
196        let render_settings = scaled_render_settings(scale);
197        let pixmap = hayro_render(p, &cache, &interp, &render_settings);
198        let w = pixmap.width() as u32;
199        let h = pixmap.height() as u32;
200        let bytes: Vec<u8> = pixmap
201            .take_unpremultiplied()
202            .into_iter()
203            .flat_map(|px| [px.r, px.g, px.b, px.a])
204            .collect();
205        Some((w, h, bytes))
206    }
207
208    fn regions(&self) -> Vec<RenderedRegion> {
209        regions_of(&self.field_specs)
210    }
211
212    /// Specs and flat PDF swap together only after both succeed. The background
213    /// never changes, so field deltas are the only visible delta.
214    fn update(&mut self, json_data: &serde_json::Value) -> Result<ChangeSet, RenderError> {
215        let field_specs = resolve_field_specs(&self.bound, json_data);
216        let flat = flatten_and_parse(&self.base_pdf, &field_specs)?;
217
218        let mut dirty_pages: Vec<usize> = self
219            .field_specs
220            .iter()
221            .zip(&field_specs)
222            .filter(|(old, new)| old != new)
223            .map(|(_, new)| new.page)
224            .collect();
225        dirty_pages.sort_unstable();
226        dirty_pages.dedup();
227
228        self.field_specs = field_specs;
229        self.flat = flat;
230
231        Ok(ChangeSet::new(self.page_boxes.len(), dirty_pages))
232    }
233}
234
235impl PdfformSession {
236    fn render_svg(&self) -> Result<RenderResult, RenderError> {
237        let interp = standard_font_settings();
238        let svg_settings = SvgRenderSettings {
239            bg_color: [255, 255, 255, 255],
240        };
241        let artifacts: Vec<Artifact> = self
242            .flat
243            .pages()
244            .iter()
245            .map(|page| {
246                let cache = SvgCache::new();
247                let svg = hayro_svg_convert(page, &cache, &interp, &svg_settings);
248                Artifact::new(svg.into_bytes(), OutputFormat::Svg)
249            })
250            .collect();
251
252        Ok(RenderResult::new(artifacts, OutputFormat::Svg))
253    }
254
255    /// `scale` is device pixels per PDF point (`ppi / 72`).
256    fn render_png(&self, scale: f32) -> Result<RenderResult, RenderError> {
257        let interp = standard_font_settings();
258        let render_settings = scaled_render_settings(scale);
259
260        let mut artifacts = Vec::with_capacity(self.flat.pages().len());
261        for page in self.flat.pages().iter() {
262            let cache = RenderCache::new();
263            let pixmap = hayro_render(page, &cache, &interp, &render_settings);
264            let png = pixmap.into_png().map_err(|e| {
265                RenderError::coded(
266                    "pdfform::png_encoding",
267                    format!("failed to encode page as PNG: {e}"),
268                )
269            })?;
270            artifacts.push(Artifact::new(png, OutputFormat::Png));
271        }
272
273        Ok(RenderResult::new(artifacts, OutputFormat::Png))
274    }
275}
276
277/// Shared by the RGBA canvas path and the PNG artifact path, which must agree
278/// or a preview and its export drift apart.
279fn scaled_render_settings(scale: f32) -> RenderSettings {
280    use hayro::vello_cpu::color::palette::css::WHITE;
281    RenderSettings {
282        x_scale: scale,
283        y_scale: scale,
284        bg_color: WHITE,
285        ..Default::default()
286    }
287}
288
289/// Satisfies standard Type1 font queries from hayro's embedded font data:
290/// required for the flat PDF's `Helv` and `ZaDb` content streams.
291fn standard_font_settings() -> InterpreterSettings {
292    InterpreterSettings {
293        font_resolver: Arc::new(|query| match query {
294            FontQuery::Standard(s) => Some(s.get_font_data()),
295            FontQuery::Fallback(f) => Some(f.pick_standard_font().get_font_data()),
296        }),
297        ..Default::default()
298    }
299}
300
301/// Owned by the backend, never defaulted from the leaf spine's version.
302fn default_producer() -> String {
303    format!("Quillmark {}", env!("CARGO_PKG_VERSION"))
304}