18 releases (9 breaking)

0.10.0 Jun 1, 2024
0.9.2 Nov 1, 2023
0.7.1 May 3, 2023
0.6.0 Jun 10, 2022
0.3.1 Jul 14, 2021

#122 in Encoding

Download history 1121/week @ 2024-04-04 1455/week @ 2024-04-11 1221/week @ 2024-04-18 1420/week @ 2024-04-25 1300/week @ 2024-05-02 1180/week @ 2024-05-09 1915/week @ 2024-05-16 1611/week @ 2024-05-23 1443/week @ 2024-05-30 1658/week @ 2024-06-06 1605/week @ 2024-06-13 1780/week @ 2024-06-20 1390/week @ 2024-06-27 1309/week @ 2024-07-04 1518/week @ 2024-07-11 1240/week @ 2024-07-18

5,750 downloads per month
Used in 21 crates (7 directly)

MIT/Apache

2MB
7.5K SLoC

pdf-writer

Crates.io Documentation

A step-by-step PDF writer.

[dependencies]
pdf-writer = "0.10"

The entry point into the API is the main Pdf, 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::{Pdf, 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 pdf = Pdf::new();
pdf.catalog(catalog_id).pages(page_tree_id);
pdf.pages(page_tree_id).kids([page_id]).count(1);
pdf.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", pdf.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