pdf-decomposer
Version:
📚 Extract text and images (as buffers) from PDF files using native parsing and OCR with Tesseract.
40 lines (39 loc) • 1.4 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.pdfToPng = pdfToPng;
const child_process_1 = require("child_process");
const crypto_1 = require("crypto");
const fs_1 = __importDefault(require("fs"));
const path_1 = __importDefault(require("path"));
/**
* Convert each pdf page into pdf
* @param pdfPath path to pdf file
* @returns png buffers
*/
function pdfToPng(pdfPath) {
const tmpDir = path_1.default.join(path_1.default.dirname(pdfPath), (0, crypto_1.randomUUID)());
if (!fs_1.default.existsSync(tmpDir)) {
fs_1.default.mkdirSync(tmpDir);
}
return new Promise((resolve, reject) => {
const proc = (0, child_process_1.spawn)('pdftoppm', [
'-png',
pdfPath,
path_1.default.join(tmpDir, 'page'),
]);
proc.on('close', (code) => {
if (code === 0) {
resolve(fs_1.default.readdirSync(tmpDir).map((f) => fs_1.default.readFileSync(`${tmpDir}/${f}`)));
}
else {
reject(new Error(`pdftoppm exited with code ${code}`));
}
});
proc.stderr.on('data', (err) => {
throw new Error(`Fail to parse pdf ${err.toString()}`);
});
});
}