pdfox 0.1.0

A pure-Rust PDF library — create, parse, and render PDF documents with zero C dependencies
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
/// PDF content stream builder.
///
/// Generates the raw PDF content stream operators for a page.
/// Supports graphics state, paths, text, and images.

use crate::color::Color;
use crate::font::BuiltinFont;

/// Line cap styles
#[derive(Debug, Clone, Copy)]
pub enum LineCap {
    Butt = 0,
    Round = 1,
    Square = 2,
}

/// Line join styles
#[derive(Debug, Clone, Copy)]
pub enum LineJoin {
    Miter = 0,
    Round = 1,
    Bevel = 2,
}

/// Text alignment
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum TextAlign {
    Left,
    Center,
    Right,
}

/// A content stream being built up incrementally
pub struct ContentStream {
    ops: Vec<String>,
}

impl ContentStream {
    pub fn new() -> Self {
        Self { ops: Vec::new() }
    }

    fn push(&mut self, op: impl Into<String>) -> &mut Self {
        self.ops.push(op.into());
        self
    }

    // ── Graphics State ──────────────────────────────────────────────────────

    /// Save graphics state
    pub fn save(&mut self) -> &mut Self {
        self.push("q")
    }

    /// Restore graphics state
    pub fn restore(&mut self) -> &mut Self {
        self.push("Q")
    }

    /// Set line width
    pub fn line_width(&mut self, w: f64) -> &mut Self {
        self.push(format!("{:.4} w", w))
    }

    /// Set line cap style
    pub fn line_cap(&mut self, cap: LineCap) -> &mut Self {
        self.push(format!("{} J", cap as u8))
    }

    /// Set line join style
    pub fn line_join(&mut self, join: LineJoin) -> &mut Self {
        self.push(format!("{} j", join as u8))
    }

    /// Set dash pattern: `dash` is the on/off lengths, `phase` is offset
    pub fn dash_pattern(&mut self, dash: &[f64], phase: f64) -> &mut Self {
        let parts: Vec<String> = dash.iter().map(|d| format!("{:.2}", d)).collect();
        self.push(format!("[{}] {:.2} d", parts.join(" "), phase))
    }

    /// Set fill color
    pub fn fill_color(&mut self, color: Color) -> &mut Self {
        self.push(color.fill_op())
    }

    /// Set stroke color
    pub fn stroke_color(&mut self, color: Color) -> &mut Self {
        self.push(color.stroke_op())
    }

    // ── Path Construction ────────────────────────────────────────────────────

    /// Move to point
    pub fn move_to(&mut self, x: f64, y: f64) -> &mut Self {
        self.push(format!("{:.4} {:.4} m", x, y))
    }

    /// Line to point
    pub fn line_to(&mut self, x: f64, y: f64) -> &mut Self {
        self.push(format!("{:.4} {:.4} l", x, y))
    }

    /// Cubic bezier curve
    pub fn curve_to(&mut self, x1: f64, y1: f64, x2: f64, y2: f64, x3: f64, y3: f64) -> &mut Self {
        self.push(format!("{:.4} {:.4} {:.4} {:.4} {:.4} {:.4} c", x1, y1, x2, y2, x3, y3))
    }

    /// Close the current subpath
    pub fn close_path(&mut self) -> &mut Self {
        self.push("h")
    }

    // ── Path Painting ────────────────────────────────────────────────────────

    /// Stroke the path
    pub fn stroke(&mut self) -> &mut Self {
        self.push("S")
    }

    /// Fill the path (nonzero winding)
    pub fn fill(&mut self) -> &mut Self {
        self.push("f")
    }

    /// Fill then stroke
    pub fn fill_stroke(&mut self) -> &mut Self {
        self.push("B")
    }

    /// End path without painting
    pub fn end_path(&mut self) -> &mut Self {
        self.push("n")
    }

    // ── High-Level Shape Helpers ─────────────────────────────────────────────

    /// Draw a rectangle (origin is bottom-left in PDF coords)
    pub fn rect(&mut self, x: f64, y: f64, w: f64, h: f64) -> &mut Self {
        self.push(format!("{:.4} {:.4} {:.4} {:.4} re", x, y, w, h))
    }

    /// Draw a filled rectangle
    pub fn filled_rect(&mut self, x: f64, y: f64, w: f64, h: f64, color: Color) -> &mut Self {
        self.save();
        self.fill_color(color);
        self.rect(x, y, w, h);
        self.fill();
        self.restore();
        self
    }

    /// Draw a stroked rectangle
    pub fn stroked_rect(
        &mut self,
        x: f64, y: f64, w: f64, h: f64,
        color: Color,
        line_w: f64,
    ) -> &mut Self {
        self.save();
        self.stroke_color(color);
        self.line_width(line_w);
        self.rect(x, y, w, h);
        self.stroke();
        self.restore();
        self
    }

