Getting Started
This page covers installing pdf2image and running your first PDF-to-image conversion in the browser.
Prerequisites
| Item | Requirement |
|---|---|
| Runtime | A modern browser with ES2022 private fields (#field), canvas, and Promise |
| Network | Access to cdnjs.cloudflare.com (pdf.js 3.4.120, JSZip 3.7.1) and cdn.jsdelivr.net (stylesheet) |
| Input | The PDF as an ArrayBuffer, usually from File.arrayBuffer() |
pdf2image runs in the browser only; Node.js has no document or window and cannot run it directly.
Installation
npm
npm i @pardnchiu/pdf2image
CDN (UMD)
<script src="https://cdn.jsdelivr.net/npm/@pardnchiu/pdf2image@1.1.2/dist/pdf2image.js"></script>
The UMD build registers the global window.pdf2image on load.
CDN (ES Module)
import { pdf2image } from "https://cdn.jsdelivr.net/npm/@pardnchiu/pdf2image@1.1.2/dist/pdf2image.esm.js";
The ESM build is the same code as the UMD build, with one extra line that exports window.pdf2image.
First Conversion
The example below converts /assets/sample.pdf (3 pages) on load; you can also pick your own PDF with the file input.
<input type="file" accept="application/pdf" id="pick">
<div id="pages"></div>
<script>
async function run(buffer) {
const converter = new pdf2image({ file: buffer, type: "png", scale: 0.5 });
try {
const images = await converter.convert();
document.getElementById("pages").replaceChildren(
...images.map(src => Object.assign(document.createElement("img"), { src, width: 120 }))
);
console.log("pages:", images.length);
} catch (err) {
console.log("failed:", String(err));
}
}
document.getElementById("pick").addEventListener("change", async e => {
const file = e.target.files[0];
if (file) run(await file.arrayBuffer());
});
addEventListener("load", async () => {
run(await (await fetch("/assets/sample.pdf")).arrayBuffer());
});
</script>
Three things to note:
filemust be anArrayBuffer, not aFileobject- Call
convert()after theloadevent, because pdf.js is injected asynchronously when the package loads (see Core Concepts) - The rejection value can be a string or an
Error;String(err)prints both (see Conversion)
Next Steps
- Conversion:
scale, output formats, and error behavior - ZIP Download: bundling and filename templates
- Constructor Options: every option and its default