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
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
//! A Pretty Darn Fast library for creating PDF files. Currently, only simple vector graphics and simple text are supported.
//!
//!

//! # Example
//!
//! ```
//! use pdfpdf::{Color, Pdf};
//!
//! Pdf::new()
//!     .add_page(180.0, 240.0)
//!     .set_color(&Color::rgb(0, 0, 248))
//!     .draw_circle(90.0, 120.0, 50.0)
//!     .write_to("example.pdf")
//!     .expect("Failed to write to file");
//! ```
//!
//! To use this library you need to add it as a dependency in your
//! `Cargo.toml`:
//!
//! ```toml
//! [dependencies]
//! pdfpdf = "0.2"
//! ```
//!
//! More working examples can be found in [here]
//! (https://github.com/saethlin/pdfpdf/tree/master/examples).
#![deny(missing_docs)]

#[macro_use]
extern crate lazy_static;
extern crate deflate;
extern crate num;

use num::NumCast;
use std::fs::File;
use std::io;

mod graphicsstate;
mod fonts;
mod text;
pub use fonts::Font;
pub use graphicsstate::{Color, Matrix};
pub use text::Alignment;

// Represents a PDF internal object
struct PdfObject {
    offset: usize,
    id: usize,
    is_page: bool,
}

/// The top-level struct that represents a (partially) in-memory PDF file
pub struct Pdf {
    buffer: Vec<u8>,
    page_buffer: Vec<u8>,
    objects: Vec<PdfObject>,
    width: f64,
    height: f64,
    fonts: Vec<fonts::Font>,
    font_size: f64,
    compress: bool,
}

impl Pdf {
    /// Create a new blank PDF document
    #[inline]
    pub fn new() -> Self {
        let mut buffer = Vec::new();
        buffer.extend(b"%PDF-1.7\n%\xB5\xED\xAE\xFB\n");
        Pdf {
            buffer: buffer,
            page_buffer: Vec::new(),
            objects: vec![
                PdfObject {
                    offset: 0,
                    id: 1,
                    is_page: false,
                },
                PdfObject {
                    offset: 0,
                    id: 2,
                    is_page: false,
                },
            ],
            width: 400.0,
            height: 400.0,
            fonts: vec![Font::Helvetica],
            font_size: 12.0,
            compress: true,
        }
    }

    /// Create a new blank PDF document without compression
    #[inline]
    pub fn new_uncompressed() -> Self {
        let mut this = Pdf::new();
        this.compress = false;
        this
    }

    /// Move then pen, starting a new path
    #[inline]
    fn move_to(&mut self, x: f64, y: f64) -> &mut Self {
        self.page_buffer.extend(
            format!("{:.2} {:.2} m ", x, y).bytes(),
        );
        self
    }

    /// Draw a line from the current location
    #[inline]
    fn line_to(&mut self, x: f64, y: f64) -> &mut Self {
        self.page_buffer.extend(
            format!("{:.2} {:.2} l ", x, y).bytes(),
        );
        self
    }

    // Draw a cubic Bézier curve
    #[inline]
    fn curve_to(
        &mut self,
        (x1, y1): (f64, f64),
        (x2, y2): (f64, f64),
        (x3, y3): (f64, f64),
    ) -> &mut Self {
        self.page_buffer.extend(
            format!(
                "{:.2} {:.2} {:.2} {:.2} {:.2} {:.2} c\n",
                x1,
                y1,
                x2,
                y2,
                x3,
                y3
            ).bytes(),
        );
        self
    }

    /// Set the current line width
    #[inline]
    pub fn set_line_width<N: NumCast>(&mut self, width: N) -> &mut Self {
        self.page_buffer.extend(
            format!(
                "{:.2} w\n",
                width.to_f64().unwrap()
            ).bytes(),
        );
        self
    }

