惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

T
Tenable Blog
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
V
Vulnerabilities – Threatpost
G
GRAHAM CLULEY
Simon Willison's Weblog
Simon Willison's Weblog
C
CXSECURITY Database RSS Feed - CXSecurity.com
P
Privacy International News Feed
H
Heimdal Security Blog
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
S
Secure Thoughts
MyScale Blog
MyScale Blog
C
Cyber Attacks, Cyber Crime and Cyber Security
V
Visual Studio Blog
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
L
LINUX DO - 最新话题
D
Darknet – Hacking Tools, Hacker News & Cyber Security
The Cloudflare Blog
美团技术团队
Recorded Future
Recorded Future
T
Tailwind CSS Blog
Latest news
Latest news
Security Archives - TechRepublic
Security Archives - TechRepublic
Security Latest
Security Latest
Know Your Adversary
Know Your Adversary
Cloudbric
Cloudbric
Schneier on Security
Schneier on Security
I
Intezer
L
LINUX DO - 热门话题
P
Palo Alto Networks Blog
云风的 BLOG
云风的 BLOG
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
Vercel News
Vercel News
Attack and Defense Labs
Attack and Defense Labs
人人都是产品经理
人人都是产品经理
L
LangChain Blog
爱范儿
爱范儿
博客园 - 三生石上(FineUI控件)
博客园 - 叶小钗
L
Lohrmann on Cybersecurity
S
SegmentFault 最新的问题
W
WeLiveSecurity
C
Cybersecurity and Infrastructure Security Agency CISA
S
Securelist
SecWiki News
SecWiki News
V2EX - 技术
V2EX - 技术
IT之家
IT之家
Cyberwarzone
Cyberwarzone
F
Full Disclosure
Spread Privacy
Spread Privacy
阮一峰的网络日志
阮一峰的网络日志

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Build a GST Invoice Parser in 60 Lines of Python
Archit Mittal · 2026-06-01 · via DEV Community

If you handle Indian invoices for any business, you know the month-end ritual: thirty vendor PDFs arrive in your inbox, and someone has to type GSTIN, invoice number, taxable value, and the CGST/SGST/IGST split into a spreadsheet so the accountant can reconcile with GSTR-2A. One typo means a mismatched input tax credit, and that means a tense email at 9pm.

I built a parser that reads any GST-compliant PDF invoice and writes the numbers straight into a CSV. Sixty lines, one external dependency, no paid OCR service, no API calls.

Here's the full code, then I'll walk through why each piece exists.

The Code

import re
import csv
import sys
from pathlib import Path
import pdfplumber

GSTIN_RE = re.compile(r"\b(\d{2}[A-Z]{5}\d{4}[A-Z]\d[A-Z][A-Z\d])\b")
INVOICE_RE = re.compile(r"Invoice\s*(?:No\.?|Number|#)\s*[:\-]?\s*([A-Z0-9\-/]+)", re.I)
DATE_RE = re.compile(r"(\d{1,2}[/\-.]\d{1,2}[/\-.]\d{2,4})")
AMOUNT_RE = re.compile(r"(?:Total|Grand\s*Total)[^\d]{0,20}([\d,]+\.\d{2})", re.I)
TAXABLE_RE = re.compile(r"Taxable\s*(?:Value|Amount)[^\d]{0,20}([\d,]+\.\d{2})", re.I)
CGST_RE = re.compile(r"\bCGST[^\d]{0,30}([\d,]+\.\d{2})", re.I)
SGST_RE = re.compile(r"\bSGST[^\d]{0,30}([\d,]+\.\d{2})", re.I)
IGST_RE = re.compile(r"\bIGST[^\d]{0,30}([\d,]+\.\d{2})", re.I)

def clean(amount):
    if not amount:
        return 0.0
    return float(amount.replace(",", ""))

def first(pattern, text, default=""):
    m = pattern.search(text)
    return m.group(1).strip() if m else default

def parse_invoice(pdf_path):
    with pdfplumber.open(pdf_path) as pdf:
        text = "\n".join(p.extract_text() or "" for p in pdf.pages)
    gstins = GSTIN_RE.findall(text)
    return {
        "file": pdf_path.name,
        "vendor_gstin": gstins[0] if gstins else "",
        "buyer_gstin": gstins[1] if len(gstins) > 1 else "",
        "invoice_no": first(INVOICE_RE, text),
        "date": first(DATE_RE, text),
        "taxable": clean(first(TAXABLE_RE, text)),
        "cgst": clean(first(CGST_RE, text)),
        "sgst": clean(first(SGST_RE, text)),
        "igst": clean(first(IGST_RE, text)),
        "total": clean(first(AMOUNT_RE, text)),
    }

