1.1.0

Conversion

Last updated


This page explains how convert() renders PDF pages into images, and what actually happens with resolution, output format, and failures.

Flow


  1. Sets pdfjsLib.GlobalWorkerOptions.workerSrc to pdf.worker.js on cdnjs
  2. Parses file with getDocument(), fetching CMaps from cdnjs (for CJK and other font encodings)
  3. Appends the progress overlay to <body> once parsing succeeds
  4. Creates a canvas for every page and renders them concurrently; each finished page pushes its Data URL into the result array and updates progress
  5. Waits 500ms after the last page, resolves with the result array, and removes the overlay

Resolution: scale


Output pixel size = PDF page size (pt) × scale. The default is 1.5; a US Letter page (612×792 pt) renders at 612×792 with scale: 1 and at 918×1188 with the default.
  1. <script>
  2. const sample = async () => (await fetch("/assets/sample.pdf")).arrayBuffer();
  3. const size = src => new Promise(r => {
  4. const img = new Image();
  5. img.onload = () => r(img.width + "x" + img.height);
  6. img.src = src;
  7. });
  8. addEventListener("load", async () => {
  9. for (const scale of [0.5, 1, 1.5]) {
  10. const [first] = await new pdf2image({ file: await sample(), type: "png", scale }).convert();
  11. console.log("scale", scale, "->", await size(first));
  12. }
  13. });
  14. </script>
Live preview · @pardnchiu/pdf2image@1.1.2

Output Format: type


type accepts only png, jpg, and webp; any other value falls back to jpg. Results come from canvas.toDataURL("image/" + type), so:
typePassed to toDataURLActual output
pngimage/pngPNG
webpimage/webpWebP (PNG where the browser lacks WebP encoding)
jpg (default)image/jpgPNG: browsers only recognize image/jpeg and fall back to PNG for unknown MIME types

So with the default type, every Data URL starts with data:image/png.
  1. <script>
  2. addEventListener("load", async () => {
  3. for (const type of ["png", "jpg", "webp", "gif"]) {
  4. const buffer = await (await fetch("/assets/sample.pdf")).arrayBuffer();
  5. const [first] = await new pdf2image({ file: buffer, type, scale: 0.5 }).convert();
  6. console.log(type.padEnd(4), "->", first.slice(0, first.indexOf(";")));
  7. }
  8. });
  9. </script>
Live preview · @pardnchiu/pdf2image@1.1.2

Result Order


Pages render concurrently, and each result is pushed onto the array when its page finishes rather than written at its page index. When page complexity varies a lot, images[0] is not guaranteed to be page 1.

file Is Single-Use


pdf.js transfers the ArrayBuffer to its worker, so after conversion the original buffer's byteLength becomes 0. As a result:
  • A second convert() on the same instance rejects with a TypeError whose message is "Cannot perform Construct on a detached ArrayBuffer"; the already converted images stay intact
  • The same buffer cannot be handed to another instance; read the file again to reconvert

  1. <script>
  2. addEventListener("load", async () => {
  3. const buffer = await (await fetch("/assets/sample.pdf")).arrayBuffer();
  4. const converter = new pdf2image({ file: buffer, type: "png", scale: 0.5 });
  5. console.log("first:", (await converter.convert()).length, "pages");
  6. console.log("buffer byteLength:", buffer.byteLength);
  7. try {
  8. await converter.convert();
  9. } catch (err) {
  10. console.log("second:", String(err));
  11. }
  12. console.log("images kept:", converter.images.length);
  13. });
  14. </script>
Live preview · @pardnchiu/pdf2image@1.1.2

Failure Behavior


CaseRejection value
No file providedString "error The PDF file is empty, i.e. its size is zero bytes."
Not a valid PDFString "error Invalid PDF structure."
A page fails to renderString "error i is not defined": the error handler references a variable that does not exist, so the original message is lost
Reusing a transferred bufferA TypeError object
pdf.js not loaded yetA ReferenceError object (see Core Concepts)

Rejection values mix strings and Error objects; String(err) handles both. For pdf.js load failures the library also calls console.error("error", err) itself.
  1. <script>
  2. addEventListener("load", async () => {
  3. const cases = { "no file": {}, "not a pdf": { file: new TextEncoder().encode("hello").buffer } };
  4. for (const [name, options] of Object.entries(cases)) {
  5. try {
  6. await new pdf2image(options).convert();
  7. } catch (err) {
  8. console.log(name, "->", typeof err, String(err));
  9. }
  10. }
  11. });
  12. </script>
Live preview · @pardnchiu/pdf2image@1.1.2


中文