Add an Image to a PDF file using Node.JS (script)
Tags: node
Published: 2020-05-24 13:54:34

I needed to add a cover for the PDF book. And I did not want to install a huge Acrobat or buy PDF editors for such a simple task. Therefore, I wrote a simple Node.JS script to add an image to the beginning of a PDF file.

To do this, we need the following packages and modules:

```js
const fs = require('fs');
const path = require('path');
const assert = require('assert');
const { PDFDocument } = require('pdf-lib');
```

Prepare PDF and Image instance with `PDFDocument`.

```js
const run = async ({ pathToPDF, pathToImage }) => {
  const pdfDoc = await PDFDocument.load(fs.readFileSync(pathToPDF));
  const img = await pdfDoc.embedPng(fs.readFileSync(pathToImage));
  // ...
```

Append a new page to the file and insert an image in full width and height.

```js
  // ...
  const imagePage = pdfDoc.insertPage(0);
  imagePage.drawImage(img, {
    x: 0,
    y: 0,
    width: imagePage.getWidth(),
    height: imagePage.getHeight()
  });
  // ...
```

Save result in a new PDF file in the current directory.

```js
  // ...
  const pdfBytes = await pdfDoc.save();
  const newFilePath = `${path.basename(pathToPDF, '.pdf')}-result.pdf`;
  fs.writeFileSync(newFilePath, pdfBytes);
}
```

And the code for running the main function and check that all required arguments are passed.

```js 
const ERRORS = {
  ARGUMENTS: 'Please provide a path to the PDF file as a first argument and path to an image as the second argument'
};

const pathToPDF = process.argv[2];
assert.notEqual(pathToPDF, null, ERRORS.ARGUMENTS);
const pathToImage = process.argv[3];
assert.notEqual(pathToImage, null, ERRORS.ARGUMENTS);

run({ pathToPDF, pathToImage }).catch(console.error);
```

Altogether:

```js
const fs = require('fs');
const path = require('path');
const assert = require('assert');
const { PDFDocument } = require('pdf-lib');

const run = async ({ pathToPDF, pathToImage }) => {
  const pdfDoc = await PDFDocument.load(fs.readFileSync(pathToPDF));
  const img = await pdfDoc.embedPng(fs.readFileSync(pathToImage));
  const imagePage = pdfDoc.insertPage(0);

  imagePage.drawImage(img, {
    x: 0,
    y: 0,
    width: imagePage.getWidth(),
    height: imagePage.getHeight()
  });

  const pdfBytes = await pdfDoc.save();
  const newFilePath = `${path.basename(pathToPDF, '.pdf')}-result.pdf`;
  fs.writeFileSync(newFilePath, pdfBytes);
}

const ERRORS = {
  ARGUMENTS: 'Please provide a path to the PDF file as a first argument and path to an image as the second argument'
};

const pathToPDF = process.argv[2];
assert.notEqual(pathToPDF, null, ERRORS.ARGUMENTS);
const pathToImage = process.argv[3];
assert.notEqual(pathToImage, null, ERRORS.ARGUMENTS);

run({ pathToPDF, pathToImage }).catch(console.error);
```

Usage:

    $ npm start ../checklist.pdf ~/Downloads/cover.png

If you need to append an image to a PDF file quickly get [this script](https://github.com/iamdidev/pdf-append-image) run `npm i` and `npm path/to/file.pdf path/to/image.png`.

---

Check out [my twitter profile](https://twitter.com/iamdidev) where every day I share helpful stuff about soft-skills and how to write clean code with good design.