statement-parser-fab
Version:
Parse bank and credit card statements. Updated fork with FAB (First Abu Dhabi Bank) support and maintained dependencies.
64 lines (63 loc) • 2.42 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.checkThatPdfExists = exports.getPdfDocument = exports.readPdf = void 0;
const fs_extra_1 = require("fs-extra");
const pdf_1 = require("pdfjs-dist/legacy/build/pdf");
async function readPdf(path) {
checkThatPdfExists(path);
// Use custom positioning-based extraction instead of pdf-text-reader
const document = await getPdfDocument(path);
const pages = [];
for (let pageNum = 1; pageNum <= document.numPages; pageNum++) {
const page = await document.getPage(pageNum);
const textContent = await page.getTextContent();
// Group text items by Y position (preserve table structure)
const itemsByY = {};
textContent.items.forEach((item) => {
if ('str' in item && item.transform && item.transform[5] !== undefined) {
const y = Math.round(item.transform[5]);
if (!itemsByY[y])
itemsByY[y] = [];
const yArray = itemsByY[y];
if (yArray) {
yArray.push(item);
}
}
});
// Create lines sorted by Y position (top to bottom)
const lines = [];
Object.keys(itemsByY)
.map((y) => parseInt(y))
.sort((a, b) => b - a) // Sort by Y descending (top to bottom)
.forEach((y) => {
const lineData = itemsByY[y];
if (lineData) {
const lineItems = lineData.sort((a, b) => a.transform[4] - b.transform[4]); // Sort by X
const lineText = lineItems
.map((item) => item.str)
.join(' ')
.trim();
if (lineText) {
lines.push(lineText);
}
}
});
pages.push(lines);
}
return pages;
}
exports.readPdf = readPdf;
async function getPdfDocument(path) {
checkThatPdfExists(path);
return await (0, pdf_1.getDocument)(createSource(path)).promise;
}
exports.getPdfDocument = getPdfDocument;
function createSource(path) {
return { url: path, verbosity: pdf_1.VerbosityLevel.ERRORS };
}
function checkThatPdfExists(filePath) {
if (!(0, fs_extra_1.existsSync)(filePath)) {
throw new Error(`PDF file "${filePath}" does not exist`);
}
}
exports.checkThatPdfExists = checkThatPdfExists;