jflib-pdf#
A PDF writer and reader for JFLib. The writer draws documents page by page
on a canvas, with real paths, embedded font subsets, images, links and bookmarks, instead of one
raster image per page; JFDiagrammer exports its drawings with it, jfWord can use it for its
documents as well. The reader (pdf::read) opens PDF files of every version, encrypted and
damaged ones too, and gives their pages, the text with the position of every glyph, outlines,
links, form fields and attachments, and draws the pages as pixels. pdf::edit changes a document
the reader opened and saves it as an incremental update (it fills in forms and flattens them), or
writes it again in full: encrypted, decrypted, with another password. It is plain Rust, without
the standard library and without a line of unsafe code.
What it writes#
- Pages of any size (A4, Letter or your own), each with a canvas whose origin is the top left corner with y downwards, or PDF's own bottom left with y upwards.
- Vector graphics: paths of lines, cubic and quadratic curves, rectangles, rounded rectangles, ellipses and arcs; fills with the non-zero or even-odd rule; strokes with width, dash pattern, caps, joins and miter limit; transforms, clipping, separate alpha for fills and strokes, RGB colours.
- Gradients and hatches: axial and radial gradients with any number of colour stops (hard edges too) and alpha per stop, either filling a path or painting the whole clip; varying alpha becomes a soft mask. Hatches fill a path with parallel lines of any angle, spacing, width and colour; two hatches cross.
- Images: JPEG files go in unchanged (DCTDecode, also progressive and CMYK); any other pixels
(gray, RGB, RGBA or a
gfx::Surface) are compressed with PNG predictors and DEFLATE, their alpha becomes a soft mask. - Text in embedded subsets of TrueType and OpenType fonts (glyf and CFF outlines), as CID fonts with Identity-H encoding. Lines are shaped with JFLib's shaper (kerning, ligatures, marks, Arabic joining, bidi, fallback fonts), every glyph lands where the shaper put it, and a ToUnicode map keeps search and copy working. Text can be filled, stroked or invisible.
- Links to URIs and to places in the document, and nested bookmarks (outlines).
- Form fields: text fields (alignment, multiline, password, maximum length, comb), check boxes, groups of radio buttons, combo boxes (editable too), list boxes (several choices too), push buttons that open a URI, and empty signature fields to sign later; names with dots make parent fields. Each widget gets its appearance streams, so every viewer shows it as written. The text is in Helvetica (one of the 14 standard fonts, the characters of WinAnsiEncoding) or in a font of the document, which is then embedded in full so a viewer can type any character it has.
- The document information (title, author, subject, keywords, dates) and the same as XMP metadata, and the document's language.
- Encryption with a user and an owner password and the permissions of the user (print, copy, change, annotate, fill in forms, ...): AES-256 (revision 6 of the standard security handler, what readers since Acrobat X open), or AES-128 (revision 4) for older ones. Every string and stream is encrypted, but for the XMP metadata stream when you keep it readable. RC4 is not written.
The output is PDF 1.7 with a classic cross-reference table. It is deterministic: the same
document with the same options always gives the same bytes, with no time stamp unless you set
one. An encrypted one draws its key from the system's random numbers, or from a seed you give
(then the same document and seed give the same bytes). The seed is the key: keep it secret and
use a fresh random one for each encryption, also when the passwords change (the same seed keeps
the old key); leave it out where the system has random numbers, and keep fixed seeds for output
that must be reproducible, such as tests. In the browser a seed is needed (from
crypto.getRandomValues). Not supported: PDF/A. Fonts whose licence (OS/2
fsType) forbids embedding are refused.
What it reads#
- Files of PDF 1.0 to 2.0: classic cross-reference tables and cross-reference streams, object streams, incremental updates and hybrid files. A file whose table is wrong or missing, or that was cut off, is rebuilt from its objects, as Acrobat, pdf.js and Poppler do.
- Encryption of the standard security handler: RC4 with 40 to 128 bits, AES-128 and AES-256 (revisions 2 to 6), with the user or the owner password, or without one when only the owner password is set. The permissions are reported, not enforced.
- Streams with FlateDecode (raw DEFLATE too, and damaged data up to the damage),
LZWDecode, ASCIIHexDecode, ASCII85Decode, RunLengthDecode and the PNG and TIFF predictors.
An image filter (DCT, JPX, JBIG2, CCITTFax) ends the chain:
decode_until_imagegives the JPEG or JPEG 2000 file as it is. - Pages with their boxes, rotation and inherited resources, and their labels ("iv", "A-3").
- Text: every glyph with its characters, position, advance and size, and each page's text
in reading order, laid out as Poppler's
pdftotext -rawdoes (words apart where the glyphs are, Hebrew and Arabic in reading order, fake bold once). Simple fonts through their ToUnicode map, their encoding and the Adobe Glyph List; Type 0 fonts through their CMaps, also every predefined one of Chinese, Japanese and Korean encodings (jflib-cidmap: Shift-JIS, EUC, GBK, Big Five, UHC, the Unicode ones), and without a ToUnicode through the CID → Unicode table of the font's collection (Adobe-GB1, -CNS1, -Japan1, -Korea1); Type 3 fonts; the 14 standard fonts with their widths; text in form XObjects. - Navigation: the document information, the XMP metadata, the language, the outline with explicit and named destinations, links and other annotations with their actions.
- Forms: every field of the interactive form with its full name, kind, value, options and widgets; for a signature field what the signature states (it is not verified).
- Attachments: embedded files with their name, MIME type, description, size and relationship (as ZUGFeRD and Factur-X invoices carry their XML), and their data.
A damaged or hostile file gives an error or less than it claims, never a panic, a hang or memory
without end: nesting, the depth of references, page trees, outlines and form XObjects are
bounded, every decoded stream is at most Options::max_stream bytes (256 MiB). Not supported:
verifying signatures.
What it draws#
Document::render draws a page into a gfx::Surface at any resolution, the whole page or a
region of it (tiles for a viewer), over paper of any colour or none:
- Paths: fills with the non-zero and even-odd rule, strokes with caps, joins, miter limit and dashes in user space (also under a matrix that scales unevenly), thin rules and frames on whole pixels as Poppler draws them, clipping paths and text clipping.
- Colours in every colour space: Device, CalGray, CalRGB, Lab, ICCBased through its profile
(grey, RGB, CMYK, Lab and up to 15 colours, by
jflib-img-core'sicc_cms; the rendering intent ofri,RIand an image's/Intent, black point compensation), Indexed, Separation and DeviceN through their tint transforms, and functions of all four types (sampled, exponential, stitching, PostScript calculator). Device colours take the resources'DefaultGray,DefaultRGBandDefaultCMYK, else the profile of the document's output intent (PDF/X, PDF/A); without one, CMYK as printing inks look (the Neugebauer model over the colours of the SWOP inks). Pages are sRGB. - Text through the glyph outlines of the embedded fonts -- Type 1, CFF (with seac accents),
TrueType, OpenType, CID-keyed fonts, Type 3 -- and for fonts that are not embedded substitutes
from a
FontSource(by default the system's fonts: URW's Nimbus, Liberation or the Windows fonts for the 14 standard fonts; for a Chinese, Japanese or Korean font one of its language,FontQuery::lang: Noto Sans CJK, Yu Gothic, Microsoft YaHei, Hiragino and the like, vertical punctuation in its vertical form); every text render mode, horizontal and vertical writing. - Images of every bit depth and colour space with Decode, stencil masks, colour-key and explicit masks, soft masks with Matte, inline images, JPEG (CMYK too) and CCITT Group 3 and 4; shrunk images averaged over the pixels they cover, enlarged ones sampled bilinearly.
- Shadings of all seven types, with
shand as patterns; tiling patterns, coloured and uncoloured. - Transparency: alpha, the sixteen blend modes, soft masks (luminosity and alpha, with backdrop and transfer function), transparency groups.
- Annotations through their appearance streams (with their states and flags), and optional
content (the default configuration, membership dictionaries). A form field without an
appearance, or one whose form asks for new ones (
NeedAppearances), is drawn from its value as Poppler does.
Pages agree with Poppler's pdftoppm (tools/pdf_render_check.py; colours of ICC profiles within
one step, tools/icc_pdf_check.py), and drawing takes about as long. JPEG 2000 images (JPXDecode) are decoded by
jflib-img-jp2: their own size and bit depth, the colour
space of the JP2 header when the dictionary names none (an ICC profile there is applied),
SMaskInData. JBIG2 images (JBIG2Decode, with their JBIG2Globals) are decoded
by jflib-img-jbig2. Not drawn: knockout groups and
groups that are not isolated (drawn as isolated ones), overprint, the vertical forms that only a
substitute's vert feature knows (the long vowel mark ー stands upright). The work of a page is
bounded: a hostile page gives Error::Limit, never a hang.
What it changes#
pdf::edit::Update takes a document the reader opened, changes it and saves it as an
incremental update: the bytes of the file stay as they are, the changed and new objects follow
with a cross-reference section of their own (a table or a stream, as the file has). The bytes a
signature covers stay as they are, so the signature still verifies over them; whether a
certification allows the change (DocMDP: /P 1 allows none, /P 2 filling in forms) is for the
verifier to judge. An encrypted file keeps its encryption (RC4, AES-128, AES-256), and a file the
reader had to repair gets a cross-reference of all its objects. Any object can be added, replaced
or deleted; filling in and flattening change all they would or, when they fail, nothing. For
forms:
- Filling in text fields, check boxes, radio buttons, combo and list boxes by their full
name, checked against the field (its options, MaxLen, MultiSelect, NoToggleToOff). Each widget
gets a new appearance stream as Acrobat and Poppler draw one: quadding, multiline with word
wrap, comb, password, automatic size, borders (solid, dashed, beveled, inset, underlined),
background, turned widgets, list boxes with the chosen options highlighted. The text is set in
the field's own font when it has every character; otherwise in fonts from a
FontSource(the system's by default: a sans-serif font for Latin, Greek and Cyrillic, one of the language for Chinese, Japanese, Korean, Arabic, Hebrew, Thai, the Indic scripts and others), embedded as subsets. A form withNeedAppearancesgets the appearances of all its fields and loses the flag (as Acrobat saves), an XFA form its XFA. JavaScript is not run. - Flattening draws the fields (all, or some by name) into their pages and takes them out of the form; signature fields stay.
Update::save_full writes the document in full instead: every object its trailer reaches, with
the update's changes, in a new file with one cross-reference section (object streams and a
cross-reference stream when the file had them). Unreachable objects and the older revisions are
gone. It keeps the encryption, removes it, or encrypts anew with AES-256 or AES-128 and new
passwords and permissions; changing the encryption of an encrypted file needs its owner password.
A file with signatures is written in full only when you allow them to break.
tools/pdf_form_check.py checks the filled and flattened files of its forms with qpdf (no errors, the values set), Poppler (the values it reads, pages drawn alike, forms Poppler filled read back), pdfsig (a signature still verifies over the bytes it signed after a field is filled) and Ghostscript (reads them). tools/pdf_sign_check.py checks the encrypted files of the writer and the files written in full with qpdf (no errors, the passwords, the permissions; qpdf encrypts the files we decrypt), Poppler (the passwords, the permissions, the same text), pdftoppm (drawn alike) and Ghostscript.
How it is used#
use jflib::pdf::{Dest, Document, FillRule, Hatch, Origin, Rgb, Shading, A4};
let mut doc = Document::new();
let page = doc.add_page(A4.0, A4.1); // points, 1/72 inch
let font = doc.add_font(font_bytes, 0)?; // a .ttf, .otf or a collection's face
{
let mut c = doc.canvas(page, Origin::TopLeft);
c.set_fill_color(Rgb::hex(0x2060C0));
c.rounded_rect(50.0, 50.0, 200.0, 80.0, 8.0);
c.fill(FillRule::NonZero);
c.rect(50.0, 200.0, 200.0, 40.0); // a gradient from left to right
c.fill_shading(FillRule::NonZero, &Shading::axial([50.0, 0.0], [250.0, 0.0],
&[(0.0, Rgb::hex(0x2060C0), 1.0), (1.0, Rgb::hex(0x2060C0), 0.0)]));
c.rect(50.0, 260.0, 200.0, 40.0); // hatched at 45 degrees
c.fill_hatch(FillRule::NonZero, &Hatch::new(0.785, 6.0, 1.0, Rgb::BLACK));
c.set_fill_color(Rgb::BLACK);
let w = c.text(font, 12.0, 50.0, 160.0, "Hallo, Welt");
c.link_uri(50.0, 148.0, w, 16.0, "https://jflib.org");
}
doc.add_outline(None, "Start", Dest::Fit(page));
let bytes = doc.write()?;
And reading one:
use jflib::pdf::read::{Action, Document, Options};
let doc = Document::open(bytes)?; // Error::Password when it needs one
let doc = Document::open_with(bytes, &Options { password: "geheim".into(), ..Options::default() })?;
for i in 0..doc.page_count() {
let (w, h) = doc.page(i)?.size(); // points, as the page is shown
let text = doc.text(i)?; // the text in reading order
}
for g in doc.page_text(0)?.items { // every glyph: text, x, y, size
if g.text == "€" { /* g.x, g.y */ }
}
let title = doc.info().title;
for o in doc.outlines() {
if let Some(Action::GoTo(dest)) = o.action { /* dest.page */ }
}
for f in doc.fields() { /* f.name, f.kind, f.value */ }
for a in doc.attachments() {
let xml = doc.decode(a.stream.as_ref().unwrap())?; // "factur-x.xml", "text/xml"
}
Filling in a form, and making one:
use jflib::pdf::edit::{FieldValue, Update};
use jflib::pdf::{read, FieldStyle, Origin, TextField, A4};
let doc = read::Document::open(bytes)?; // bytes: the form's file
let mut up = Update::new(&doc);
up.set_field("person.name", FieldValue::Text("Jakob"))?;
up.set_field("agree", FieldValue::Check(true))?;
up.set_field("size", FieldValue::Choice(&["M"]))?; // a radio button, combo or list box
up.flatten(None)?; // optional: the fields into the pages
let filled: Vec<u8> = up.save()?; // the file and the update after it
let mut doc_w = jflib::pdf::Document::new(); // a new form
let page = doc_w.add_page(A4.0, A4.1);
let mut c = doc_w.canvas(page, Origin::TopLeft);
c.text_field(50.0, 50.0, 200.0, 20.0, "person.name", &TextField { value: "Jakob", ..TextField::default() });
c.check_box(260.0, 50.0, 14.0, 14.0, "agree", false, &FieldStyle::default());
Encrypting a new document, and one that exists:
use jflib::pdf::edit::{Full, Security, Update};
use jflib::pdf::{read, Encryption, Permissions};
doc_w.set_encryption(Some(Encryption::aes256("user", "owner").permissions(Permissions::PRINT | Permissions::FILL_FORMS)));
let bytes = doc_w.write()?;
let doc = read::Document::open_with(old, &read::Options { password: "owner".into(), ..Default::default() })?;
let enc = Encryption::aes256("new", "new owner");
let again = Update::new(&doc).save_full(&Full { security: Security::Encrypt(&enc), ..Full::default() })?;
let clear = Update::new(&doc).save_full(&Full { security: Security::None, ..Full::default() })?;
And drawing one:
use jflib::pdf::read::{Document, RenderOptions};
let doc = Document::open(bytes)?;
let (w, h) = doc.page_pixels(0, 150.0)?; // the page's size at 150 dpi
let page: gfx::Surface = doc.render(0, &RenderOptions { dpi: 150.0, ..RenderOptions::default() })?;
let tile = doc.render(0, &RenderOptions { dpi: 300.0, region: Some([0, 0, 512, 512]), ..RenderOptions::default() })?;
How to get it#
Like all of JFLib, the crate comes through the one dependency
jflib, as jflib::pdf. All of JFLib's crates share one
version and are released together.
What's new in 0.2.2#
The crate is new: a vector PDF writer with embedded font subsets, images, gradients, hatches, links,
outlines and encryption, and a reader that opens documents, extracts text, draws pages with ICC
colour management and changes forms (edit::Update). Crafted files take bounded time and memory.
Everything is in the changelog.
Documentation#
- API reference: every public
item of
pdf, also on docs.rs - The plan (in German): decision V5 and milestone JD12
License#
MIT or Apache-2.0, at your choice. The reader carries the Adobe Glyph List (BSD 3-Clause License,
Copyright Adobe) and the advance widths of the Liberation fonts Sans and Serif (SIL Open Font
License 1.1); their texts are in the crate's
licenses/ folder.