Skip to content

Render PDF to Image

using document = await pdfium.openDocument(buff);
// ... do something with the document
// Automatically disposed when scope exits

Get a page from the document by index (starting from 0):

using page = document.getPage(0);

Or iterate over all pages:

for (const page of document.pages()) {
using p = page;
// ... do something with the page
}

Then render the page by calling the render method. It accepts an optional RenderOptions object:

  • scale - scale factor for the image (default: 1, which means 72 DPI; 3 is almost always enough for good quality)
  • width / height - target dimensions in pixels (overrides scale, does not preserve aspect ratio)
  • renderFormFields - whether to render interactive form fields (default: false)
  • backgroundColour - ARGB background colour integer (default: 0xFFFFFFFF — white)
  • rotation - rotation to apply during rendering
const { data, width, height } = page.render({ scale: 3 });
// data is a Uint8Array of RGBA pixels (4 bytes per pixel)

To render with form fields visible:

const result = page.render({ scale: 3, renderFormFields: true });

The render result contains:

  • data - RGBA pixel data as a Uint8Array
  • width - rendered width in pixels
  • height - rendered height in pixels
  • originalWidth - original page width in points (before scaling)
  • originalHeight - original page height in points (before scaling)

To convert the raw RGBA pixels to a PNG image, use the sharp library:

Terminal window
pnpm add sharp
import sharp from 'sharp';
const { data, width, height } = page.render({ scale: 3 });
const png = await sharp(data, {
raw: { width, height, channels: 4 },
}).png().toBuffer();

You can use width and height options instead of scale to specify exact pixel dimensions. The aspect ratio will not be preserved — the image will be stretched to the specified size.

const result = page.render({ width: 800, height: 600 });
import { PDFium } from '@scaryterry/pdfium';
import { promises as fs } from 'fs';
import sharp from 'sharp';
async function main() {
const buff = await fs.readFile('document.pdf');
// Initialise the library
using pdfium = await PDFium.init();
// Open the document
using document = await pdfium.openDocument(buff);
// Render each page to PNG
for (const page of document.pages()) {
using p = page;
console.log(`Page ${p.index} - rendering...`);
const { data, width, height } = p.render({ scale: 3 });
const png = await sharp(data, {
raw: { width, height, channels: 4 },
}).png().toBuffer();
await fs.writeFile(`output/${p.index}.png`, png);
}
}
main();