    /// Set the color for all subsequent drawing operations
    #[inline]
    pub fn set_color(&mut self, color: &Color) -> &mut Self {
        let norm = |color| color as f64 / 255.0;
        self.page_buffer.extend(
            format!(
                "{:.2} {:.2} {:.2} SC\n",
                norm(color.red),
                norm(color.green),
                norm(color.blue),
            ).bytes(),
        );
        self.page_buffer.extend(
            format!(
                "{:.2} {:.2} {:.2} rg\n",
                norm(color.red),
                norm(color.green),
                norm(color.blue),
            ).bytes(),
        );

        self
    }

    /// Apply a coordinate transformation to all subsequent drawing calls
    /// Consecutive applications of this function are cumulative
    #[inline]
    pub fn transform(&mut self, m: Matrix) -> &mut Self {
        self.page_buffer.extend(format!("{} cm\n", m).bytes());
        self
    }

    /// Draw a circle with the current drawing configuration,
    /// based on http://spencermortensen.com/articles/bezier-circle/
    #[inline]
    pub fn draw_circle<N1: NumCast, N2: NumCast, N3: NumCast>(
        &mut self,
        x: N1,
        y: N2,
        radius: N3,
    ) -> &mut Self {
        let x = x.to_f64().unwrap();
        let y = y.to_f64().unwrap();
        let radius = radius.to_f64().unwrap();
        let top = y - radius;
        let bottom = y + radius;
        let left = x - radius;
        let right = x + radius;
        let c = 0.551915024494;
        let leftp = x - (radius * c);
        let rightp = x + (radius * c);
        let topp = y - (radius * c);
        let bottomp = y + (radius * c);
        self.move_to(x, top);
        self.curve_to((leftp, top), (left, topp), (left, y));
        self.curve_to((left, bottomp), (leftp, bottom), (x, bottom));
        self.curve_to((rightp, bottom), (right, bottomp), (right, y));
        self.curve_to((right, topp), (rightp, top), (x, top));
        self.page_buffer.extend_from_slice(b"S\n");
        self
    }

    /// Draw a line between all these points in the order they appear
    #[inline]
    pub fn draw_line<I, N: NumCast>(&mut self, mut points: I) -> &mut Self
    where
        I: Iterator<Item = (N, N)>,
    {
        if let Some((x, y)) = points.next() {
            let x = x.to_f64().unwrap();
            let y = y.to_f64().unwrap();
            self.move_to(x, y);
            for (x, y) in points {
                let x = x.to_f64().unwrap();
                let y = y.to_f64().unwrap();
                self.line_to(x, y);
            }
        }
        self.page_buffer.extend_from_slice(b"S\n");
        self
    }

    /// Draw a rectangle that extends from x1, y1 to x2, y2
    #[inline]
    pub fn draw_rectangle_filled<N1: NumCast, N2: NumCast, N3: NumCast, N4: NumCast>(
        &mut self,
        x: N1,
        y: N2,
        width: N3,
        height: N4,
    ) -> &mut Self {
        self.page_buffer.extend(
            format!(
                "{:.2} {:.2} {:.2} {:.2} re\n",
                x.to_f64().unwrap(),
                y.to_f64().unwrap(),
                width.to_f64().unwrap(),
                height.to_f64().unwrap()
            ).bytes(),
        );
        // Fill path using Nonzero Winding Number Rule
        self.page_buffer.extend_from_slice(b"f\n");
        self
    }

    #[inline]
    /// Set the font for all subsequent drawing calls
    pub fn font<N: NumCast>(&mut self, font: Font, size: N) -> &mut Self {
        self.fonts.push(font);
        self.font_size = size.to_f64().unwrap();
        self
    }

