Skip to main content

Turn a CSV into printable invoices with Python's standard library

Updated 3 min readMarkdown

If your jobs live in a spreadsheet, a short script can turn each invoice number into a page you print from the browser. No packages to install beyond Python 3.

The input

Save this as example.csv in UTF-8:

invoice_number,client,description,qty,rate
INV-001,Example Co,Logo sketch,2,45.50
INV-001,Example Co,"Layout, <draft>",1,"1,200"
INV-002,Sample Shop,Copy editing,3,20

The script

Save as make_invoices.py:

import csv
import html
import sys
from collections import defaultdict
from decimal import Decimal, ROUND_HALF_UP
from pathlib import Path

CENT = Decimal("0.01")


def money(text):
    # Accepts "1200" or "1,200.50"; symbols such as $ or ฿ raise an error on purpose.
    return Decimal(text.strip().replace(",", ""))


def load(path):
    invoices = defaultdict(list)
    with open(path, encoding="utf-8-sig", newline="") as f:
        reader = csv.DictReader(f)
        for row in reader:
            number = (row["invoice_number"] or "").strip()
            if not number:
                print(f"skipped line {reader.line_num}: blank invoice_number", file=sys.stderr)
                continue
            invoices[number].append(row)
    return invoices


def render(number, rows):
    total = Decimal("0")
    lines = []
    for r in rows:
        amount = (money(r["qty"]) * money(r["rate"])).quantize(CENT, ROUND_HALF_UP)
        total += amount
        lines.append(
            f"<tr><td>{html.escape(r['description'])}</td>"
            f"<td>{html.escape(r['qty'])}</td><td>{amount:,.2f}</td></tr>"
        )
    return f"""<!doctype html><meta charset="utf-8"><title>{html.escape(number)}</title>
<style>@page{{size:A4;margin:18mm}} body{{font-family:sans-serif}}
table{{width:100%;border-collapse:collapse}} td,th{{border-bottom:1px solid #ccc;padding:6px;text-align:left}}</style>
<h1>Invoice {html.escape(number)}</h1>
<p>Bill to: {html.escape(rows[0]['client'])}</p>
<table><tr><th>Description</th><th>Qty</th><th>Amount</th></tr>{''.join(lines)}</table>
<h2>Total: {total:,.2f}</h2>"""


def main(source, out_dir):
    out = Path(out_dir)
    out.mkdir(parents=True, exist_ok=True)
    used = set()
    for number, rows in load(source).items():
        stem = "".join(c if c.isalnum() or c in "-_" else "_" for c in number)
        name, copy = stem, 1
        # Compare without case: many computers treat "a.html" and "A.html" as one file.
        while name.casefold() in used:
            copy += 1
            name = f"{stem}_{copy}"
        used.add(name.casefold())
        (out / f"{name}.html").write_text(render(number, rows), encoding="utf-8")
        print(f"wrote {name}.html (invoice {number})")


if __name__ == "__main__":
    if len(sys.argv) != 3:
        sys.exit("usage: python3 make_invoices.py input.csv output_folder")
    main(sys.argv[1], sys.argv[2])

Run it:

python3 make_invoices.py example.csv out

Open out/INV-001.html and use your browser's print dialog to save a PDF. Its total is 1,291.00.

Four details worth keeping

  1. utf-8-sig reads CSV files with or without the byte-order mark some spreadsheet apps add.
  2. Decimal, not floating point, keeps money rounding predictable.
  3. html.escape stops text such as <draft> in a spreadsheet cell from being treated as HTML.
  4. File names are cleaned, so INV/01 and INV:01 would both become INV_01. The second gets INV_01_2.html instead of overwriting the first. Rows with a blank invoice number are skipped with a message.

What it does not do

  • Number cells with $ or ฿ stop the script. Remove symbols first.
  • Files saved in a non-UTF-8 encoding fail to open.
  • There is no tax, discount, date, currency or payment section.
  • It is a starting point. Check what a legal invoice needs where you work.

Disclosure: this article and its code were prepared with AI help. I sell a related paid tool, the Offline Freelancer Invoice & Expense Kit ($9). Its app was tested in Chrome on macOS, does not convert currencies and does not sync between devices.

No comments yet. Be the first to comment.