#pdf #writer

pdf-writer

A step-by-step PDF writer

9 releases (5 breaking)

0.6.0 Jun 10, 2022
0.5.0 Mar 18, 2022
0.4.1 Dec 6, 2021
0.3.2 Aug 24, 2021
0.1.0 May 22, 2021

#321 in Encoding

Download history 687/week @ 2022-12-02 279/week @ 2022-12-09 234/week @ 2022-12-16 112/week @ 2022-12-23 370/week @ 2022-12-30 421/week @ 2023-01-06 486/week @ 2023-01-13 668/week @ 2023-01-20 703/week @ 2023-01-27 646/week @ 2023-02-03 487/week @ 2023-02-10 548/week @ 2023-02-17 392/week @ 2023-02-24 256/week @ 2023-03-03 478/week @ 2023-03-10 1306/week @ 2023-03-17

2,556 downloads per month
Used in 7 crates (3 directly)

MIT/Apache

285KB
5.5K SLoC

pdf-writer

Crates.io Documentation

A step-by-step PDF writer.

[dependencies]
pdf-writer = "0.6"

The entry point into the API is the main PdfWriter, which constructs the document into one big internal buffer. The top-level writer has many methods to create specialized writers for specific PDF objects. These all follow the same general pattern: They borrow the main buffer mutably, expose a builder pattern for writing individual fields in a strongly typed fashion and finish up the object when dropped.

There are a few more top-level structs with internal buffers, like the builder for Content streams, but wherever possible buffers are borrowed from parent writers to minimize allocations.

Minimal example

The following example creates a PDF with a single, empty A4 page.

use pdf_writer::{PdfWriter, Rect, Ref};

// Define some indirect reference ids we'll use.
let catalog_id = Ref::new(1);
let page_tree_id = Ref::new(2);
let page_id = Ref::new(3);

// Write a document catalog and a page tree with one A4 page that uses no resources.
let mut writer = PdfWriter::new();
writer.catalog(catalog_id).pages(page_tree_id);
writer.pages(page_tree_id).kids([page_id]).count(1);
writer.page(page_id)
    .parent(page_tree_id)
    .media_box(Rect::new(0.0, 0.0, 595.0, 842.0))
    .resources();

// Finish with cross-reference table and trailer and write to file.
std::fs::write("target/empty.pdf", writer.finish())?;

For more examples, check out the examples folder in the repository.

Safety

This crate forbids unsafe code, but it depends on a few popular crates that use unsafe internally.

License

This crate is dual-licensed under the MIT and Apache 2.0 licenses.

Dependencies