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::prelude::*;

fn main() -> Result<()> {
    let doc = PdfDocument::open("document.pdf")?;

    let report = doc.to_images(
        "page_{page}.png",
        ToImagesOptions::new()
            .with_dpi(150)
            .with_format(ImageFormat::Png),
    )?;

    println!("rendered {} pages", report.paths.len());
    Ok(())
}
Install:cargo add pdfluent@1.0.0-beta.5Download SDK →

Step by step

1

Open the PDF

Open the document. Rendering is a document-level operation in PDFluent: you choose the output pattern and a page range.

rust
use pdfluent::prelude::*;

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

Build ToImagesOptions

ToImagesOptions::new() defaults to 150 DPI and PNG output. Override DPI and format to taste. For sharp screen previews 150 DPI is fine; print-quality output is 300 DPI.

rust
let opts = ToImagesOptions::new()
    .with_dpi(150)
    .with_format(ImageFormat::Png);
3

Render a specific page range

Use .with_pages(from, to) with 1-based inclusive bounds. Omit to render every page.

rust
let opts = ToImagesOptions::new()
    .with_dpi(150)
    .with_pages(1, 3); // pages 1, 2, 3
4

Write the output files

Pass a filename pattern. The {page} placeholder is substituted with the 1-based page number. If the pattern has no {page}, PDFluent inserts _N before the extension.

rust
let report = doc.to_images("page_{page}.png", opts)?;
for path in &report.paths {
    println!("wrote {}", path.display());
}
5

Render to JPEG

Change the format via .with_format(ImageFormat::Jpeg). JPEG does not carry transparency, so RGBA pixels are flattened to RGB before encoding.

rust
use pdfluent::prelude::*;

let doc = PdfDocument::open("document.pdf")?;

doc.to_images(
    "thumb_{page}.jpg",
    ToImagesOptions::new()
        .with_dpi(72)
        .with_format(ImageFormat::Jpeg),
)?;

Notes and tips

  • to_images is native-only. On wasm32 targets it returns Error::UnsupportedOnWasm. See WASM_SUPPORT.md §2.5.
  • Rendering is CPU-bound. Page-level parallelism isn't exposed via to_images in 1.0; for large documents, split via extract_pages and run to_images on each slice in parallel.
  • Very high DPI values (above 600) produce large image files. 150 DPI is a good default for web previews.
  • The 1.0 renderer outputs RGBA8 pixels. CMYK-preserving export lands with the renderer changes in a later release.

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