通用 PDF 轉 Excel 工具為何會漏掉交易,以及雙鏈餘額核對如何找出異常
Why Generic PDF-to-Excel Converters Silently Drop Transactions — And How Dual-Chain Running Balance Math Catches It
作者拆解通用 PDF 轉 Excel 工具漏掉美國銀行結單交易的原因,並介紹 DocuBridge 的座標解析、雙鏈餘額核對、公式注入防護及私隱架構。文中以漏掉一筆 $490.40 Zelle 入帳為例,説明以 Python 的 decimal.Decimal 精確計算並維持兩條餘額累計鏈,可定位異常交易,避免單鏈檢查造成後續多行連帶誤報。
If you have ever converted a PDF bank statement into Excel using a generic PDF-to-XLSX tool—or Excel's built-in Power Query PDF connector—you have probably seen a spreadsheet that looks completely fine. The columns line up. The rows look tidy.
Then, at month-end close, your QuickBooks or Excel reconciliation is off by $490.40. Twenty-five minutes of line-by-line checking later, you discover that a single Zelle deposit sitting at the bottom of page 1 silently vanished during extraction.
When we built DocuBridge, we started from one rule: a bank statement converter that does not prove its own math is worse than manual data entry, because manual typos feel uncertain while a neat CSV creates false confidence.
This post breaks down why generic PDF extractors fail silently on US bank statements, and four concrete architectural patterns we implemented in Python and Next.js to make failures loud, deterministic, and safe:
- Coordinate-based layout parsing for real bank PDF quirks.
-
Dual-chain running balance verification in
decimal.Decimalthat isolates a single broken row without cascading false alarms. - Defense-in-depth spreadsheet formula-injection protection across CSV and XLSX exports.
- A privacy-first boundary using browser pre-checks, zero-disk worker isolation, in-memory local OCR, dual-factor HKDF crypto-shredding, and a strict per-request nonce CSP.
1. Why Bank Statement PDFs Break Generic Table Extractors
The PDF specification has no native "table" primitive—only positioned glyph runs on a 72-DPI canvas. Generic converters cluster bounding boxes into grids, which routinely breaks on real US checking and savings statements for four reasons:
- Multi-line wrapped descriptions: ACH entries, wire memos, and card purchases wrap across two or three lines directly beneath the row with nothing in the Date or Amount columns. Generic tools spawn orphan rows or drop continuation text.
-
Ambiguous amount columns and sign conventions: Some banks print one signed
Amountcolumn (-53.61,2520.17). Others print unsignedWithdrawals/DebitsandDeposits/Creditscolumns, trailingCR/DRsuffixes, placeholder dashes (—), or separate Deposits and Withdrawals sections sharing identical headers. -
Yearless
MM/DDdates across year boundaries: Many US banks print12/29and01/03without a year, relying on a statement period likeDec 15 - Jan 14, 2026. Stamping every row with the end year pushes December transactions a full year into the future. Our parser resolves yearless(month, day)tuples against[period_start - 10 days, period_end + 10 days]before falling back to a flagged inference. -
Page furniture impersonating rows: Repeating headers,
"Page 2 of 4","Continued", section subtotals, and"Daily Balance Summary"boxes contain dates and dollar amounts. Mistaking a subtotal for a transaction—or a real row near a page break for a footer—produces a tidy spreadsheet whose totals silently diverge.
2. Why "Looks Like a Table" Is a Financial Hazard
In document-AI benchmarks, 98% row accuracy sounds great. In bookkeeping, 98% accuracy on a 100-row statement means two corrupted or missing transactions on every single statement—with zero warning about which two failed.
Consider a real case from our end-to-end synthetic test suite (missing-row.pdf, January 2026):
-
Printed Opening / Closing Balance:
$1,115.75→-$623.33 -
Extracted Rows: 14 transactions (
$5,085.79credits,$7,315.27debits) -
Computed Closing Balance:
$1,115.75 + $5,085.79 - $7,315.27 = -$1,113.73 -
Discrepancy:
-$623.33 - (-$1,113.73) = +$490.40
One $490.40 Zelle deposit between row 4 (01/06) and row 5 (01/09) was missing. Also note that IEEE 754 float has no place in accounting math: every monetary token must stay in Python's decimal.Decimal across all sums, running-balance checks, and diffs so exact-cent equality never suffers binary rounding drift.
3. Dual-Chain Running Balance Verification
Before any statement can earn a VERIFIED badge, it must pass two independent accounting proofs:
-
Statement-level identity:
opening + total_credits - total_debits == closingwith exactDecimal("0.00")tolerance. If opening or closing balance is missing, the status is strictlyUNVERIFIABLE—never a green checkmark. - Row-level running balance proof: Every printed running balance (or daily ending balance) must agree mathematically with the preceding transactions.
The Naive Single-Chain Trap
The obvious implementation tracks one running sum from opening:
# Naive single-chain check (DO NOT USE)
running = opening
for tx in transactions:
running += tx.amount
if tx.balance is not None and running != tx.balance:
breaks.append(tx.id)
If row 5 on a 60-row statement is missing a $490.40 deposit—or OCR misreads one digit of row 5's amount—row 5 fails, row 6 fails, and rows 7 through 60 all fail. One localized glitch causes 56 cascading false positives.
The Dual-Chain Algorithm
Instead, we maintain two simultaneous chains:
-
anchor+since_anchor: cumulative sum from the last trustworthy balance (initiallyopening, updated only when a row agrees). -
prev+since_prev: cumulative sum from the immediately preceding printed balance (always updated, even after a break).
A row's printed balance passes if it agrees with either chain:
from decimal import Decimal
ZERO = Decimal("0.00")
def reconcile(txs, opening: Decimal | None, closing: Decimal | None):
credits = sum((t.amount for t in txs if t.amount > 0), ZERO)
debits = sum((-t.amount for t in txs if t.amount < 0), ZERO)
breaks: list[str] = []
anchor = prev = opening
since_anchor = since_prev = ZERO
for t in txs:
since_anchor += t.amount
since_prev += t.amount
if t.balance is None:
continue
ok_anchor = anchor is not None and (anchor + since_anchor == t.balance)
ok_prev = prev is not None and (prev + since_prev == t.balance)
if anchor is not None and not (ok_anchor or ok_prev):
breaks.append(t.id)
else:
anchor, since_anchor = t.balance, ZERO
prev, since_prev = t.balance, ZERO
if not txs:
return ("unverifiable", "no_transactions", None, None, breaks)
if opening is None or closing is None:
return ("unverifiable", "missing_opening_or_closing_balance", None, None, breaks)
computed = opening + credits - debits
diff = closing - computed
if diff != ZERO:
return ("mismatch", "totals_do_not_match", computed, diff, breaks)
if breaks:
return ("mismatch", "running_balance_breaks", computed, ZERO, breaks)
return ("verified", "balanced", computed, ZERO, breaks)
Why does this isolate both single-row failure modes cleanly?
-
Case A — Single misread printed balance on row k: Row k fails both chains and is flagged;
anchorstays on row k−1. On row k+1,prevdisagrees, butanchor + since_anchorequals row k+1's true balance, so row k+1 passes and re-anchors. Only row k is flagged. -
Case B — Single misread amount or dropped row right before row k: Trace our
$490.40missing Zelle deposit:
| Row | Date | Amount | Printed Bal. | anchor + Δ |
prev + Δ |
Outcome |
|---|---|---|---|---|---|---|
| 4 | 01/06 |
-986.72 |
1,823.52 |
1,823.52 ✓ |
1,823.52 ✓ |
Clean (anchor=prev=1823.52) |
| 5 | 01/09 |
-89.25 |
2,224.67 |
1,734.27 ✗ |
1,734.27 ✗ |
Flagged (balance_break); prev → 2224.67
|
| 6 | 01/09 |
-39.97 |
2,184.70 |
1,694.30 ✗ |
2,184.70 ✓ |
Clean! Matches prev, re-anchors |
| 7 | 01/10 |
-81.28 |
2,103.42 |
2,103.42 ✓ |
2,103.42 ✓ |
Clean! |
Out of an entire multi-page statement, only row 5 is tagged needs_review with its exact source_page. Rows where t.balance is None (such as Wells Fargo daily-ending-balance statements) accumulate cleanly into both deltas until the next printed balance.
4. Defending Against Spreadsheet Formula Injection (OWASP CSV Injection)
Bank descriptions are untrusted third-party strings. Legitimate merchants start with formula characters (@HOME DECOR OUTLET, +1 MOBILE TOPUP, =TAX PREP SERVICES LLC), and malicious P2P memos can smuggle =HYPERLINK(...) or legacy DDE payloads.
Our exporter defends both CSV and XLSX outputs identically:
DANGEROUS_PREFIXES = ("=", "+", "-", "@", "\t", "\r", "=", "+", "-", "@")
def safe_text(value: str) -> str:
return "'" + value if value.startswith(DANGEROUS_PREFIXES) else value
Three details matter in practice:
-
Block full-width Unicode triggers (
=,+,-,@) alongside ASCII=,+,-,@,\t, and\r. -
Harden XLSX and CSV together: In
.xlsx, we setcell.data_type = "s"(explicit string) and keep the leading single quote so the cell remains inert if a user later opens the.xlsxin Excel and runs Save As → CSV. -
Emit boring, import-safe CSVs: UTF-8 with BOM (
\ufeff),CRLFline endings,MM/DD/YYYYdates, plain decimals without currency symbols or thousands commas (-53.61), and both separateDebit/Creditcolumns and a signedAmountcolumn so QuickBooks Online (3- or 4-column) and Xero import without manual reformatting.
5. Privacy-First Architecture for Sensitive Financial PDFs
Bank statements expose salaries, landlords, medical providers, and counterparties. We built our security boundary around five explicit constraints:
-
Browser pre-checks & explicit consent: Locally in the browser,
pdf.jsvalidates PDF magic bytes, file size (≤ 4 MB), page count (≤ 15), and password protection before any upload. Nothing transmits until the user reviews a plain-English disclosure and consents. -
Zero raw-PDF disk storage & isolated worker: Uploaded bytes never hit disk or object storage (
rawFileStored: false). The API pipes bytes overstdininto a short-lived Python subprocess inside a read-only container withRLIMIT_FSIZE=0and strict CPU, memory, and wall-clock limits. A malformed PDF can only kill the disposable worker, and the PDF bytes vanish from RAM as soon as parsing completes. -
In-memory local OCR boundary: Sending financial PDFs to third-party cloud OCR or LLM vision APIs expands the subprocessor blast radius. For clear scanned PDFs up to 5 pages, the same worker renders pages in memory via PDFium (
pypdfium2), writes grayscale PNGs to anio.BytesIObuffer, and pipes them into localtesseract stdin stdout -l eng --psm 6 tsv. Word coordinates scale back to 72 DPI and enter the exact same layout parser and dual-chain reconciliation—zero disk writes, zero external APIs. -
Dual-factor HKDF crypto-shredding at rest: Extracted transactions stay available for up to 24 hours (or until the user clicks Delete) so flagged rows can be reviewed and fixed. Each job is sealed with
AES-256-GCMunder a key derived from both the server key and a browser-onlyHttpOnlycookie secret:
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.hkdf import HKDF
def job_key(server_key: bytes, session_secret: str, job_id: str) -> bytes:
hkdf = HKDF(
algorithm=hashes.SHA256(),
length=32,
salt=job_id.encode(),
info=b"docubridge/job-payload/v1",
)
return hkdf.derive(session_secret.encode() + b"|" + server_key)
The server never stores session_secret (it stores only a keyed HMAC lookup hash). Compromising the database alone—or even the database plus the server key—yields unreadable ciphertext without the user's cookie. Clicking Delete or letting the 24-hour TTL expire crypto-shreds any residual copies.
-
Strict per-request nonce CSP & zero statement-page trackers: Middleware mints a per-request cryptographic nonce (
script-src 'self' 'nonce-<random>' 'strict-dynamic',connect-src 'self',object-src 'none',frame-ancestors 'none'). Zero third-party analytics SDKs, session replay scripts, or ad tags execute on upload or review pages; product telemetry goes through a first-party relay (/api/t) enforcing allow-listed enum schemas and stripping client IPs.
Closing & Transparent Disclosure
In financial document processing, deterministic accounting invariants (Decimal math + dual-chain running balance checks) paired with a narrow, auditable security boundary beat "98% accurate" heuristics every time.
Full disclosure: I built DocuBridge (an independent web tool at docubridge.cc, distinct from unrelated enterprise software sharing that name) using this exact stack. You can inspect the workflow on a built-in synthetic statement or review our plain-English security model here:
- Balance-checked PDF-to-Excel workflow: https://docubridge.cc/reconcile-bank-statement-in-excel
- Privacy, retention, and security architecture: https://docubridge.cc/security
Current boundaries (stated plainly): DocuBridge currently supports single-account US checking and savings statements in USD only (no credit cards or non-US currencies), digital PDFs up to 15 pages (4 MB), and clear scanned PDFs up to 5 pages via in-memory local OCR. Functional access is enabled in the US and South Korea with processing in the United States, and an independent third-party security assessment has not yet been completed (disclosed directly on /security).
If you have wrestled with messy bank PDFs—or spotted an edge case in dual-chain balance tracking—let's compare notes in the comments.
來源:DEV Community · dev.to