Dev.to WebDev 🛠 Dev 👁 0 📖 5 min read

How I Built a Zero-Dependency Offline PDF Invoice Generator in 1 Single HTML File (@media print + QR + CSV)

Every freelance developer eventually hits the same annoyance: you finish a $300 client project, go to send an invoice, and your "free" invoicing SaaS tells you you've hit the 3-client limit — upgrade for $19/month. An i

Every freelance developer eventually hits the same annoyance: you finish a $300 client project, go to send an invoice, and your "free" invoicing SaaS tells you you've hit the 3-client limit — upgrade for $19/month.

An invoice is literally a styled HTML table that prints cleanly to A4 PDF. It does not need a cloud database, OAuth login, or a monthly subscription.

Here is the exact zero-dependency architecture I used to build a single-file offline PDF invoice generator that opens straight from disk (file://), saves drafts in localStorage, exports CSV for bookkeeping, and prints pixel-sharp A4 PDFs using native browser @media print.

1. The Secret to Crisp PDFs Without Puppeteer or jsPDF: @media print

Libraries like html2canvas + jsPDF rasterize text into blurry bitmaps and balloon file sizes to 5MB+. Instead, the browser's built-in print engine outputs real selectable vector text under 80KB when you lock three CSS rules:

@page {
  size: A4 portrait;
  margin: 14mm;
}

@media print {
  /* Hide buttons, sidebars, and edit controls */
  .no-print {
    display: none !important;
  }

  /* Preserve brand accent headers & badge backgrounds */
  * {
    -webkit-print-color-adjust: exact !important;
    print-color-adjust: exact !important;
  }

  /* Prevent line-item rows from splitting awkwardly across pages */
  tr, .totals-box {
    break-inside: avoid;
    page-break-inside: avoid;
  }

  /* Strip input borders so fields look like typeset text */
  input, textarea {
    border: none !important;
    background: transparent !important;
    box-shadow: none !important;
    resize: none;
  }
}

That single CSS block eliminates 90% of browser print glitches across Chrome, Edge, Safari, and Firefox.

2. Dynamic Line Items + Live Tax / Deposit Math in Vanilla JS

No React, no bundler, no npm install. One lightweight state array renders both the interactive editor and the final printable sheet:

<table id="items-table">
  <thead>
    <tr>
      <th>Description</th>
      <th>Qty</th>
      <th>Rate ($)</th>
      <th>Line Total</th>
      <th class="no-print"></th>
    </tr>
  </thead>
  <tbody id="items-body"></tbody>
</table>

<button class="no-print" onclick="addRow()">+ Add Item</button>
<button class="no-print" onclick="exportCSV()">Export CSV</button>
<button class="no-print" onclick="window.print()">Save PDF</button>

<div class="totals-box">
  <div>Subtotal: <strong id="subtotal">$0.00</strong></div>
  <div>50% Deposit Due Now: <strong id="deposit">$0.00</strong></div>
</div>

<script>
  const STORAGE_KEY = "offline_invoice_v1";
  let items = JSON.parse(localStorage.getItem(STORAGE_KEY) || "null") || [
    { desc: "Custom Landing Page Build (HTML/CSS/JS)", qty: 1, rate: 350 },
    { desc: "Automated Lead Capture Webhook Setup", qty: 1, rate: 120 },
  ];

  const fmt = (n) => "$" + Number(n || 0).toLocaleString("en-US", { minimumFractionDigits: 2, maximumFractionDigits: 2 });

  function saveAndRender() {
    localStorage.setItem(STORAGE_KEY, JSON.stringify(items));
    const tbody = document.getElementById("items-body");
    tbody.innerHTML = "";

    let subtotal = 0;
    items.forEach((item, idx) => {
      const lineTotal = (Number(item.qty) || 0) * (Number(item.rate) || 0);
      subtotal += lineTotal;

      const tr = document.createElement("tr");
      tr.innerHTML = `
        <td><input value="${item.desc.replace(/"/g, "&quot;")}" oninput="updateItem(${idx}, 'desc', this.value)"></td>
        <td><input type="number" min="0" step="0.5" value="${item.qty}" oninput="updateItem(${idx}, 'qty', this.value)"></td>
        <td><input type="number" min="0" step="1" value="${item.rate}" oninput="updateItem(${idx}, 'rate', this.value)"></td>
        <td><strong>${fmt(lineTotal)}</strong></td>
        <td class="no-print"><button onclick="removeRow(${idx})">×</button></td>
      `;
      tbody.appendChild(tr);
    });

    document.getElementById("subtotal").textContent = fmt(subtotal);
    document.getElementById("deposit").textContent = fmt(subtotal * 0.5);
  }

  function updateItem(idx, key, val) {
    items[idx][key] = key === "desc" ? val : parseFloat(val) || 0;
    saveAndRender();
  }

  function addRow() {
    items.push({ desc: "New Service Line Item", qty: 1, rate: 0 });
    saveAndRender();
  }

  function removeRow(idx) {
    items.splice(idx, 1);
    saveAndRender();
  }

  function exportCSV() {
    const rows = [["Description", "Qty", "Rate", "LineTotal"]];
    items.forEach((i) => rows.push([`"${i.desc.replace(/"/g, '""')}"`, i.qty, i.rate, (i.qty * i.rate).toFixed(2)]));
    const blob = new Blob([rows.map((r) => r.join(",")).join("\n")], { type: "text/csv" });
    const a = document.createElement("a");
    a.href = URL.createObjectURL(blob);
    a.download = `invoice_${new Date().toISOString().slice(0, 10)}.csv`;
    a.click();
  }

  saveAndRender();
</script>

3. Adding Offline Payment QR Codes (Bank / PayPal / Crypto)

Because everything runs locally, you can embed a client-ready payment QR directly inside the printable footer using a simple FileReader data URL (no image upload to any third-party server):

<input class="no-print" type="file" accept="image/*" onchange="loadQR(this)">
<img id="qr-preview" style="max-width:110px; display:none;" alt="Payment QR">

<script>
  function loadQR(input) {
    const file = input.files?.[0];
    if (!file) return;
    const reader = new FileReader();
    reader.onload = () => {
      const img = document.getElementById("qr-preview");
      img.src = reader.result;
      img.style.display = "block";
      localStorage.setItem("invoice_qr_img", reader.result);
    };
    reader.readAsDataURL(file);
  }
</script>

Once saved to localStorage, your payment QR appears automatically on every future invoice — 100% private, zero cloud tracking.

Why Single-File Local Tools Beat Monthly SaaS for Freelancers

Metric Typical Invoicing SaaS Single-File Local HTML
Monthly Cost $15 – $30/mo $0 forever
Load Time 1.5 – 3.5s + login < 30ms offline
Client Data Privacy Stored on third-party servers 100% local on your machine
PDF Quality Variable Native vector A4 (< 80KB)

Want the Polished Production Version (Multi-Currency, Client Book, Tax/Discount, QR, Themes, History)?

If you want to customize the snippet above yourself, everything you need is right in this article.

If you'd rather skip the styling/edge-case work and grab the complete, battle-tested production version (InvoiceForge Pro 2027 — multi-currency USD/EUR/GBP/VND, saved client profiles, auto invoice numbering, tax/discount/deposit toggles, embedded logo + payment QR, JSON backup & CSV ledger export, 100% offline):

What other bloated monthly SaaS tools have you replaced with a single local HTML or Python script? Drop your favorite below!

📰 Read the original article on Dev.to WebDev

Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.