Embed fonts fully into a PDF in Rust

Load font files from disk and embed them into a PDF so it renders correctly on any system.

rust
use pdfluent::{Document, Font};

fn main() -> pdfluent::Result<()> {
    let mut doc = Document::open("input.pdf")?;

    // Load a font from disk and embed it
    let font = Font::from_file("fonts/NotoSans-Regular.ttf")?;
    doc.embed_font(&font)?;

    doc.save("with_embedded_font.pdf")?;
    Ok(())
}
Install:cargo add pdfluentDownload SDK →

Step by step

1

Load a font from a file

PDFluent accepts TrueType (.ttf), OpenType (.otf), and TrueType Collection (.ttc) files. Pass the path to Font::from_file.

rust
use pdfluent::Font;

let font = Font::from_file("fonts/NotoSans-Regular.ttf")?;
2

Embed the font into the document

embed_font adds the font program to the PDF as a stream object and registers it in the document font resources.

rust
doc.embed_font(&font)?;
3

Use the font when drawing text

After embedding, use the font handle when adding text to a page. The font name in the content stream references the embedded resource.

rust
use pdfluent::content::{TextBuilder, Color};

let mut page = doc.add_page(pdfluent::PageSize::A4);
page.draw_text(
    TextBuilder::new("Hello, world!")
        .font(&font)
        .size(14.0)
        .position(72.0, 700.0)
        .color(Color::black()),
)?;
4

Embed a font into an existing page resource dictionary

To re-embed a font that a page already references by name but is not embedded, look it up by its PDF resource name.

rust
let font_data = std::fs::read("fonts/Arial.ttf")?;
doc.embed_font_data("Arial", &font_data)?;
5

Verify embedding succeeded

List fonts after the operation to confirm each font shows is_embedded = true.

rust
for font in doc.fonts() {
    assert!(font.is_embedded(), "Font {} not embedded", font.name());
}
doc.save("with_embedded_font.pdf")?;

Notes and tips

  • Embedded fonts make the PDF larger but guarantee consistent rendering on all platforms.
  • For web delivery, consider subsetting after embedding to keep file size down.
  • Standard 14 PDF fonts (Helvetica, Times, Courier, etc.) are not embedded by convention; viewers are required to supply them.
  • Font licensing applies to embedding. Fonts with the fsType embedding restriction bits set to 2 (no embedding) cannot legally be embedded.

Why PDFluent for this

Pure Rust

No JVM, no runtime, no DLL dependencies. Ships as a single native binary or WASM module.

Memory safe

Rust's ownership model prevents buffer overflows and use-after-free. No segfaults in PDF parsing.

Runs anywhere

Same code runs server-side, in Docker, on AWS Lambda, on Cloudflare Workers, or in the browser via WASM.

Frequently asked questions