    /// Draw text at a given location with the current settings
    #[inline]
    pub fn draw_text<N1: NumCast, N2: NumCast>(
        &mut self,
        x: N1,
        y: N2,
        alignment: Alignment,
        text: &str,
    ) -> &mut Self {

        let x = x.to_f64().unwrap();
        let y = y.to_f64().unwrap();
        let widths = &fonts::GLYPH_WIDTHS[self.fonts.iter().last().unwrap()];
        let height = self.font_size;

        self.page_buffer.extend(
            format!("BT\n/F{} {} Tf\n", self.fonts.len() - 1, self.font_size).bytes(),
        );

        let num_lines = text.split('\n').count();
        for (l, line) in text.split('\n').enumerate() {
            let line_width = line.chars()
                .filter(|c| *c != '\n')
                .map(|c| *widths.get(&c).unwrap_or(&1.0))
                .sum::<f64>() * self.font_size;

            let (line_x, line_y) = match alignment {
                Alignment::TopLeft => (x, y - height * (l as f64 + 1.0)),
                Alignment::TopRight => (x - line_width, y - height * (l as f64 + 1.0)),
                Alignment::TopCenter => (x - line_width / 2.0, y - height * (l as f64 + 1.0)),
                Alignment::CenterLeft => (
                    x,
                    (y - height / 3.0) -
                        (l as f64 - (num_lines as f64 - 1.0) / 2.0) *
                            height * 1.25,
                ),
                Alignment::CenterRight => (
                    x - line_width,
                    (y - height / 3.0) -
                        (l as f64 - (num_lines as f64 - 1.0) / 2.0) *
                            height * 1.25,
                ),
                Alignment::CenterCenter => (
                    x - line_width / 2.0,
                    (y - height / 3.0) -
                        (l as f64 - (num_lines as f64 - 1.0) / 2.0) *
                            height * 1.25,
                ),
                Alignment::BottomLeft => (x, y + (num_lines - l - 1) as f64 * 1.25 * height),
                Alignment::BottomRight => (
                    x - line_width,
                    y + (num_lines - l - 1) as f64 * 1.25 * height,
                ),
                Alignment::BottomCenter => (
                    x - line_width / 2.0,
                    y + (num_lines - l - 1) as f64 * 1.25 * height,
                ),
            };

            self.page_buffer.extend(
                format!(
                    "1 0 0 1 {} {} Tm (",
                    line_x,
                    line_y
                ).bytes(),
            );
            for c in line.chars() {
                let data = format!("\\{:o}", c as u32);
                self.page_buffer.extend(data.bytes());
            }
            self.page_buffer.extend(b") Tj\n");
        }
        self.page_buffer.extend(b"ET\n");
        self
    }

    // TODO: test with multi-page documents
    /// Move to a new page in the PDF document
    #[inline]
    pub fn add_page<N1: NumCast, N2: NumCast>(&mut self, width: N1, height: N2) -> &mut Self {
        // Compress and write out the previous page if it exists
        if !self.page_buffer.is_empty() {
            self.flush_page();
        }

        self.page_buffer.extend(
            "/DeviceRGB cs /DeviceRGB CS\n".bytes(),
        );
        self.width = width.to_f64().unwrap();
        self.height = height.to_f64().unwrap();
        self
    }

