AI · Automation · Backend

    Turning PDFs and Invoices into Structured JSON with LLMs

    How Anup Ojha builds document-to-JSON extraction pipelines with LLMs: schemas, validation, confidence checks and integration with accounting tools like Tally.

    Anup Ojha

    /4 min read

    A lot of business work is still one person reading a PDF and typing its numbers into another system. Invoices, bank statements, purchase orders, receipts. Language models can now do most of that reading. Whether the output is something an accountant will actually trust depends almost entirely on what you build around the model.

    At Perimattic I worked on Arhtattva, a system that takes accounting documents (PDFs, images, Word files) and turns them into structured JSON, and from there into Tally entries a user can post with a single click. What follows is what I learned building it, including a few things I'd do differently next time.

    Why accounting documents suit this

    Before my MCA at VESIT I did a B.Com in Computer Application in Nagpur, so I came into this project already knowing what a voucher is and why a trial balance has to tally. That helped me more than any prompt trick did.

    Accounting documents follow rules. Line items add up to a subtotal, tax follows a rate, and the same vendor shouldn't send the same invoice number twice. Rules are things you can check in code. That makes this a much safer place to put an LLM than, say, open-ended summarisation, where there's no simple way to know if the output is right.

    Start with the schema

    The most important file in a project like this is the schema: exactly which fields you need, what type each one is, and which ones are required. I write it in Pydantic so it doubles as validation code. A simplified version looks something like this:

    from datetime import date
    from decimal import Decimal
    from pydantic import BaseModel, Field
    
    class LineItem(BaseModel):
        description: str
        quantity: Decimal
        rate: Decimal
        amount: Decimal
    
    class Invoice(BaseModel):
        vendor_name: str
        vendor_gstin: str | None = None
        invoice_number: str
        invoice_date: date
        line_items: list[LineItem]
        subtotal: Decimal
        tax_total: Decimal
        grand_total: Decimal
        source_page: int = Field(description="Page the totals were read from")

    Two small things in there are deliberate. Money is Decimal, not float, because rounding errors in an accounting system are the kind of bug nobody forgives. And source_page is there so every number can be traced back to where it came from.

    The model's job is to fill this schema and nothing else. No "insights", no extra fields it decided might be useful. When a client asks for a new field, it goes into the schema first and the prompt second.

    Get clean input before anything else

    Native PDFs are the easy case. I pull the text layer with positions so tables survive, rather than reading the page as one long string. Scans and phone photos either go through OCR first or straight to a vision-capable model, depending on how bad they are. And phone photos can be very bad: tilted, shadowed, folded, half the receipt out of frame.

    For multi-page documents I keep page numbers attached to everything. It costs nothing at this stage and it's painful to add later.

    Ask for structured output

    I use structured output (JSON mode or function calling) so the response is always valid JSON that matches the schema. Parsing a free-text answer with regex works right up until the day it quietly doesn't.

    The prompt includes the field definitions and a couple of short examples of the tricky cases: dates written as DD/MM versus MM/DD, totals that already include tax, a vendor name that appears in both the header and the stamp. If I were starting again, I'd collect those tricky examples before writing the first prompt, not after seeing the first batch of wrong results.

    Never trust the extraction

    Every extraction goes through checks before it gets anywhere near the accounting system:

    • types and required fields, which the schema handles for free
    • business rules, like line items summing to the subtotal, tax matching the rate, dates being plausible
    • duplicates, so the same invoice number from the same vendor can't be entered twice

    Anything that fails a rule is flagged for a person, with the reason shown right next to the document. In practice this means people review a small share of documents instead of typing all of them. That's the trade I explain to clients upfront. I don't promise full automation. I promise that the routine stuff goes through on its own and the odd stuff lands in front of someone with enough context to fix it in seconds.

    Push it into Tally

    Extracted data is only useful once it lands where the work happens. For Arhtattva that meant generating Tally XML and using TDL so one click creates the entry. No re-typing, no copy-paste between windows.

    The same pipeline also generated and merged Balance Sheet, Trial Balance and P&L reports in under 10 seconds, without Tally needing to be on the client side. For the people using it, that meant getting their reports without opening Tally at all, which is a bigger deal for a small accounting team than it sounds.

    What I tell teams thinking about this

    Don't aim for a hundred percent automation. Aim for a pipeline where routine documents go straight through, unusual ones go to a person, and every value can be traced back to its source page. That's achievable, and it's what actually saves hours.

    The extraction step has a lot in common with RAG, since both live or die on parsing. I've written about that in how I build production RAG pipelines. If your team spends hours on document entry, read about my agentic AI and automation work or get in touch.

    Frequently asked questions

    01Can an LLM extract data from invoices accurately?

    Yes, for most routine invoices, as long as the pipeline around it is built properly. That means clean input, a strict schema, structured output and validation checks on every result. Documents that fail a check, such as totals that don't add up, should go to a person instead of straight into your books.

    02How do you convert a PDF to structured JSON with an LLM?

    Define the output schema first, for example as a Pydantic model with types and required fields. Extract the PDF's text with layout preserved, or use OCR or a vision model for scans, then ask the model for structured output that matches the schema. Validate the result against the schema and your business rules before using it.

    03Can extracted invoice data be pushed into Tally automatically?

    It can. On the Arhtattva project I generated Tally XML and used TDL so a validated extraction becomes a Tally entry with one click. The same pipeline also produced Balance Sheet, Trial Balance and P&L reports in under 10 seconds without needing Tally on the client side.

    04Do I still need human review for AI document extraction?

    For accounting data, yes, but only for the documents that fail a check. Validation rules for totals, tax, dates and duplicates catch most problems and flag them with a reason. That way people review a small share of documents instead of typing every one.