Skip to content

Commit

Permalink
add CLI
Browse files Browse the repository at this point in the history
  • Loading branch information
k-yle committed Oct 17, 2023
1 parent ab0f7cd commit 73d7b57
Show file tree
Hide file tree
Showing 3 changed files with 75 additions and 1 deletion.
16 changes: 15 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@

Useful for unit tests of PDFs

Supports nodejs v16 to v20.
Supports nodejs v16 to v20, and comes with a CLI.

## Install

Expand Down Expand Up @@ -76,3 +76,17 @@ const doc = await pdf("example.pdf", {
scale: 2.0, // use this for PDFs with high resolution images if the generated image is low quality
});
```

## CLI

```sh
npm i -g pdf-to-img@latest

# example:
pdf2img inputFile.pdf

# options:
# -s / --scale: set the scale (defaults to 3)
# -p / --password: the password to unlock the PDF
# -o / --output: the output folder, relative to the current working directory.
```
57 changes: 57 additions & 0 deletions bin/cli.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
#!/usr/bin/env node

// @ts-check
/* eslint-disable import/extensions */
import { promises as fs } from "node:fs";
import { parseArgs } from "node:util";
import { join } from "node:path";
import { pdf } from "../dist/index.js";

const { values, positionals } = parseArgs({
options: {
scale: { short: "s", type: "string", default: "3" },
password: { short: "p", type: "string" },
output: { short: "o", type: "string" },
},
allowPositionals: true,
});

const [inputFile] = positionals;

if (!inputFile) {
throw new Error(
"Please specify an input file, for example, `pdf2img -s 3 example.pdf`"
);
}

/** the name of the file, without the file extension */
const inputFileBaseName = /** @type {string} */ (
inputFile.split("/").at(-1)
).replace(/\.pdf$/, "");

const fullInputFilePath = join(process.cwd(), inputFile);
const outputFolder = join(process.cwd(), values.output || "");

async function main() {
let pageNumber = 1;

const document = await pdf(fullInputFilePath, {
scale: +(values.scale || 3),
password: values.password,
});

if (values.output) {
// if the user specified a custom output folder,
// create it if it does't already exist.
await fs.mkdir(outputFolder, { recursive: true });
}

for await (const image of document) {
const outputImageName = `${inputFileBaseName}-${pageNumber}.png`;
console.log(outputImageName);
await fs.writeFile(join(outputFolder, outputImageName), image);
pageNumber++;
}
}

main();
3 changes: 3 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,9 @@
"test": "jest",
"trypublish": "npm publish || true"
},
"bin": {
"pdf2img": "./bin/cli.mjs"
},
"engines": {
"node": ">=16"
},
Expand Down

0 comments on commit 73d7b57

Please sign in to comment.