    /// Dump a page out to disk
    fn flush_page(&mut self) {
        // Write out the data stream for this page
        let obj_id = self.objects.iter().map(|o| o.id).max().unwrap() + 1;
        self.objects.push(PdfObject {
            offset: self.buffer.len(),
            id: obj_id,
            is_page: false,
        });

        self.buffer.extend(format!("{} 0 obj\n", obj_id).bytes());
        if self.compress {
            let (compressed, rounds) = compress(self.page_buffer.clone());
            self.buffer.extend(
                format!(
                    "<</Length {} /Filter [{}]>>\nstream\n",
                    compressed.len(),
                    "/FlateDecode ".repeat(rounds)
                ).bytes(),
            );
            self.buffer.extend(compressed.iter());
            self.buffer.extend("endstream\nendobj\n".bytes())
        } else {
            self.buffer.extend(
                format!("<</Length {}>>\nstream\n", self.page_buffer.len()).bytes(),
            );
            self.buffer.extend(self.page_buffer.iter());
            self.buffer.extend("endstream\nendobj\n".bytes());
        }
        self.page_buffer.clear();

        // Write out the page object
        let obj_id = self.objects.iter().map(|o| o.id).max().unwrap() + 1;
        self.objects.push(PdfObject {
            offset: self.buffer.len(),
            id: obj_id,
            is_page: true,
        });
        self.buffer.extend(format!("{} 0 obj\n", obj_id).bytes());
        self.buffer.extend_from_slice(b"<</Type /Page\n");
        self.buffer.extend_from_slice(b"/Parent 2 0 R\n");
        // TODO: Temporary restricted fonts
        for (f, font) in self.fonts.iter().enumerate() {
            self.buffer.extend(
            format!("/Resources << /Font << /F{} << /Type /Font /Subtype /Type1 /BaseFont /{:?} /Encoding /WinAnsiEncoding>> >> >>\n", f, font).bytes(),
            );
        }

        self.buffer.extend(
            format!("/MediaBox [0 0 {} {}]\n", self.width, self.height).bytes(),
        );
        self.buffer.extend(
            format!("/Contents {} 0 R >>\n", obj_id - 1)
                .bytes(),
        );

        self.buffer.extend("endobj\n".bytes());
        self.fonts.clear();
    }

    /// Write the in-memory PDF representation to disk
    pub fn write_to(&mut self, filename: &str) -> io::Result<()> {
        use std::io::Write;

        if !self.page_buffer.is_empty() {
            self.flush_page();
        }

        // Write out the page tree object
        self.objects[1].offset = self.buffer.len();
        self.buffer.extend_from_slice(b"2 0 obj\n");
        self.buffer.extend_from_slice(b"<</Type /Pages\n");
        self.buffer.extend(
            format!(
                "/Count {}\n",
                self.objects.iter().filter(|o| o.is_page).count()
            ).bytes(),
        );
        self.buffer.extend_from_slice(b"/Kids [");
        for obj in self.objects.iter().filter(|obj| obj.is_page) {
            self.buffer.extend(format!("{} 0 R ", obj.id).bytes());
        }
        self.buffer.pop();
        self.buffer.extend_from_slice(b"]>>\nendobj\n");

        // Write out the catalog dictionary object
        self.objects[0].offset = self.buffer.len();
        self.buffer.extend_from_slice(
            b"1 0 obj\n<</Type /Catalog\n/Pages 2 0 R>>\nendobj\n",
        );

        // Write the cross-reference table
        let startxref = self.buffer.len();
        self.buffer.extend_from_slice(b"xref\n");
        self.buffer.extend(
            format!("0 {}\n", self.objects.len() + 1).bytes(),
        );
        self.buffer.extend_from_slice(b"0000000000 65535 f \n");
        self.objects.sort_by(|a, b| a.id.cmp(&b.id));

        for obj in &self.objects {
            self.buffer.extend(
                format!("{:010} 00000 f \n", obj.offset).bytes(),
            );
        }

        // Write the document trailer
        self.buffer.extend_from_slice(b"trailer\n");
        self.buffer.extend(
            format!("<</Size {}\n", self.objects.len())
                .bytes(),
        );
        self.buffer.extend_from_slice(b"/Root 1 0 R>>\n");

        // Write the offset to the xref table
        self.buffer.extend(
            format!("startxref\n{}\n", startxref).bytes(),
        );

        // Write the PDF EOF
        self.buffer.extend_from_slice(b"%%EOF");

        File::create(filename)?.write_all(self.buffer.as_slice())
    }
}

fn compress(input: Vec<u8>) -> (Vec<u8>, usize) {
    let mut compressed = input;
    let mut rounds = 0;
    loop {
        let another = deflate::deflate_bytes_zlib(compressed.as_slice());
        if another.len() < compressed.len() {
            compressed = another;
            rounds += 1;
        } else {
            break;
        }
    }
    (compressed, rounds)
}