Skip to main content

strata_render/
pdf.rs

1//! Pure-Rust Vector PDF 1.7 Exporter directly from `strata_render::compositor::DisplayList`.
2//!
3//! Compiles rectangles, cubic-Bezier rounded rects, borders, gradients, vector SVG paths,
4//! text runs, embedded RGB/RGBA images, transforms, opacity states, and clip regions directly
5//! into spec-compliant PDF 1.7 bytes with exact `xref` byte offsets and optional `FlateDecode`
6//! compression (using `miniz_oxide`, zero extra crates).
7
8use crate::compositor::{DisplayList, DrawCommand};
9use std::fmt::Write as _;
10use strata_layout::Rect;
11use strata_style::types::{BorderRadius, Color, FontWeight};
12
13/// Standard print page geometry in PDF points (`72 pt = 1 inch`).
14#[derive(Debug, Clone, Copy, PartialEq)]
15pub enum PdfPageSize {
16    /// ISO 216 A4 (`595.28 x 841.89 pt` = `210 x 297 mm`).
17    A4,
18    /// US Letter (`612.0 x 792.0 pt` = `8.5 x 11 in`).
19    Letter,
20    /// Explicit page dimensions in PDF points (`72 pt/in`).
21    Custom { width_pt: f32, height_pt: f32 },
22}
23
24impl PdfPageSize {
25    pub const fn dimensions_pt(self) -> (f32, f32) {
26        match self {
27            Self::A4 => (595.28, 841.89),
28            Self::Letter => (612.0, 792.0),
29            Self::Custom {
30                width_pt,
31                height_pt,
32            } => (width_pt, height_pt),
33        }
34    }
35}
36
37/// Configuration controlling pure-Rust Vector PDF 1.7 compilation.
38#[derive(Debug, Clone, PartialEq)]
39pub struct PdfExportOptions {
40    pub page_size: PdfPageSize,
41    /// Uniform page margin in PDF points (default: `24.0 pt`).
42    pub margin_pt: f32,
43    /// Logical CSS DPI reference (`96.0` CSS px per inch -> `0.75 pt/px`).
44    pub dpi: f32,
45    /// Automatically scale the viewport uniformly to fit inside the printable page box.
46    pub fit_to_page: bool,
47    /// Compress PDF content & image streams with zlib (`FlateDecode`).
48    pub compress_streams: bool,
49    pub title: String,
50    pub author: String,
51}
52
53impl Default for PdfExportOptions {
54    fn default() -> Self {
55        Self {
56            page_size: PdfPageSize::A4,
57            margin_pt: 24.0,
58            dpi: 96.0,
59            fit_to_page: true,
60            compress_streams: false,
61            title: "Strata Vector Export".into(),
62            author: "Strata Engine".into(),
63        }
64    }
65}
66
67struct PdfImageObject {
68    name: String,
69    width: u32,
70    height: u32,
71    rgb_bytes: Vec<u8>,
72}
73
74/// Compiles a [`DisplayList`] directly into a valid, spec-compliant Vector PDF 1.7 document.
75pub fn export_display_list_to_pdf(
76    display_list: &DisplayList,
77    viewport_width_px: f32,
78    viewport_height_px: f32,
79    options: &PdfExportOptions,
80) -> Vec<u8> {
81    let (page_w, page_h) = options.page_size.dimensions_pt();
82    let margin = options.margin_pt.max(0.0);
83    let avail_w = (page_w - margin * 2.0).max(1.0);
84    let avail_h = (page_h - margin * 2.0).max(1.0);
85    let vw = viewport_width_px.max(1.0);
86    let vh = viewport_height_px.max(1.0);
87
88    let pt_per_px = 72.0 / options.dpi.max(1.0);
89    let scale = if options.fit_to_page {
90        (avail_w / vw).min(avail_h / vh)
91    } else {
92        pt_per_px
93    };
94
95    let mut content = String::with_capacity(4096);
96    let mut images: Vec<PdfImageObject> = Vec::new();
97    let mut ext_gstates: Vec<(String, f32)> = Vec::new();
98
99    // Establish CSS top-left origin -> PDF bottom-left origin transform:
100    // x_pdf = margin + x_px * scale
101    // y_pdf = (page_h - margin) - y_px * scale
102    let _ = writeln!(content, "q");
103    let _ = writeln!(
104        content,
105        "{scale:.4} 0 0 {scale:.4} {margin:.3} {:.3} cm",
106        page_h - margin
107    );
108
109    let flip_y = |y: f32| -y;
110    let alpha_f = |a: u8| a as f32 / 255.0;
111
112    for cmd in &display_list.commands {
113        match cmd {
114            DrawCommand::DrawRect { bounds, color } => {
115                if color.a == 0 || bounds.width <= 0.0 || bounds.height <= 0.0 {
116                    continue;
117                }
118                emit_alpha_state(&mut content, &mut ext_gstates, alpha_f(color.a));
119                emit_fill_rgb(&mut content, *color);
120                let _ = writeln!(
121                    content,
122                    "{:.3} {:.3} {:.3} {:.3} re f",
123                    bounds.x,
124                    flip_y(bounds.y + bounds.height),
125                    bounds.width,
126                    bounds.height
127                );
128            }
129            DrawCommand::DrawRoundedRect {
130                bounds,
131                color,
132                border_radius,
133                border_width,
134                border_color,
135            } => {
136                if bounds.width <= 0.0 || bounds.height <= 0.0 {
137                    continue;
138                }
139                if color.a > 0 {
140                    emit_alpha_state(&mut content, &mut ext_gstates, alpha_f(color.a));
141                    emit_fill_rgb(&mut content, *color);
142                    emit_rounded_rect_path(&mut content, *bounds, *border_radius);
143                    let _ = writeln!(content, "f");
144                }
145                if let Some(bc) = border_color {
146                    let bw = border_width
147                        .top
148                        .max(border_width.right)
149                        .max(border_width.bottom)
150                        .max(border_width.left);
151                    if bw > 0.0 && bc.a > 0 {
152                        emit_alpha_state(&mut content, &mut ext_gstates, alpha_f(bc.a));
153                        emit_stroke_rgb(&mut content, *bc);
154                        let _ = writeln!(content, "{bw:.3} w");
155                        emit_rounded_rect_path(&mut content, *bounds, *border_radius);
156                        let _ = writeln!(content, "S");
157                    }
158                }
159            }
160            DrawCommand::DrawLinearGradient {
161                bounds,
162                stops,
163                border_radius,
164                ..
165            } => {
166                if let Some(first) = stops.first() {
167                    emit_alpha_state(&mut content, &mut ext_gstates, alpha_f(first.color.a));
168                    emit_fill_rgb(&mut content, first.color);
169                    emit_rounded_rect_path(&mut content, *bounds, *border_radius);
170                    let _ = writeln!(content, "f");
171                }
172            }
173            DrawCommand::DrawBorder {
174                bounds,
175                widths,
176                color,
177                border_radius,
178                ..
179            } => {
180                let bw = widths
181                    .top
182                    .max(widths.right)
183                    .max(widths.bottom)
184                    .max(widths.left);
185                if bw > 0.0 && color.a > 0 {
186                    emit_alpha_state(&mut content, &mut ext_gstates, alpha_f(color.a));
187                    emit_stroke_rgb(&mut content, *color);
188                    let _ = writeln!(content, "{bw:.3} w");
189                    emit_rounded_rect_path(&mut content, *bounds, *border_radius);
190                    let _ = writeln!(content, "S");
191                }
192            }
193            DrawCommand::DrawText {
194                origin,
195                text,
196                font_size,
197                font_weight,
198                color,
199                is_monospace,
200                ..
201            } => {
202                if text.is_empty() || color.a == 0 {
203                    continue;
204                }
205                emit_alpha_state(&mut content, &mut ext_gstates, alpha_f(color.a));
206                emit_fill_rgb(&mut content, *color);
207                let font_key = match (*is_monospace, *font_weight) {
208                    (true, _) => "/F3",
209                    (
210                        false,
211                        FontWeight::Bold
212                        | FontWeight::SemiBold
213                        | FontWeight::ExtraBold
214                        | FontWeight::Black,
215                    ) => "/F2",
216                    _ => "/F1",
217                };
218                let baseline_y = flip_y(origin.1 + font_size * 0.82);
219                let _ = writeln!(
220                    content,
221                    "BT {font_key} {:.2} Tf 1 0 0 1 {:.3} {:.3} Tm ({}) Tj ET",
222                    font_size.max(1.0),
223                    origin.0,
224                    baseline_y,
225                    escape_pdf_string(text)
226                );
227            }
228            DrawCommand::DrawTextFragments { fragments } => {
229                for frag in fragments {
230                    if frag.text.is_empty() || frag.style.color.a == 0 {
231                        continue;
232                    }
233                    emit_alpha_state(&mut content, &mut ext_gstates, alpha_f(frag.style.color.a));
234                    emit_fill_rgb(&mut content, frag.style.color);
235                    let font_key = if frag.style.is_monospace { "/F3" } else { "/F1" };
236                    let baseline_y = flip_y(frag.bounds.y + frag.style.font_size * 0.82);
237                    let _ = writeln!(
238                        content,
239                        "BT {font_key} {:.2} Tf 1 0 0 1 {:.3} {:.3} Tm ({}) Tj ET",
240                        frag.style.font_size.max(1.0),
241                        frag.bounds.x,
242                        baseline_y,
243                        escape_pdf_string(&frag.text)
244                    );
245                }
246            }
247            DrawCommand::DrawSvgPath {
248                bounds,
249                path_data,
250                stroke_color,
251                fill_color,
252                stroke_width,
253                view_box,
254                ..
255            } => {
256                let sx = if view_box.0 > 0.0 {
257                    bounds.width / view_box.0
258                } else {
259                    1.0
260                };
261                let sy = if view_box.1 > 0.0 {
262                    bounds.height / view_box.1
263                } else {
264                    1.0
265                };
266                let path_ops = svg_path_to_pdf_ops(path_data, bounds.x, bounds.y, sx, sy);
267                if path_ops.is_empty() {
268                    continue;
269                }
270                if let Some(fc) = fill_color {
271                    if fc.a > 0 {
272                        emit_alpha_state(&mut content, &mut ext_gstates, alpha_f(fc.a));
273                        emit_fill_rgb(&mut content, *fc);
274                        content.push_str(&path_ops);
275                        let _ = writeln!(content, "f");
276                    }
277                }
278                if let Some(sc) = stroke_color {
279                    if sc.a > 0 && *stroke_width > 0.0 {
280                        emit_alpha_state(&mut content, &mut ext_gstates, alpha_f(sc.a));
281                        emit_stroke_rgb(&mut content, *sc);
282                        let _ = writeln!(content, "{:.3} w", stroke_width);
283                        content.push_str(&path_ops);
284                        let _ = writeln!(content, "S");
285                    }
286                }
287            }
288            DrawCommand::DrawImage { bounds, image } => {
289                if image.width > 0 && image.height > 0 && !image.data.is_empty() {
290                    let img_idx = images.len() + 1;
291                    let name = format!("Im{img_idx}");
292                    let mut rgb = Vec::with_capacity((image.width * image.height * 3) as usize);
293                    for px in image.data.chunks_exact(4) {
294                        rgb.push(px[0]);
295                        rgb.push(px[1]);
296                        rgb.push(px[2]);
297                    }
298                    images.push(PdfImageObject {
299                        name: name.clone(),
300                        width: image.width,
301                        height: image.height,
302                        rgb_bytes: rgb,
303                    });
304                    let _ = writeln!(
305                        content,
306                        "q {:.3} 0 0 {:.3} {:.3} {:.3} cm /{name} Do Q",
307                        bounds.width,
308                        bounds.height,
309                        bounds.x,
310                        flip_y(bounds.y + bounds.height)
311                    );
312                }
313            }
314            DrawCommand::PushClip { bounds, radius } => {
315                let _ = writeln!(content, "q");
316                emit_rounded_rect_path(&mut content, *bounds, *radius);
317                let _ = writeln!(content, "W n");
318            }
319            DrawCommand::PopClip => {
320                let _ = writeln!(content, "Q");
321            }
322            DrawCommand::PushOpacity { alpha } => {
323                let _ = writeln!(content, "q");
324                emit_alpha_state(&mut content, &mut ext_gstates, *alpha);
325            }
326            DrawCommand::PopOpacity => {
327                let _ = writeln!(content, "Q");
328            }
329            DrawCommand::PushTransform { matrix } => {
330                let m = &matrix.m;
331                // Extract 2D affine components `[a b c d e f]` from column-major 4x4 matrix
332                let _ = writeln!(
333                    content,
334                    "q {:.4} {:.4} {:.4} {:.4} {:.3} {:.3} cm",
335                    m[0], -m[1], -m[4], m[5], m[12], -m[13]
336                );
337            }
338            DrawCommand::PopTransform => {
339                let _ = writeln!(content, "Q");
340            }
341            _ => {}
342        }
343    }
344
345    let _ = writeln!(content, "Q");
346
347    assemble_pdf_document(
348        page_w,
349        page_h,
350        content.as_bytes(),
351        &images,
352        &ext_gstates,
353        options,
354    )
355}
356
357fn emit_fill_rgb(out: &mut String, color: Color) {
358    let _ = writeln!(
359        out,
360        "{:.4} {:.4} {:.4} rg",
361        color.r as f32 / 255.0,
362        color.g as f32 / 255.0,
363        color.b as f32 / 255.0
364    );
365}
366
367fn emit_stroke_rgb(out: &mut String, color: Color) {
368    let _ = writeln!(
369        out,
370        "{:.4} {:.4} {:.4} RG",
371        color.r as f32 / 255.0,
372        color.g as f32 / 255.0,
373        color.b as f32 / 255.0
374    );
375}
376
377fn emit_alpha_state(out: &mut String, gstates: &mut Vec<(String, f32)>, alpha: f32) {
378    let a = alpha.clamp(0.0, 1.0);
379    if (a - 1.0).abs() < 0.005 {
380        return;
381    }
382    let key = if let Some((existing, _)) = gstates.iter().find(|(_, v)| (*v - a).abs() < 0.005) {
383        existing.clone()
384    } else {
385        let name = format!("GS{}", gstates.len() + 1);
386        gstates.push((name.clone(), a));
387        name
388    };
389    let _ = writeln!(out, "/{key} gs");
390}
391
392/// Emits a closed rounded rectangle path using exact cubic Bezier corner arcs ($\kappa = 0.55228475$).
393fn emit_rounded_rect_path(out: &mut String, b: Rect, r: BorderRadius) {
394    let max_r = (b.width * 0.5).min(b.height * 0.5).max(0.0);
395    let tl = r.top_left.clamp(0.0, max_r);
396    let tr = r.top_right.clamp(0.0, max_r);
397    let br = r.bottom_right.clamp(0.0, max_r);
398    let bl = r.bottom_left.clamp(0.0, max_r);
399
400    let x0 = b.x;
401    let x1 = b.x + b.width;
402    let y_top = -b.y;
403    let y_bot = -(b.y + b.height);
404
405    if tl < 0.01 && tr < 0.01 && br < 0.01 && bl < 0.01 {
406        let _ = writeln!(out, "{x0:.3} {y_bot:.3} {:.3} {:.3} re", b.width, b.height);
407        return;
408    }
409
410    const K: f32 = 0.552_284_8;
411    let _ = writeln!(out, "{:.3} {:.3} m", x0 + tl, y_top);
412    let _ = writeln!(out, "{:.3} {:.3} l", x1 - tr, y_top);
413    if tr > 0.01 {
414        let _ = writeln!(
415            out,
416            "{:.3} {:.3} {:.3} {:.3} {:.3} {:.3} c",
417            x1 - tr * (1.0 - K),
418            y_top,
419            x1,
420            y_top - tr * (1.0 - K),
421            x1,
422            y_top - tr
423        );
424    }
425    let _ = writeln!(out, "{:.3} {:.3} l", x1, y_bot + br);
426    if br > 0.01 {
427        let _ = writeln!(
428            out,
429            "{:.3} {:.3} {:.3} {:.3} {:.3} {:.3} c",
430            x1,
431            y_bot + br * (1.0 - K),
432            x1 - br * (1.0 - K),
433            y_bot,
434            x1 - br,
435            y_bot
436        );
437    }
438    let _ = writeln!(out, "{:.3} {:.3} l", x0 + bl, y_bot);
439    if bl > 0.01 {
440        let _ = writeln!(
441            out,
442            "{:.3} {:.3} {:.3} {:.3} {:.3} {:.3} c",
443            x0 + bl * (1.0 - K),
444            y_bot,
445            x0,
446            y_bot + bl * (1.0 - K),
447            x0,
448            y_bot + bl
449        );
450    }
451    let _ = writeln!(out, "{:.3} {:.3} l", x0, y_top - tl);
452    if tl > 0.01 {
453        let _ = writeln!(
454            out,
455            "{:.3} {:.3} {:.3} {:.3} {:.3} {:.3} c",
456            x0,
457            y_top - tl * (1.0 - K),
458            x0 + tl * (1.0 - K),
459            y_top,
460            x0 + tl,
461            y_top
462        );
463    }
464    let _ = writeln!(out, "h");
465}
466
467/// Minimal SVG `d` path translator (`M`/`m`, `L`/`l`, `H`/`h`, `V`/`v`, `C`/`c`, `Z`/`z`) to PDF operators.
468fn svg_path_to_pdf_ops(d: &str, ox: f32, oy: f32, sx: f32, sy: f32) -> String {
469    let mut out = String::new();
470    let mut tokens = Vec::new();
471    let mut cur = String::new();
472    for ch in d.chars() {
473        if ch.is_ascii_alphabetic() {
474            if !cur.is_empty() {
475                tokens.push(std::mem::take(&mut cur));
476            }
477            tokens.push(ch.to_string());
478        } else if ch.is_ascii_whitespace() || ch == ',' {
479            if !cur.is_empty() {
480                tokens.push(std::mem::take(&mut cur));
481            }
482        } else {
483            cur.push(ch);
484        }
485    }
486    if !cur.is_empty() {
487        tokens.push(cur);
488    }
489
490    let mut i = 0;
491    let mut cx = 0.0f32;
492    let mut cy = 0.0f32;
493    let mut cmd = ' ';
494    let tx = |x: f32| ox + x * sx;
495    let ty = |y: f32| -(oy + y * sy);
496
497    while i < tokens.len() {
498        if tokens[i].len() == 1 && tokens[i].chars().next().unwrap().is_ascii_alphabetic() {
499            cmd = tokens[i].chars().next().unwrap();
500            i += 1;
501        }
502        match cmd {
503            'M' | 'L' if i + 1 < tokens.len() => {
504                if let (Ok(x), Ok(y)) = (tokens[i].parse::<f32>(), tokens[i + 1].parse::<f32>()) {
505                    cx = x;
506                    cy = y;
507                    let op = if cmd == 'M' { 'm' } else { 'l' };
508                    let _ = writeln!(out, "{:.3} {:.3} {op}", tx(cx), ty(cy));
509                    if cmd == 'M' {
510                        cmd = 'L';
511                    }
512                }
513                i += 2;
514            }
515            'm' | 'l' if i + 1 < tokens.len() => {
516                if let (Ok(dx), Ok(dy)) = (tokens[i].parse::<f32>(), tokens[i + 1].parse::<f32>()) {
517                    cx += dx;
518                    cy += dy;
519                    let op = if cmd == 'm' { 'm' } else { 'l' };
520                    let _ = writeln!(out, "{:.3} {:.3} {op}", tx(cx), ty(cy));
521                    if cmd == 'm' {
522                        cmd = 'l';
523                    }
524                }
525                i += 2;
526            }
527            'H' if i < tokens.len() => {
528                if let Ok(x) = tokens[i].parse::<f32>() {
529                    cx = x;
530                    let _ = writeln!(out, "{:.3} {:.3} l", tx(cx), ty(cy));
531                }
532                i += 1;
533            }
534            'V' if i < tokens.len() => {
535                if let Ok(y) = tokens[i].parse::<f32>() {
536                    cy = y;
537                    let _ = writeln!(out, "{:.3} {:.3} l", tx(cx), ty(cy));
538                }
539                i += 1;
540            }
541            'C' if i + 5 < tokens.len() => {
542                if let (Ok(x1), Ok(y1), Ok(x2), Ok(y2), Ok(x), Ok(y)) = (
543                    tokens[i].parse::<f32>(),
544                    tokens[i + 1].parse::<f32>(),
545                    tokens[i + 2].parse::<f32>(),
546                    tokens[i + 3].parse::<f32>(),
547                    tokens[i + 4].parse::<f32>(),
548                    tokens[i + 5].parse::<f32>(),
549                ) {
550                    cx = x;
551                    cy = y;
552                    let _ = writeln!(
553                        out,
554                        "{:.3} {:.3} {:.3} {:.3} {:.3} {:.3} c",
555                        tx(x1),
556                        ty(y1),
557                        tx(x2),
558                        ty(y2),
559                        tx(x),
560                        ty(y)
561                    );
562                }
563                i += 6;
564            }
565            'Z' | 'z' => {
566                let _ = writeln!(out, "h");
567                cmd = ' ';
568            }
569            _ => i += 1,
570        }
571    }
572    out
573}
574
575fn escape_pdf_string(s: &str) -> String {
576    let mut out = String::with_capacity(s.len());
577    for ch in s.chars() {
578        match ch {
579            '\\' => out.push_str("\\\\"),
580            '(' => out.push_str("\\("),
581            ')' => out.push_str("\\)"),
582            '\n' | '\r' => out.push(' '),
583            c if c.is_ascii() => out.push(c),
584            _ => out.push('?'),
585        }
586    }
587    out
588}
589
590fn assemble_pdf_document(
591    page_w: f32,
592    page_h: f32,
593    raw_content: &[u8],
594    images: &[PdfImageObject],
595    ext_gstates: &[(String, f32)],
596    options: &PdfExportOptions,
597) -> Vec<u8> {
598    let mut pdf = Vec::with_capacity(raw_content.len() + 2048);
599    // Binary comment marker per PDF 1.7 Section 7.5.2
600    pdf.extend_from_slice(b"%PDF-1.7\n%\xE2\xE3\xCF\xD3\n");
601
602    let mut offsets: Vec<usize> = Vec::new();
603    let push_obj = |pdf: &mut Vec<u8>, offsets: &mut Vec<usize>, id: usize, body: &[u8]| {
604        offsets.push(pdf.len());
605        pdf.extend_from_slice(format!("{id} 0 obj\n").as_bytes());
606        pdf.extend_from_slice(body);
607        pdf.extend_from_slice(b"\nendobj\n");
608    };
609
610    // Object ID layout:
611    // 1: Catalog
612    // 2: Pages
613    // 3: Page
614    // 4: Font F1 (Helvetica)
615    // 5: Font F2 (Helvetica-Bold)
616    // 6: Font F3 (Courier)
617    // 7: Info dictionary
618    // 8: Content stream
619    // 9..: Image XObjects (one per image)
620    let first_img_id = 9usize;
621
622    push_obj(
623        &mut pdf,
624        &mut offsets,
625        1,
626        b"<< /Type /Catalog /Pages 2 0 R >>",
627    );
628    push_obj(
629        &mut pdf,
630        &mut offsets,
631        2,
632        b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>",
633    );
634
635    // Build Page Resources dictionary (Fonts + ExtGStates + Image XObjects)
636    let mut resources =
637        String::from("<< /Font << /F1 4 0 R /F2 5 0 R /F3 6 0 R >>");
638    if !ext_gstates.is_empty() {
639        resources.push_str(" /ExtGState <<");
640        for (name, alpha) in ext_gstates {
641            let _ = write!(
642                resources,
643                " /{name} << /Type /ExtGState /ca {alpha:.3} /CA {alpha:.3} >>"
644            );
645        }
646        resources.push_str(" >>");
647    }
648    if !images.is_empty() {
649        resources.push_str(" /XObject <<");
650        for (idx, img) in images.iter().enumerate() {
651            let _ = write!(resources, " /{} {} 0 R", img.name, first_img_id + idx);
652        }
653        resources.push_str(" >>");
654    }
655    resources.push_str(" >>");
656
657    let page_dict = format!(
658        "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 {page_w:.2} {page_h:.2}] /Resources {resources} /Contents 8 0 R >>"
659    );
660    push_obj(&mut pdf, &mut offsets, 3, page_dict.as_bytes());
661
662    push_obj(
663        &mut pdf,
664        &mut offsets,
665        4,
666        b"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>",
667    );
668    push_obj(
669        &mut pdf,
670        &mut offsets,
671        5,
672        b"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica-Bold >>",
673    );
674    push_obj(
675        &mut pdf,
676        &mut offsets,
677        6,
678        b"<< /Type /Font /Subtype /Type1 /BaseFont /Courier >>",
679    );
680
681    let info_dict = format!(
682        "<< /Title ({}) /Author ({}) /Producer (Strata Pure-Rust Vector PDF 1.7 Engine) >>",
683        escape_pdf_string(&options.title),
684        escape_pdf_string(&options.author)
685    );
686    push_obj(&mut pdf, &mut offsets, 7, info_dict.as_bytes());
687
688    // Object 8: Content stream (optionally FlateDecode compressed via miniz_oxide)
689    let (stream_bytes, filter_clause) = if options.compress_streams {
690        (
691            miniz_oxide::deflate::compress_to_vec_zlib(raw_content, 6),
692            " /Filter /FlateDecode",
693        )
694    } else {
695        (raw_content.to_vec(), "")
696    };
697    let mut content_obj = Vec::with_capacity(stream_bytes.len() + 96);
698    content_obj.extend_from_slice(
699        format!(
700            "<< /Length {}{filter_clause} >>\nstream\n",
701            stream_bytes.len()
702        )
703        .as_bytes(),
704    );
705    content_obj.extend_from_slice(&stream_bytes);
706    content_obj.extend_from_slice(b"\nendstream");
707    push_obj(&mut pdf, &mut offsets, 8, &content_obj);
708
709    // Objects 9+: Embedded RGB Image XObjects
710    for (idx, img) in images.iter().enumerate() {
711        let (img_data, img_filter) = if options.compress_streams {
712            (
713                miniz_oxide::deflate::compress_to_vec_zlib(&img.rgb_bytes, 6),
714                " /Filter /FlateDecode",
715            )
716        } else {
717            (img.rgb_bytes.clone(), "")
718        };
719        let mut obj = Vec::with_capacity(img_data.len() + 160);
720        obj.extend_from_slice(
721            format!(
722                "<< /Type /XObject /Subtype /Image /Width {} /Height {} /ColorSpace /DeviceRGB /BitsPerComponent 8 /Length {}{img_filter} >>\nstream\n",
723                img.width,
724                img.height,
725                img_data.len()
726            )
727            .as_bytes(),
728        );
729        obj.extend_from_slice(&img_data);
730        obj.extend_from_slice(b"\nendstream");
731        push_obj(&mut pdf, &mut offsets, first_img_id + idx, &obj);
732    }
733
734    // Exact spec-compliant xref table
735    let xref_offset = pdf.len();
736    let total_objs = offsets.len() + 1;
737    pdf.extend_from_slice(format!("xref\n0 {total_objs}\n").as_bytes());
738    pdf.extend_from_slice(b"0000000000 65535 f \n");
739    for off in &offsets {
740        pdf.extend_from_slice(format!("{off:010} 00000 n \n").as_bytes());
741    }
742    pdf.extend_from_slice(
743        format!(
744            "trailer\n<< /Size {total_objs} /Root 1 0 R /Info 7 0 R >>\nstartxref\n{xref_offset}\n%%EOF\n"
745        )
746        .as_bytes(),
747    );
748
749    pdf
750}