How-to guides/Rendering

Render a PDF page to PNG in Rust

Rasterise any PDF page to a PNG image at a chosen DPI. Works headless with no display server required.

rust
use pdfluent::{PdfDocument, RenderOptions};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let doc = PdfDocument::open("document.pdf")?;
    let page = doc.page(0)?;

    let opts = RenderOptions::default().dpi(150);
    let image = page.render(&opts)?;
    image.save_png("page_1.png")?;

    println!("{}x{} pixels", image.width, image.height);
    Ok(())
}
Install:cargo add pdfluentDownload SDK →

Step by step

1

Open the PDF and select a page

Open the document and get the page you want to render. Pages are 0-indexed.

rust
use pdfluent::PdfDocument;

let doc = PdfDocument::open("slides.pdf")?;
let page = doc.page(0)?;
2

Set the render resolution

RenderOptions::default() uses 72 DPI. For sharp screen previews, use 150 DPI. For print-quality output, use 300 DPI.

rust
use pdfluent::RenderOptions;

let opts = RenderOptions::default()
    .dpi(150)
    .background_color([255, 255, 255, 255]); // white, opaque
3

Render the page

Call page.render() with the options. The returned RenderedPage holds the raw RGBA pixel data and the pixel dimensions.

rust
let image = page.render(&opts)?;
println!("Rendered: {}x{} px", image.width, image.height);
4

Save as PNG

Call save_png() with an output path. PNG encoding is built in; no external image library is required.

rust
image.save_png("output.png")?;
5

Access raw pixel data

For further processing with the image crate or another renderer, access the raw RGBA bytes directly.

rust
let rgba: &[u8] = image.as_rgba_bytes();
// Width * height * 4 bytes
assert_eq!(rgba.len(), image.width as usize * image.height as usize * 4);

Notes and tips

  • Rendering is CPU-bound and single-threaded per page. Use a thread pool to render multiple pages in parallel.
  • Transparent backgrounds require a PDF with no page background. Set background_color with alpha=0 to get a transparent PNG.
  • Very high DPI values (above 600) produce large image files. 150 DPI is sufficient for most web preview use cases.

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