srs-api/src/results/pdfText.ts
Aswin Biju 6851d66b38 feat: SRS backend: orders intake, results pipeline, user management
Fastify + TypeScript + SQLite backend for a single Kerala lottery agency.
2026-11-03 10:09:46 +05:30

27 lines
1.0 KiB
TypeScript

import { execFile } from 'node:child_process';
import { mkdtemp, rm, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
export async function extractPdfText(pdf: Buffer, bin = 'pdftotext', timeoutMs = 30_000): Promise<string> {
const dir = await mkdtemp(join(tmpdir(), 'srs-pdf-'));
try {
const file = join(dir, 'result.pdf');
await writeFile(file, pdf);
return await new Promise<string>((resolve, reject) => {
execFile(
bin,
['-raw', '-enc', 'UTF-8', file, '-'],
{ encoding: 'utf8', maxBuffer: 20 * 1024 * 1024, timeout: timeoutMs },
(err, stdout) => {
if (!err) return resolve(stdout.replace(/\r\n/g, '\n'));
const missing = (err as NodeJS.ErrnoException).code === 'ENOENT';
reject(new Error(missing ? 'pdftotext not found: install poppler-utils' : `pdftotext failed: ${err.message}`));
},
);
});
} finally {
await rm(dir, { recursive: true, force: true });
}
}