Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

pdf-to-png-converter

Package Overview
Dependencies
Maintainers
0
Versions
33
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

pdf-to-png-converter - npm Package Compare versions

Comparing version 3.6.1 to 3.6.3

8

out/comparePNG.d.ts
import { ComparePngOptions } from 'png-visual-compare';
/**
* Compares a PNG image with an expected PNG image.
* If the expected image does not exist, it creates it by copying the actual image.
* @param actualFile - The path or buffer of the actual PNG image.
* @param expectedFile - The path of the expected PNG image.
* @param opts - Optional compare options.
* @returns A promise that resolves to the comparison result.
*/
export declare function comparePNG({ actualFile, expectedFile, createExpectedFileIfMissing, opts, }: {

@@ -3,0 +11,0 @@ actualFile: string | Buffer;

34

out/comparePNG.js

@@ -1,12 +0,26 @@

import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
import { parse } from 'node:path';
import comparePng from 'png-visual-compare';
export function comparePNG({ actualFile, expectedFile, createExpectedFileIfMissing, opts, }) {
if (createExpectedFileIfMissing && !existsSync(expectedFile)) {
const expectedFileDir = parse(expectedFile).dir;
mkdirSync(expectedFileDir, { recursive: true });
const actualBuffer = typeof actualFile === 'string' ? readFileSync(actualFile) : actualFile;
writeFileSync(expectedFile, actualBuffer);
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.comparePNG = comparePNG;
const node_fs_1 = require("node:fs");
const node_path_1 = require("node:path");
const png_visual_compare_1 = __importDefault(require("png-visual-compare"));
/**
* Compares a PNG image with an expected PNG image.
* If the expected image does not exist, it creates it by copying the actual image.
* @param actualFile - The path or buffer of the actual PNG image.
* @param expectedFile - The path of the expected PNG image.
* @param opts - Optional compare options.
* @returns A promise that resolves to the comparison result.
*/
function comparePNG({ actualFile, expectedFile, createExpectedFileIfMissing, opts, }) {
if (createExpectedFileIfMissing && !(0, node_fs_1.existsSync)(expectedFile)) {
const expectedFileDir = (0, node_path_1.parse)(expectedFile).dir;
(0, node_fs_1.mkdirSync)(expectedFileDir, { recursive: true });
const actualBuffer = typeof actualFile === 'string' ? (0, node_fs_1.readFileSync)(actualFile) : actualFile;
(0, node_fs_1.writeFileSync)(expectedFile, actualBuffer);
}
return comparePng(actualFile, expectedFile, opts);
return (0, png_visual_compare_1.default)(actualFile, expectedFile, opts);
}

@@ -1,3 +0,6 @@

import { normalizePath } from './normalizePath';
export const PDF_TO_PNG_OPTIONS_DEFAULTS = {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.STANDARD_CMAPS = exports.STANDARD_FONTS = exports.DOCUMENT_INIT_PARAMS_DEFAULTS = exports.PDF_TO_PNG_OPTIONS_DEFAULTS = void 0;
const normalizePath_1 = require("./normalizePath");
exports.PDF_TO_PNG_OPTIONS_DEFAULTS = {
viewportScale: 1,

@@ -11,8 +14,8 @@ disableFontFace: true,

};
export const DOCUMENT_INIT_PARAMS_DEFAULTS = {
cMapUrl: normalizePath('./node_modules/pdfjs-dist/cmaps/'),
exports.DOCUMENT_INIT_PARAMS_DEFAULTS = {
cMapUrl: (0, normalizePath_1.normalizePath)('./node_modules/pdfjs-dist/cmaps/'),
cMapPacked: true,
standardFontDataUrl: normalizePath('./node_modules/pdfjs-dist/standard_fonts/'),
standardFontDataUrl: (0, normalizePath_1.normalizePath)('./node_modules/pdfjs-dist/standard_fonts/'),
};
export const STANDARD_FONTS = [
exports.STANDARD_FONTS = [
'FoxitDingbats.pfb',

@@ -35,3 +38,3 @@ 'FoxitFixed.pfb',

];
export const STANDARD_CMAPS = [
exports.STANDARD_CMAPS = [
'78-EUC-H.bcmap',

@@ -38,0 +41,0 @@ '78-EUC-V.bcmap',

@@ -1,2 +0,20 @@

export { pdfToPng } from './pdfToPng';
export * from './types';
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.pdfToPng = void 0;
var pdfToPng_1 = require("./pdfToPng");
Object.defineProperty(exports, "pdfToPng", { enumerable: true, get: function () { return pdfToPng_1.pdfToPng; } });
__exportStar(require("./types"), exports);

@@ -0,1 +1,8 @@

/**
* Normalizes a given path by ensuring it ends with the appropriate path separator.
*
* @param path - The path to be normalized.
* @returns The normalized path.
* @throws Error if the path is empty.
*/
export declare function normalizePath(path: string): string;

@@ -1,7 +0,17 @@

import { normalize, resolve } from 'node:path';
export function normalizePath(path) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.normalizePath = normalizePath;
const node_path_1 = require("node:path");
/**
* Normalizes a given path by ensuring it ends with the appropriate path separator.
*
* @param path - The path to be normalized.
* @returns The normalized path.
* @throws Error if the path is empty.
*/
function normalizePath(path) {
if (path === '') {
throw new Error('Path cannot be empty');
}
const resolvedPath = (normalize(resolve(path)));
const resolvedPath = ((0, node_path_1.normalize)((0, node_path_1.resolve)(path)));
if (process.platform === 'win32') {

@@ -8,0 +18,0 @@ if (resolvedPath.endsWith('\\')) {

import { PdfToPngOptions, PngPageOutput } from './types';
/**
* Converts a PDF file to PNG images.
*
* @param pdfFile - The path to the PDF file or a buffer containing the PDF data.
* @param props - Optional properties to customize the conversion process.
* @returns A promise that resolves to an array of PNG page outputs.
*
* @throws Will throw an error if invalid pages are requested when `strictPagesToProcess` is true.
*
* @example
* ```typescript
* const pngPages = await pdfToPng('/path/to/pdf/file.pdf', {
* pagesToProcess: [1, 2, 3],
* outputFolder: '/path/to/output/folder',
* viewportScale: 2.0,
* outputFileMaskFunc: (pageNumber) => `custom_name_page_${pageNumber}.png`,
* });
* ```
*/
export declare function pdfToPng(pdfFile: string | ArrayBufferLike, props?: PdfToPngOptions): Promise<PngPageOutput[]>;

@@ -1,72 +0,92 @@

var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
import { promises as fsPromises } from 'node:fs';
import { parse, resolve } from 'node:path';
import { PDF_TO_PNG_OPTIONS_DEFAULTS } from './const';
import { propsToPdfDocInitParams } from './propsToPdfDocInitParams';
export function pdfToPng(pdfFile, props) {
return __awaiter(this, void 0, void 0, function* () {
var _a;
const isBuffer = Buffer.isBuffer(pdfFile);
const pdfFileBuffer = isBuffer ? pdfFile : (yield fsPromises.readFile(pdfFile)).buffer;
const pdfDocument = yield getPdfDocument(pdfFileBuffer, props);
const pagesToProcess = (_a = props === null || props === void 0 ? void 0 : props.pagesToProcess) !== null && _a !== void 0 ? _a : Array.from({ length: pdfDocument.numPages }, (_, index) => index + 1);
const pngPagesOutput = [];
try {
const pngPageOutputs = yield Promise.all(pagesToProcess
.filter((pageNumber) => pageNumber <= pdfDocument.numPages && pageNumber >= 1)
.map((pageNumber) => {
var _a, _b;
const pageViewportScale = (props === null || props === void 0 ? void 0 : props.viewportScale) !== undefined ? props.viewportScale : PDF_TO_PNG_OPTIONS_DEFAULTS.viewportScale;
const defaultMask = isBuffer ? PDF_TO_PNG_OPTIONS_DEFAULTS.outputFileMask : parse(pdfFile).name;
const pageName = (_b = (_a = props === null || props === void 0 ? void 0 : props.outputFileMaskFunc) === null || _a === void 0 ? void 0 : _a.call(props, pageNumber)) !== null && _b !== void 0 ? _b : `${defaultMask}_page_${pageNumber}.png`;
return processPdfPage(pdfDocument, pageName, pageNumber, pageViewportScale);
}));
pngPagesOutput.push(...pngPageOutputs);
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.pdfToPng = pdfToPng;
const node_fs_1 = require("node:fs");
const node_path_1 = require("node:path");
const const_1 = require("./const");
const propsToPdfDocInitParams_1 = require("./propsToPdfDocInitParams");
/**
* Converts a PDF file to PNG images.
*
* @param pdfFile - The path to the PDF file or a buffer containing the PDF data.
* @param props - Optional properties to customize the conversion process.
* @returns A promise that resolves to an array of PNG page outputs.
*
* @throws Will throw an error if invalid pages are requested when `strictPagesToProcess` is true.
*
* @example
* ```typescript
* const pngPages = await pdfToPng('/path/to/pdf/file.pdf', {
* pagesToProcess: [1, 2, 3],
* outputFolder: '/path/to/output/folder',
* viewportScale: 2.0,
* outputFileMaskFunc: (pageNumber) => `custom_name_page_${pageNumber}.png`,
* });
* ```
*/
async function pdfToPng(pdfFile, props) {
const isBuffer = Buffer.isBuffer(pdfFile);
const pdfFileBuffer = isBuffer ? pdfFile : (await node_fs_1.promises.readFile(pdfFile)).buffer;
const pdfDocument = await getPdfDocument(pdfFileBuffer, props);
// Get the pages to process based on the provided options, invalid pages will be filtered out
const pagesToProcess = props?.pagesToProcess ?? Array.from({ length: pdfDocument.numPages }, (_, index) => index + 1);
const pngPagesOutput = [];
try {
// Process each page in parallel
const pngPageOutputs = await Promise.all(pagesToProcess
// Filter out invalid page numbers
.filter((pageNumber) => pageNumber <= pdfDocument.numPages && pageNumber >= 1)
// Process the page
.map((pageNumber) => {
const pageViewportScale = props?.viewportScale !== undefined ? props.viewportScale : const_1.PDF_TO_PNG_OPTIONS_DEFAULTS.viewportScale;
const defaultMask = isBuffer ? const_1.PDF_TO_PNG_OPTIONS_DEFAULTS.outputFileMask : (0, node_path_1.parse)(pdfFile).name;
const pageName = props?.outputFileMaskFunc?.(pageNumber) ?? `${defaultMask}_page_${pageNumber}.png`;
return processPdfPage(pdfDocument, pageName, pageNumber, pageViewportScale);
}));
pngPagesOutput.push(...pngPageOutputs);
}
finally {
await pdfDocument.cleanup();
}
// Save the PNG files to the output folder
if (props?.outputFolder) {
await node_fs_1.promises.mkdir(props.outputFolder, { recursive: true });
for (const pngPageOutput of pngPagesOutput) {
pngPageOutput.path = (0, node_path_1.resolve)(props.outputFolder, pngPageOutput.name);
await node_fs_1.promises.writeFile(pngPageOutput.path, pngPageOutput.content);
pngPageOutput.path = (0, node_path_1.resolve)(props.outputFolder, pngPageOutput.name);
}
finally {
yield pdfDocument.cleanup();
}
if (props === null || props === void 0 ? void 0 : props.outputFolder) {
yield fsPromises.mkdir(props.outputFolder, { recursive: true });
for (const pngPageOutput of pngPagesOutput) {
pngPageOutput.path = resolve(props.outputFolder, pngPageOutput.name);
yield fsPromises.writeFile(pngPageOutput.path, pngPageOutput.content);
pngPageOutput.path = resolve(props.outputFolder, pngPageOutput.name);
}
}
return pngPagesOutput;
});
}
return pngPagesOutput;
}
function getPdfDocument(pdfFileBuffer, props) {
return __awaiter(this, void 0, void 0, function* () {
const { getDocument } = yield import('pdfjs-dist/legacy/build/pdf.mjs');
const documentInitParameters = propsToPdfDocInitParams(props);
return yield getDocument(Object.assign(Object.assign({}, documentInitParameters), { data: new Uint8Array(pdfFileBuffer) })).promise;
});
/**
* Asynchronously retrieves a PDF document from a given ArrayBuffer.
*
* @param pdfFileBuffer - The buffer containing the PDF file data.
* @param props - Optional properties to customize the PDF document initialization.
* @returns A promise that resolves to a PDFDocumentProxy object representing the PDF document.
*/
async function getPdfDocument(pdfFileBuffer, props) {
const { getDocument } = await import('pdfjs-dist/legacy/build/pdf.mjs');
const documentInitParameters = (0, propsToPdfDocInitParams_1.propsToPdfDocInitParams)(props);
return await getDocument({
...documentInitParameters,
data: new Uint8Array(pdfFileBuffer),
}).promise;
}
function processPdfPage(pdfDocument, pageName, pageNumber, pageViewportScale) {
return __awaiter(this, void 0, void 0, function* () {
const page = yield pdfDocument.getPage(pageNumber);
const viewport = page.getViewport({ scale: pageViewportScale });
const { canvas, context } = pdfDocument.canvasFactory.create(viewport.width, viewport.height);
yield page.render({ canvasContext: context, viewport }).promise;
const pngPageOutput = {
pageNumber,
name: pageName,
content: canvas.toBuffer('image/png'),
path: '',
width: viewport.width,
height: viewport.height,
};
page.cleanup();
return pngPageOutput;
});
async function processPdfPage(pdfDocument, pageName, pageNumber, pageViewportScale) {
const page = await pdfDocument.getPage(pageNumber);
const viewport = page.getViewport({ scale: pageViewportScale });
const { canvas, context } = pdfDocument.canvasFactory.create(viewport.width, viewport.height);
await page.render({ canvasContext: context, viewport }).promise;
const pngPageOutput = {
pageNumber,
name: pageName,
content: canvas.toBuffer('image/png'),
path: '',
width: viewport.width,
height: viewport.height,
};
page.cleanup();
return pngPageOutput;
}
import * as pdfApiTypes from 'pdfjs-dist/types/src/display/api';
import { PdfToPngOptions } from './types/pdf.to.png.options';
/**
* Converts the given `PdfToPngOptions` object to a `pdfApiTypes.DocumentInitParameters` object.
* @param props - The `PdfToPngOptions` object to convert.
* @returns The resulting `pdfApiTypes.DocumentInitParameters` object.
*/
export declare function propsToPdfDocInitParams(props?: PdfToPngOptions): pdfApiTypes.DocumentInitParameters;

@@ -1,15 +0,25 @@

import { DOCUMENT_INIT_PARAMS_DEFAULTS, PDF_TO_PNG_OPTIONS_DEFAULTS } from './const';
import { VerbosityLevel } from './types/verbosity.level';
export function propsToPdfDocInitParams(props) {
const pdfDocInitParams = Object.assign({}, DOCUMENT_INIT_PARAMS_DEFAULTS);
pdfDocInitParams.verbosity = (props === null || props === void 0 ? void 0 : props.verbosityLevel) !== undefined ? props === null || props === void 0 ? void 0 : props.verbosityLevel : VerbosityLevel.ERRORS;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.propsToPdfDocInitParams = propsToPdfDocInitParams;
const const_1 = require("./const");
const verbosity_level_1 = require("./types/verbosity.level");
/**
* Converts the given `PdfToPngOptions` object to a `pdfApiTypes.DocumentInitParameters` object.
* @param props - The `PdfToPngOptions` object to convert.
* @returns The resulting `pdfApiTypes.DocumentInitParameters` object.
*/
function propsToPdfDocInitParams(props) {
const pdfDocInitParams = {
...const_1.DOCUMENT_INIT_PARAMS_DEFAULTS,
};
pdfDocInitParams.verbosity = props?.verbosityLevel !== undefined ? props?.verbosityLevel : verbosity_level_1.VerbosityLevel.ERRORS;
pdfDocInitParams.disableFontFace =
(props === null || props === void 0 ? void 0 : props.disableFontFace) !== undefined ? props.disableFontFace : PDF_TO_PNG_OPTIONS_DEFAULTS.disableFontFace;
props?.disableFontFace !== undefined ? props.disableFontFace : const_1.PDF_TO_PNG_OPTIONS_DEFAULTS.disableFontFace;
pdfDocInitParams.useSystemFonts =
(props === null || props === void 0 ? void 0 : props.useSystemFonts) !== undefined ? props.useSystemFonts : PDF_TO_PNG_OPTIONS_DEFAULTS.useSystemFonts;
props?.useSystemFonts !== undefined ? props.useSystemFonts : const_1.PDF_TO_PNG_OPTIONS_DEFAULTS.useSystemFonts;
pdfDocInitParams.enableXfa =
(props === null || props === void 0 ? void 0 : props.enableXfa) !== undefined ? props.enableXfa : PDF_TO_PNG_OPTIONS_DEFAULTS.enableXfa;
props?.enableXfa !== undefined ? props.enableXfa : const_1.PDF_TO_PNG_OPTIONS_DEFAULTS.enableXfa;
pdfDocInitParams.password =
(props === null || props === void 0 ? void 0 : props.pdfFilePassword) !== undefined ? props === null || props === void 0 ? void 0 : props.pdfFilePassword : PDF_TO_PNG_OPTIONS_DEFAULTS.pdfFilePassword;
props?.pdfFilePassword !== undefined ? props?.pdfFilePassword : const_1.PDF_TO_PNG_OPTIONS_DEFAULTS.pdfFilePassword;
return pdfDocInitParams;
}

@@ -1,2 +0,5 @@

export const VerbosityLevel = {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.VerbosityLevel = void 0;
exports.VerbosityLevel = {
ERRORS: 0,

@@ -3,0 +6,0 @@ WARNINGS: 1,

{
"name": "pdf-to-png-converter",
"version": "3.6.1",
"version": "3.6.3",
"description": "Node.js utility to convert PDF file/buffer pages to PNG files/buffers with no native dependencies.",
"keywords": [
"pdf",
"pdf parse",
"pdf to png",

@@ -22,6 +23,6 @@ "pdf to image",

"author": "Igor Magdich <magdich.igor@gmail.com>",
"main": "out/index.js",
"types": "out/index.d.ts",
"main": "./out/index.js",
"types": "./out/index.d.ts",
"files": [
"/out"
"./out"
],

@@ -38,8 +39,7 @@ "scripts": {

"docker:test": "vitest run --coverage",
"license-checker": "npx license-checker --production --onlyAllow 'MIT; MIT OR X11; BSD; ISC; Apache-2.0; Unlicense'",
"lint": "eslint .",
"lint:fix": "npm run lint -- --fix",
"pretest": "npm run build",
"test": "vitest run --coverage",
"test:docker": "npm run clean && npm run docker:build && npm run docker:run"
"test:docker": "npm run clean && npm run docker:build && npm run docker:run",
"test:license": "npx --yes license-checker --production --onlyAllow \"ISC; MIT; MIT OR X11; BSD; Apache-2.0; Unlicense\""
},

@@ -50,9 +50,10 @@ "dependencies": {

"devDependencies": {
"@tsconfig/recommended": "^1.0.8",
"@types/eslint__eslintrc": "^2.1.2",
"@types/node": "^22.10.1",
"@typescript-eslint/eslint-plugin": "^8.17.0",
"@typescript-eslint/parser": "^8.17.0",
"@types/node": "^22.10.2",
"@typescript-eslint/eslint-plugin": "^8.18.0",
"@typescript-eslint/parser": "^8.18.0",
"@vitest/coverage-v8": "^2.1.8",
"eslint": "^9.16.0",
"png-visual-compare": "^2.2.1",
"eslint": "^9.17.0",
"png-visual-compare": "^2.5.0",
"rimraf": "^6.0.1",

@@ -63,4 +64,5 @@ "typescript": "^5.7.2",

"engines": {
"node": ">=20.0.0"
"node": ">=20",
"yarn": "please-use-npm"
}
}
# pdf-to-png-converter
Node.js utility to convert PDF file/buffer pages to PNG files/buffers without binary and OS dependencies (except macOS on arm64).
A Node.js utility to convert PDF file/buffer pages to PNG files/buffers without binary and OS dependencies. This utility is ideal for applications that need to process and convert PDF documents into image formats for easier viewing, sharing, or further image processing. It supports various options for rendering fonts, handling encrypted PDFs, and specifying output details, making it a versatile tool for developers working with PDF files in different environments.

@@ -17,2 +17,4 @@ [![Tests on push](https://github.com/dichovsky/pdf-to-png-converter/actions/workflows/test.yml/badge.svg?branch=main)](https://github.com/dichovsky/pdf-to-png-converter/actions/workflows/test.yml)

**Note:** This package requires Node.js version 22 or higher.
## Example

@@ -30,3 +32,3 @@

outputFolder: 'output/folder', // Folder to write output PNG files. If not specified, PNG output will be available only as a Buffer content, without saving to a file.
outputFileMaskFunc, // Output filename mask function.
outputFileMaskFunc: (pageNum) => `page_${pageNum}.png`, // Function to generate custom output filenames. Example: (pageNum) => `page_${pageNum}.png`
pdfFilePassword: 'pa$$word', // Password for encrypted PDF.

@@ -50,3 +52,3 @@ pagesToProcess: [1, 3, 11], // Subset of pages to convert (first page = 1), other pages will be skipped if specified.

content: Buffer; // PNG page Buffer content
path: string; // Path to the rendered PNG page file (empty string if outputFilesFolder is not provided)
path: string; // Path to the rendered PNG page file (empty string if outputFolder is not provided)
width: number; // PNG page width

@@ -53,0 +55,0 @@ height: number; // PNG page height

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc