foliojs / pdfkit

A JavaScript PDF generation library for Node and the browser
http://pdfkit.org/
MIT License
9.93k stars 1.16k forks source link

cannot add image to pdf : unknown image format. #1543

Closed 78raoul78 closed 4 months ago

78raoul78 commented 4 months ago

I get the following error when I try to add a local image to my pdf document :

➜  sandbox npx ts-node ./src/main.ts
/Users/user/payfit/sandbox/node_modules/pdfkit/lib/image.js:34
      throw new Error('Unknown image format.');
            ^
Error: Unknown image format.
    at Function.open (/Users/user/payfit/sandbox/node_modules/pdfkit/lib/image.js:34:13)
    at PDFDocument.openImage (/Users/user/payfit/sandbox/node_modules/pdfkit/lib/mixins/images.js:226:24)
    at PDFDocument.image (/Users/user/payfit/sandbox/node_modules/pdfkit/lib/mixins/images.js:32:22)
    at convertImageToPdf (/Users/user/payfit/sandbox/src/main.ts:23:7)
    at main (/Users/user/payfit/sandbox/src/main.ts:29:26)
    at Object.<anonymous> (/Users/user/payfit/sandbox/src/main.ts:32:1)
    at Module._compile (node:internal/modules/cjs/loader:1198:14)
    at Module.m._compile (/Users/user/payfit/sandbox/node_modules/ts-node/src/index.ts:1618:23)
    at Module._extensions..js (node:internal/modules/cjs/loader:1252:10)
    at Object.require.extensions.<computed> [as .ts] (/Users/user/payfit/sandbox/node_modules/ts-node/src/index.ts:1621:12)

This is my code :

import { createWriteStream } from "fs";
import PDFDocument from "pdfkit";

export const convertImageToPdf = (fileName: string) => {
  const convertedFileName = fileName.endsWith(".pdf")
    ? fileName
    : `${fileName}.pdf`;

  const doc = new PDFDocument({ size: "A4" });
  const { width, height } = doc.page;

  const stream = doc.pipe(createWriteStream(convertedFileName));

  doc.image(fileName, 0, 0, { fit: [width, height] });
  doc.end();
  return new Promise((resolve) => stream.on("finish", resolve));
};

async function main() {
  await convertImageToPdf("IMG_1473.jpg");
}

main();

This is the picture I'm using

liborm85 commented 4 months ago

HEIC format is not supported. Use JPEG or PNG.