<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[Matthurindo Notes]]></title><description><![CDATA[Matthurindo Notes]]></description><link>https://matthurindo.hashnode.dev</link><generator>RSS for Node</generator><lastBuildDate>Sat, 05 Dec 2026 00:50:08 GMT</lastBuildDate><atom:link href="https://matthurindo.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Turn a CSV into printable invoices with Python's standard library]]></title><description><![CDATA[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…]]></description><link>https://matthurindo.hashnode.dev/turn-a-csv-into-printable-invoices-with-python-s-standard-library</link><guid isPermaLink="true">https://matthurindo.hashnode.dev/turn-a-csv-into-printable-invoices-with-python-s-standard-library</guid><dc:creator><![CDATA[Matthurindo]]></dc:creator><pubDate>Sun, 29 Nov 2026 10:33:22 GMT</pubDate><content:encoded><![CDATA[<p>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.</p>
<h2>The input</h2>
<p>Save this as <code>example.csv</code> in UTF-8:</p>
<pre><code class="language-csv">invoice_number,client,description,qty,rate
INV-001,Example Co,Logo sketch,2,45.50
INV-001,Example Co,"Layout, &lt;draft&gt;",1,"1,200"
INV-002,Sample Shop,Copy editing,3,20
</code></pre>
<h2>The script</h2>
<p>Save as <code>make_invoices.py</code>:</p>
<pre><code class="language-python">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"&lt;tr&gt;&lt;td&gt;{html.escape(r['description'])}&lt;/td&gt;"
            f"&lt;td&gt;{html.escape(r['qty'])}&lt;/td&gt;&lt;td&gt;{amount:,.2f}&lt;/td&gt;&lt;/tr&gt;"
        )
    return f"""&lt;!doctype html&gt;&lt;meta charset="utf-8"&gt;&lt;title&gt;{html.escape(number)}&lt;/title&gt;
&lt;style&gt;@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}}&lt;/style&gt;
&lt;h1&gt;Invoice {html.escape(number)}&lt;/h1&gt;
&lt;p&gt;Bill to: {html.escape(rows[0]['client'])}&lt;/p&gt;
&lt;table&gt;&lt;tr&gt;&lt;th&gt;Description&lt;/th&gt;&lt;th&gt;Qty&lt;/th&gt;&lt;th&gt;Amount&lt;/th&gt;&lt;/tr&gt;{''.join(lines)}&lt;/table&gt;
&lt;h2&gt;Total: {total:,.2f}&lt;/h2&gt;"""


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])
</code></pre>
<p>Run it:</p>
<pre><code class="language-bash">python3 make_invoices.py example.csv out
</code></pre>
<p>Open <code>out/INV-001.html</code> and use your browser's print dialog to save a PDF. Its total is 1,291.00.</p>
<h2>Four details worth keeping</h2>
<ol>
<li><strong><code>utf-8-sig</code></strong> reads CSV files with or without the byte-order mark some spreadsheet apps add.</li>
<li><strong><code>Decimal</code></strong>, not floating point, keeps money rounding predictable.</li>
<li><strong><code>html.escape</code></strong> stops text such as <code>&lt;draft&gt;</code> in a spreadsheet cell from being treated as HTML.</li>
<li><strong>File names</strong> are cleaned, so <code>INV/01</code> and <code>INV:01</code> would both become <code>INV_01</code>. The second gets <code>INV_01_2.html</code> instead of overwriting the first. Rows with a blank invoice number are skipped with a message.</li>
</ol>
<h2>What it does not do</h2>
<ul>
<li>Number cells with <code>$</code> or <code>฿</code> stop the script. Remove symbols first.</li>
<li>Files saved in a non-UTF-8 encoding fail to open.</li>
<li>There is no tax, discount, date, currency or payment section.</li>
<li>It is a starting point. Check what a legal invoice needs where you work.</li>
</ul>
<hr />
<p><em>Disclosure: this article and its code were prepared with AI help. I sell a related paid tool, the <a href="https://brushzephyr.gumroad.com/l/offline-invoice-expense-kit">Offline Freelancer Invoice &amp; Expense Kit</a> ($9). Its app was tested in Chrome on macOS, does not convert currencies and does not sync between devices.</em></p>
]]></content:encoded></item></channel></rss>