    /// Draw a line between two points
    pub fn line(
        &mut self,
        x1: f64, y1: f64, x2: f64, y2: f64,
        color: Color,
        width: f64,
    ) -> &mut Self {
        self.save();
        self.stroke_color(color);
        self.line_width(width);
        self.move_to(x1, y1);
        self.line_to(x2, y2);
        self.stroke();
        self.restore();
        self
    }

    /// Draw a circle (approximated with 4 bezier curves)
    pub fn circle(&mut self, cx: f64, cy: f64, r: f64) -> &mut Self {
        // Magic number: 4*(sqrt(2)-1)/3 ≈ 0.5523 for circle bezier approximation
        let k = 0.5523 * r;
        self.move_to(cx + r, cy);
        self.curve_to(cx + r, cy + k, cx + k, cy + r, cx, cy + r);
        self.curve_to(cx - k, cy + r, cx - r, cy + k, cx - r, cy);
        self.curve_to(cx - r, cy - k, cx - k, cy - r, cx, cy - r);
        self.curve_to(cx + k, cy - r, cx + r, cy - k, cx + r, cy);
        self.close_path();
        self
    }

    // ── Text Operations ──────────────────────────────────────────────────────

    /// Begin text block
    pub fn begin_text(&mut self) -> &mut Self {
        self.push("BT")
    }

    /// End text block
    pub fn end_text(&mut self) -> &mut Self {
        self.push("ET")
    }

    /// Set font and size (font_key is the resource name, e.g. "F1")
    pub fn set_font(&mut self, font_key: &str, size: f64) -> &mut Self {
        self.push(format!("/{} {:.4} Tf", font_key, size))
    }

    /// Move text position (absolute)
    pub fn text_position(&mut self, x: f64, y: f64) -> &mut Self {
        self.push(format!("{:.4} {:.4} Td", x, y))
    }

    /// Move to an absolute position by using the text matrix
    pub fn text_matrix(&mut self, x: f64, y: f64) -> &mut Self {
        self.push(format!("1 0 0 1 {:.4} {:.4} Tm", x, y))
    }

    /// Show a text string
    pub fn show_text(&mut self, text: &str) -> &mut Self {
        let escaped = pdf_string_escape(text);
        self.push(format!("({}) Tj", escaped))
    }

    /// Set text leading (line spacing)
    pub fn text_leading(&mut self, leading: f64) -> &mut Self {
        self.push(format!("{:.4} TL", leading))
    }

    /// Move to next line and show text
    pub fn next_line_text(&mut self, text: &str) -> &mut Self {
        let escaped = pdf_string_escape(text);
        self.push(format!("({}) '", escaped))
    }

    /// Set character spacing
    pub fn char_spacing(&mut self, spacing: f64) -> &mut Self {
        self.push(format!("{:.4} Tc", spacing))
    }

    /// Set word spacing
    pub fn word_spacing(&mut self, spacing: f64) -> &mut Self {
        self.push(format!("{:.4} Tw", spacing))
    }

    /// Set text rise (superscript/subscript)
    pub fn text_rise(&mut self, rise: f64) -> &mut Self {
        self.push(format!("{:.4} Ts", rise))
    }

    /// High-level: draw text at position with font+size+color, aligned
    pub fn draw_text(
        &mut self,
        text: &str,
        x: f64,
        y: f64,
        font_key: &str,
        font: BuiltinFont,
        size: f64,
        color: Color,
        align: TextAlign,
    ) -> &mut Self {
        let actual_x = match align {
            TextAlign::Left => x,
            TextAlign::Center => x - font.string_width(text, size) / 2.0,
            TextAlign::Right => x - font.string_width(text, size),
        };

        self.save();
        self.fill_color(color);
        self.begin_text();
        self.set_font(font_key, size);
        self.text_matrix(actual_x, y);
        self.show_text(text);
        self.end_text();
        self.restore();
        self
    }

