Parsing Spanish payslips in the browser, and throwing away the ID data
Ahorreo imports bank statements as CSV or Excel and nothing else. Early on we wrote down that bank statement PDFs were out: a PDF can be read wrong without anyone noticing. A thousands separator gets lost, 1.250,00 becomes 250,00, and nothing on the screen looks broken.
Payslips are the one exception, and this post is about why, and how we read them without keeping who you are.
Why a payslip can be a PDF
There’s no alternative format. Banks let you download a CSV; employers give you a PDF and that’s it. If we wanted payslips at all, we had to read PDFs.
What made it acceptable is that a Spanish payslip (hoja de salario) checks itself. It prints every earning and every deduction, then the total of each column, then the net pay, which has to be the difference. A misread number breaks at least one of those sums. So the rule we wrote for PDFs (ADR-018 in the Ahorreo repo) has three conditions:
- A dedicated parser for a layout we have seen. No generic PDF reader, no manual column mapping.
- Text only. No OCR.
- The document’s own totals must add up to the cent, or it isn’t imported.
Bank statement PDFs still fail the third condition, because they carry no totals to check against, so they stay out.
Getting text out of the PDF
We use pdf.js. It’s loaded with a dynamic import() only when you pick a PDF, so nobody who never imports a payslip downloads it. Its worker is served from the app’s own bundle, so the Content Security Policy and the test that forbids network calls didn’t need to change. The file arrives as bytes in memory. From src/features/payroll/pdfText.ts:
const task = pdfjs.getDocument({
data: new Uint8Array(buffer),
isEvalSupported: false,
useSystemFonts: false,
disableFontFace: true,
verbosity: 0,
});
What comes out is a list of text pieces with their position on the page: the string, x, y, width and page number. That’s all the domain code ever sees. It doesn’t know pdf.js exists, which means the parser can be tested against a real PDF without the rest of the app.
If fewer than five of those pieces contain a letter, the PDF has no text layer: it’s a scan. Ahorreo says so (“This PDF has no text layer”) and offers manual entry instead. In manual entry you type the totals too, and the app checks them against the lines you typed. We could compute them for you, but then there’d be nothing to check.
Reading by position
A payslip is a table drawn on a page, not a table in a file. The parser groups text pieces into rows by their y coordinate, finds the header row (CONCEPTO, DEVENGOS, DEDUCCIONES) and reads each value from the column under its label.
Each page is read on its own. The first version merged all pages into one, and since every page starts at the top, page two was laid over page one. The grid ends at the totals row, so half the deductions went missing and the document was accused of not adding up.
Payroll software doesn’t agree on labels either. Ahorreo knows two layouts, which the code calls rem-total and detalle after labels they print. Each is recognised by a signature: labels from two different parts of the page, because one heading can match by accident and two are less likely to. The vocabulary for each layout lives in src/domain/payroll/formats.ts, and the file has one rule: a new layout never loosens a check. If a document can’t be read with every sum closing, it isn’t imported, and the fix is to learn to read it.
Eight checks, four of which block
Once it’s read, src/domain/payroll/checks.ts runs up to eight checks the document makes about itself. Four block the import if they’re off by even a cent:
- Sum of earnings: the earnings column adds up to the declared total.
- Sum of deductions: same for deductions.
- Net pay: total earned minus total deducted is the net pay.
- Total remuneration: the earnings minus the lines that aren’t salary (the document marks them with a prefix and explains the prefixes in its footer), minus overtime, which the document declares with a base of its own.
The other four only warn:
- Each contribution against its base: every social security contribution should be its base times its printed rate. The tolerance is one cent, because the document rounded that product before printing it.
- Flexible benefits: in-kind benefit lines should equal the deduction that pays for them.
- Employer cost, which often doesn’t close because documents don’t itemise everything that goes into it. We show both numbers and the gap, and don’t invent lines to fill it.
- Sum of employer contributions in the box at the bottom.
A check that doesn’t apply to your document (no flexible benefits, say) isn’t shown as passed. It’s shown as “Can’t be checked”, because a check that says “passes” without having run is a lie in the worst possible place. Simplified from checks.ts:
checks.push(check('earnings-sum', totals.totalEarned, sum(earnings.map((l) => l.amount), currency)));
checks.push(check('deductions-sum', totals.totalDeducted, sum(deductions.map((l) => l.amount), currency)));
checks.push(check('net-pay', totals.netPay, subtract(totals.totalEarned, totals.totalDeducted)));
All the amounts are integer cents, as everywhere in Ahorreo (why money should never be a float), so “adds up” means exactly equal, not “close enough”. If a blocking check fails, the preview still shows what was read and which check failed, with both numbers, but there’s no “import anyway” button. The save function runs the checks again and refuses, so a screen can’t skip them by mistake.
The net pay against the bank
A payslip creates no transaction in Ahorreo. The net pay is already in your current account, imported from the bank statement; if the payslip created it too, every month would have two salaries. Instead the payslip is matched to the income that’s already there: same account, same accrual period, positive amount.
The match gives one of five answers: the deposit equals the net pay exactly; it differs by exactly one carried-over line from a previous month (Spanish payslips have a line for that); it differs and the document doesn’t explain why, and by how much; there are transactions that month but none that could be this payslip; or there’s no statement for that month yet. A mismatch is never adjusted. The bank is right about what reached the account, and the payslip is right about why.
The data it never reads
A payslip carries your name, home address, DNI (the Spanish national ID number) and social security number, and the employer’s registration number. None of that explains a single figure, and all of it turns a stolen backup from “how much they earn” into “who they are and where they live”.
So the parser doesn’t read those fields at all. They aren’t read and then deleted; the code never looks at those cells:
- Job category, job title and seniority are read from the columns under their own labels. The worker-name and DNI columns next to them are never touched.
- The employer’s name is read by its left edge. In one layout the worker’s name sits on the same row, one column over, and reading by edge leaves it out.
- The employer’s tax ID is accepted only if it matches the pattern of a company tax ID (CIF). In the
detallelayout the company’s and the worker’s ID columns have the same label, and that pattern is the only thing that tells them apart. A personal DNI doesn’t match it, so nothing is saved. - The IBAN is read, because it’s what tells Ahorreo which account receives the salary. It’s used to pick that account and isn’t stored with the payslip. The account’s IBAN was already in Ahorreo from the first statement import, so that’s not new exposure.
What gets saved is the employer (name and tax ID), the period, the lines, the totals, the result of the checks and the parser version. The PDF itself is never stored: it’s read into memory, its text is extracted, and the pdf.js document is destroyed.
And like the zero-network rule, this one has a test. The fixture is a real PDF, generated by a test helper that draws text at the positions measured on a real payslip, with invented amounts and an invented identity. The identity has to be there, or the test proves nothing. From src/domain/payroll/parse.test.ts:
it('cap dada personal arriba al model', async () => {
const { draft } = await parse(nominaCompleta);
const serialised = JSON.stringify(draft);
for (const secret of [
'EXEMPLE EXEMPLE, NOM',
'CL EXEMPLE, 1 2 3',
'00000 CIUTAT',
'PROVINCIA',
'00000000X',
'07/00000000-00',
'07/0000000-00',
]) {
expect(serialised, secret).not.toContain(secret);
}
});
(The test name is Catalan, like the rest of the codebase: “no personal data reaches the model”.)
Limits
- Scanned PDFs are rejected. No OCR, by design: OCR is where misreading comes from. Manual entry is the way in.
- Two layouts. A payslip from different payroll software is rejected with “This doesn’t look like a payslip” and a list of the labels it couldn’t find. Every new layout needs a real document to build against, which is why the list is short.
- No tax calculation. Ahorreo reads what was withheld; it never computes what should have been. Getting a tax figure wrong has legal consequences, and tax is out of scope for the whole app.
- Currency is often assumed. The payslips we’ve verified print no currency symbol, so Ahorreo uses the account’s currency and says that’s what it did.
- Reports stay net. The gross salary, contributions and withholding live on the payslip’s own page. Moving them into the monthly reports would change the meaning of every savings rate and budget at once, so we didn’t.
The categories that incoming salary gets are decided by the cascade described in Categorising bank transactions without a server.
This article explains how our software works and the maths behind it. It is not financial, tax or legal advice: for decisions about your own money, check with a qualified professional.