def main(folder, out_csv="invoices.csv"):
    rows = [parse_invoice(p) for p in Path(folder).glob("*.pdf")]
    if not rows:
        print("No PDFs found.")
        return
    with open(out_csv, "w", newline="") as f:
        writer = csv.DictWriter(f, fieldnames=rows[0].keys())
        writer.writeheader()
        writer.writerows(rows)
    print(f"Parsed {len(rows)} invoices -> {out_csv}")

if __name__ == "__main__":
    main(sys.argv[1], sys.argv[2] if len(sys.argv) > 2 else "invoices.csv")

Enter fullscreen mode Exit fullscreen mode

Install and run:

pip install pdfplumber
python parse_gst.py ./invoices/ output.csv

Enter fullscreen mode Exit fullscreen mode

How It Works

The GSTIN regex. A GSTIN is exactly 15 characters in a strict format: 2-digit state code, 5 letters (the entity's PAN prefix), 4 digits (PAN), 1 letter (PAN suffix), 1 digit (entity number within the state), 1 letter (Z by default), and 1 alphanumeric checksum. The pattern matches that exact shape and rejects everything else, so you won't accidentally pick up phone numbers, PIN codes, or random alphanumeric strings.

A typical invoice carries two GSTINs: the vendor's at the top, usually in the header block, and the buyer's in the bill-to section. The reading order pdfplumber returns is consistent for nearly every template I've tested, so taking the first two matches works in practice. If you want to be defensive, you can label each GSTIN by checking which one appears before the words "Bill To" in the extracted text.

The tax field regexes. Each tax field has the same structural pattern across templates: a label like CGST, then some whitespace or punctuation (@9%, Rs., INR, a colon, or a table cell separator), then the amount. The [^\d]{0,30} window lets the regex skip past anything non-numeric for up to 30 characters before grabbing the next amount. That window is wide enough to handle most table layouts but tight enough that it won't accidentally jump down to the next row's number.

The \b word boundary on CGST, SGST, and IGST matters more than it looks. Without it, you can match parts of compound labels and end up with the wrong number landing in the wrong column on every single invoice in the batch.

Why pdfplumber over PyPDF2 or pdfminer. pdfplumber preserves visual layout when extracting text, which means amounts in a totals box at the bottom of the page don't get scrambled with line items above them. PyPDF2 returns the same characters in document reading order, which sounds fine until you hit a multi-column invoice and CGST from row 3 ends up next to SGST from row 1. pdfplumber pays attention to coordinates, so structured fields stay structured.

Comma handling. Indian invoices write amounts as 1,23,456.00. Python's float() refuses to parse commas. The clean() helper strips them before casting, and returns 0.0 on missing matches rather than crashing — important when a single malformed PDF in a batch of thirty shouldn't kill the whole run.

What It Catches

Run it against a folder of 30 invoices and you get a CSV like:

file,vendor_gstin,buyer_gstin,invoice_no,date,taxable,cgst,sgst,igst,total
inv_001.pdf,27ABCDE1234F1Z5,29XYZAB5678G2Z9,INV-2025-001,15/05/2025,10000.00,900.0,900.0,0.0,11800.00
inv_002.pdf,27ABCDE1234F1Z5,06PQRST9876H3Z1,INV-2025-002,16/05/2025,25000.00,0.0,0.0,4500.0,29500.00

Enter fullscreen mode Exit fullscreen mode

Pipe that into your GSTR-2A reconciliation sheet, sort by vendor_gstin, and you're done in five minutes instead of two hours.

What It Doesn't Catch (Yet)

Scanned PDFs are invisible to pdfplumber — it reads embedded text only. For scanned invoices, add a pytesseract OCR step before the text extraction; that's another ten lines and a brew install tesseract. Non-standard layouts (vendors who label GST as "Tax Amount" or split CGST across two rows) will defeat the regex. The fix is to print the extracted text for that file once, adjust the pattern, and never touch it again. Reverse-charge entries return the right total but with the tax direction flipped; if you process reverse-charge invoices regularly, add a flag check for "Reverse Charge: Yes" in the text.

Running It On Schedule

Drop the script in a cron job that runs nightly:

0 22 * * * cd /home/me/invoices && python parse_gst.py ./incoming output.csv

Enter fullscreen mode Exit fullscreen mode

Now your accountant opens a fresh, accurate CSV every morning at 10am and the manual typing step disappears from the workflow.

Why I Like This Pattern

Sixty lines of regex over PDF text beats a ₹2000/month invoice OCR SaaS for 95% of real-world Indian invoices, and the 5% you can fix by reading one error message and tweaking one pattern. The entire script fits in your head, so when something breaks, you know exactly where to look. No vendor lock-in, no rate limits, no quarterly price hikes. Just Python and a regex book.

Build the boring thing yourself. Charge yourself ₹0 a month. Use the saved money for better chai.


Follow me on Twitter @automate_archit for daily AI automation tips.