    /// Word-wrapped text block within a bounding box.
    /// Returns the y-coordinate below the last line.
    pub fn draw_text_box(
        &mut self,
        text: &str,
        x: f64,
        y: f64,
        width: f64,
        font_key: &str,
        font: BuiltinFont,
        size: f64,
        color: Color,
        line_height: f64,
    ) -> f64 {
        let words: Vec<&str> = text.split_whitespace().collect();
        let space_w = font.char_width(' ') * size / 1000.0;

        let mut lines: Vec<String> = Vec::new();
        let mut current_line = String::new();
        let mut current_width = 0.0;

        for word in &words {
            let word_w = font.string_width(word, size);
            if current_line.is_empty() {
                current_line.push_str(word);
                current_width = word_w;
            } else if current_width + space_w + word_w <= width {
                current_line.push(' ');
                current_line.push_str(word);
                current_width += space_w + word_w;
            } else {
                lines.push(current_line.clone());
                current_line = word.to_string();
                current_width = word_w;
            }
        }
        if !current_line.is_empty() {
            lines.push(current_line);
        }

        self.save();
        self.fill_color(color);
        self.begin_text();
        self.set_font(font_key, size);

        let mut cur_y = y;
        for line in &lines {
            self.text_matrix(x, cur_y);
            self.show_text(line);
            cur_y -= line_height;
        }

        self.end_text();
        self.restore();

        cur_y
    }

    // ── Image Operations ─────────────────────────────────────────────────────

    /// Place an image XObject at position (x, y) with given dimensions
    /// `image_key` is the resource name (e.g. "Im1")
    pub fn draw_image(&mut self, image_key: &str, x: f64, y: f64, w: f64, h: f64) -> &mut Self {
        self.save();
        // PDF image transformation matrix: [w 0 0 h x y] cm
        self.push(format!("{:.4} 0 0 {:.4} {:.4} {:.4} cm", w, h, x, y));
        self.push(format!("/{} Do", image_key));
        self.restore();
        self
    }

    // ── Clipping ─────────────────────────────────────────────────────────────

    /// Set clipping region to current path
    pub fn clip(&mut self) -> &mut Self {
        self.push("W")
    }

    // ── Transformation Matrix ────────────────────────────────────────────────

    /// Apply a transformation matrix [a b c d e f]
    pub fn transform(&mut self, a: f64, b: f64, c: f64, d: f64, e: f64, f: f64) -> &mut Self {
        self.push(format!("{:.4} {:.4} {:.4} {:.4} {:.4} {:.4} cm", a, b, c, d, e, f))
    }

    /// Translate
    pub fn translate(&mut self, tx: f64, ty: f64) -> &mut Self {
        self.transform(1.0, 0.0, 0.0, 1.0, tx, ty)
    }

    /// Scale
    pub fn scale(&mut self, sx: f64, sy: f64) -> &mut Self {
        self.transform(sx, 0.0, 0.0, sy, 0.0, 0.0)
    }

    /// Rotate by angle in radians
    pub fn rotate(&mut self, angle: f64) -> &mut Self {
        let cos = angle.cos();
        let sin = angle.sin();
        self.transform(cos, sin, -sin, cos, 0.0, 0.0)
    }

    // ── Serialization ────────────────────────────────────────────────────────

    /// Serialize to raw bytes for use in a PDF stream
    pub fn to_bytes(&self) -> Vec<u8> {
        self.ops.join("\n").into_bytes()
    }
}


// ── Public helpers used by other modules ─────────────────────────────────────

/// Push a raw operator string (used by watermark/header renderers that build
/// their own content outside of ContentStream's typed API).
/// This is identical to the private `push` method but accessible from sibling modules.
impl ContentStream {
    pub fn push_raw(&mut self, op: impl Into<String>) -> &mut Self {
        self.ops.push(op.into());
        self
    }
}

/// Escape `text` for use inside a PDF literal string `(...)`.
/// Identical to the private `pdf_string_escape` but pub(crate) so watermark.rs can use it.
pub fn escape_for_stream(text: &str) -> String {
    pdf_string_escape(text)
}

fn pdf_string_escape(text: &str) -> String {
    let mut out = String::new();
    for c in text.chars() {
        match c {
            '(' => out.push_str("\\("),
            ')' => out.push_str("\\)"),
            '\\' => out.push_str("\\\\"),
            '\r' => out.push_str("\\r"),
            '\n' => out.push_str("\\n"),
            c if c as u32 > 127 => {
                // Map to WinAnsiEncoding (Latin-1, 0x80-0xFF) where possible.
                // Characters outside this range cannot be represented in Type1 fonts
                // with WinAnsiEncoding and must be replaced with ASCII fallbacks.
                let code = c as u32;
                if (0x80..=0xFF).contains(&code) {
                    out.push_str(&format!("\\{:03o}", code));
                } else {
                    let replacement = match c {
                        '\u{2014}' => "--",  // em dash
                        '\u{2013}' => "-",   // en dash
                        '\u{2018}' | '\u{2019}' => "'", // curly single quotes
                        '\u{201C}' | '\u{201D}' => "\"", // curly double quotes
                        '\u{2026}' => "...", // ellipsis
                        '\u{00A0}' => " ",   // non-breaking space
                        _ => "?",
                    };
                    out.push_str(replacement);
                }
            }
            _ => out.push(c),
        }
    }
    out
}