Load font files from disk and embed them into a PDF so it renders correctly on any system.
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(())
}PDFluent accepts TrueType (.ttf), OpenType (.otf), and TrueType Collection (.ttc) files. Pass the path to Font::from_file.
use pdfluent::Font;
let font = Font::from_file("fonts/NotoSans-Regular.ttf")?;embed_font adds the font program to the PDF as a stream object and registers it in the document font resources.
doc.embed_font(&font)?;After embedding, use the font handle when adding text to a page. The font name in the content stream references the embedded resource.
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()),
)?;To re-embed a font that a page already references by name but is not embedded, look it up by its PDF resource name.
let font_data = std::fs::read("fonts/Arial.ttf")?;
doc.embed_font_data("Arial", &font_data)?;List fonts after the operation to confirm each font shows is_embedded = true.
for font in doc.fonts() {
assert!(font.is_embedded(), "Font {} not embedded", font.name());
}
doc.save("with_embedded_font.pdf")?;No JVM, no runtime, no DLL dependencies. Ships as a single native binary or WASM module.
Rust's ownership model prevents buffer overflows and use-after-free. No segfaults in PDF parsing.
Same code runs server-side, in Docker, on AWS Lambda, on Cloudflare Workers, or in the browser via WASM.