Embed JPEG, PNG, or WebP images at a specific position and size on any PDF page.
use pdfluent::{PdfDocument, Image, ImagePosition};
fn main() -> pdfluent::Result<()> {
let mut doc = PdfDocument::open("document.pdf")?;
let image = Image::from_file("logo.png")?;
let mut page = doc.page_mut(0)?;
page.add_image(
&image,
ImagePosition {
x: 50.0, // points from left
y: 700.0, // points from bottom
width: 150.0,
height: 60.0,
},
)?;
doc.save("document-with-logo.pdf")?;
Ok(())
}Image embedding is in the base crate. The image feature adds format conversion helpers.
# Cargo.toml
[dependencies]
pdfluent = { version = "0.9", features = ["image"] }Image::from_file() reads JPEG, PNG, or WebP. Image::from_bytes() accepts the raw image bytes if you are reading from memory or a network source.
use pdfluent::Image;
// From a file path
let image = Image::from_file("logo.png")?;
// From raw bytes (e.g. from an HTTP response)
let bytes: Vec<u8> = std::fs::read("logo.png")?;
let image = Image::from_bytes(&bytes)?;
println!("{}x{} image loaded", image.width(), image.height());page_mut(n) returns a mutable handle to page n. PDF page indices are zero-based.
let mut page = doc.page_mut(0)?; // First page
// Or add to the last page
let last_idx = doc.page_count() - 1;
let mut page = doc.page_mut(last_idx)?;PDF uses a coordinate system where (0, 0) is the bottom-left corner. Measurements are in points (1 pt = 1/72 inch). A4 is 595 x 842 pt, US Letter is 612 x 792 pt.
use pdfluent::ImagePosition;
page.add_image(
&image,
ImagePosition {
x: 50.0, // 50 pt from left edge
y: 700.0, // 700 pt from bottom edge
width: 150.0,
height: 60.0,
},
)?;Use ImagePosition::fit_width() to scale the image to a given width while preserving the aspect ratio.
let pos = ImagePosition::fit_width(
&image,
50.0, // x
700.0, // y (top of image)
150.0, // target width in points
);
page.add_image(&image, pos)?;
doc.save("document-with-logo.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.