Quickstart
Render PDF pages from a file path or a buffer, pick pages and choose an output format.
Everything in pdf-raster goes through convert(input, options?). This page
covers the options you will use first.
Render every page
import { writeFile } from "node:fs/promises";
import { convert } from "pdf-raster";
const pages = await convert("./report.pdf");
for (const page of pages) {
await writeFile(`page-${page.pageIndex + 1}.png`, page.data);
}Without options, pdf-raster renders every page at 300 DPI and encodes each one as PNG.
Read the result
convert() resolves to an array with one ConvertedPage per rendered page:
const [page] = await convert("./report.pdf");
console.log(page);
// {
// pageIndex: 0,
// data: <Buffer 89 50 4e 47 ...>,
// mimeType: "image/png",
// width: 2550,
// height: 3300,
// dpi: 300,
// }data holds the encoded image. You can write it to disk, return it from an
HTTP handler or pass it to another library as is.
Render selected pages
pages takes zero-based indices. The result follows the order you list them
in:
const pages = await convert("./report.pdf", {
pages: [0, 2], // the first and third pages
});An index past the last page throws INVALID_PAGE_INDEX.
Choose an output format
const pages = await convert("./report.pdf", {
outputFormat: "webp",
});
console.log(pages[0].mimeType); // "image/webp"| Format | Compression | When to use it |
|---|---|---|
png (default) | Lossless, fast | The fastest encode. Files are the largest. |
webp | Lossless | About a third of the PNG size on text pages. |
jpeg | Lossy, quality 75 | The smallest files for pages with photos or scans. |
The benchmark lists measured sizes for each format.
Pass bytes instead of a path
If the PDF is already in memory, pass a Buffer, Uint8Array or
ArrayBuffer. pdf-raster does not write a temporary file.
const response = await fetch("https://example.com/invoice.pdf");
const pages = await convert(await response.arrayBuffer(), { dpi: 150 });Other options
const pages = await convert("./statement.pdf", {
dpi: 200,
password: "s3cret", // for encrypted PDFs
crop: { x: 0, y: 0, width: 1700, height: 600 }, // in rendered pixels
renderAnnotations: false, // skip comments and form field values
maxPixels: 50_000_000, // reject pages larger than this
});The API reference describes each option and its default.