To use the library, follow these steps:
- Initialize the library: Call
PDFiumLibrary.init() once for your application. This returns a library instance. - Load a document: Use
library.loadDocument(buffer) to load a PDF from a buffer. If the document is encrypted, pass the password as the second argument. - Access pages: Iterate over pages using
document.pages(). - Render a page: Call
page.render(options) on a page object. You must provide a render function in the options to handle the raw bitmap data returned by the library. - Cleanup: Always call
document.destroy() and library.destroy() when finished to free resources.
Note: The render function receives a PDFiumPageRenderOptions object containing data (raw bitmap), width, and height. You are responsible for converting this raw data into a usable format (like PNG) using a library like sharp or your own implementation.
import { PDFiumLibrary } from "@hyzyla/pdfium";
import { promises as fs } from 'fs';
import sharp from 'sharp';
// Example render function using sharp to convert raw bitmap to PNG
async function renderFunction(options: PDFiumPageRenderOptions) {
return await sharp(options.data, {
raw: {
width: options.width,
height: options.height,
channels: 4,
},
})
.png()
.toBuffer();
}
async function main() {
const buff = await fs.readFile('test2.pdf');
// 1. Initialize
const library = await PDFiumLibrary.init();
// 2. Load
const document = await library.loadDocument(buff);
// 3. Iterate and Render
for (const page of document.pages()) {
const image = await page.render({
scale: 3, // 3x scale
render: renderFunction,
});
// image.data contains the result from your render function
await fs.writeFile(`output/${page.number}.png`, Buffer.from(image.data));
}
// 4. Cleanup
document.destroy();
library.destroy();
}
main();