Tech With Galvan
Back to Articles
AutomationMay 19, 2029 • 5 min read

Python Script to Create PDF Invoices in Bulk

Generate multiple PDF invoices in bulk with Python — from CSV/Excel data, with templates, GST support, and email sending. Free script included.

Galvan
Galvan

Founder & Creator

Introduction

Generating 50 invoices manually takes hours. A Python script can do it in seconds — read data from a CSV/Excel, generate PDF invoices, and even email them. This post gives you a complete, runnable script.

Setup

pip install fpdf pandas openpyxl

The input data (CSV)

Create invoices.csv:

invoice_number,client_name,client_email,client_address,description,qty,rate,gst_rate,due_days
INV-001,Acme Corp,[email protected],123 Main St Vadodara,Website Design (5 pages),1,25000,18,15
INV-001,Acme Corp,[email protected],123 Main St Vadodara,Mobile Optimization,1,5000,18,15
INV-001,Acme Corp,[email protected],123 Main St Vadodara,SEO Setup,1,3000,18,15
INV-002,StartupX,[email protected],456 Park Ave Ahmedabad,Logo Design,1,8000,18,15
INV-002,StartupX,[email protected],456 Park Ave Ahmedabad,Social Media Graphics (10),1,3000,18,15
INV-003,BlogCo,[email protected],789 Lake Rd Mumbai,Blog Post (1000 words),4,1500,18,15

Multiple rows with the same invoice number = multiple line items on one invoice.

The script

import pandas as pd
from fpdf import FPDF
from datetime import datetime, timedelta
import os

def generate_invoice_pdf(invoice_number, client_name, client_email, client_address, items, due_days=15):
    """Generate a single invoice PDF."""
    pdf = FPDF()
    pdf.add_page()
    pdf.set_font("Arial", "B", 16)
    pdf.cell(0, 10, "INVOICE", ln=True, align="C")
    
    pdf.set_font("Arial", "", 11)
    pdf.cell(0, 7, f"Invoice #: {invoice_number}", ln=True)
    pdf.cell(0, 7, f"Date: {datetime.now().strftime('%B %d, %Y')}", ln=True)
    due_date = (datetime.now() + timedelta(days=due_days)).strftime("%B %d, %Y")
    pdf.cell(0, 7, f"Due Date: {due_date}", ln=True)
    pdf.ln(3)
    
    pdf.cell(0, 7, f"Bill to: {client_name}", ln=True)
    pdf.cell(0, 7, f"Email: {client_email}", ln=True)
    pdf.cell(0, 7, f"Address: {client_address}", ln=True)
    pdf.ln(5)
    
    # Line items
    pdf.set_font("Arial", "B", 10)
    pdf.cell(80, 8, "Description", border=1)
    pdf.cell(20, 8, "Qty", border=1)
    pdf.cell(40, 8, "Rate", border=1)
    pdf.cell(20, 8, "GST%", border=1)
    pdf.cell(30, 8, "Amount", border=1, ln=True)
    
    pdf.set_font("Arial", "", 10)
    total = 0
    for item in items:
        amt = item["qty"] * item["rate"]
        gst = amt * item["gst_rate"] / 100
        pdf.cell(80, 8, item["desc"][:40], border=1)
        pdf.cell(20, 8, str(item["qty"]), border=1)
        pdf.cell(40, 8, f"Rs.{item['rate']:,}", border=1)
        pdf.cell(20, 8, f"{item['gst_rate']}%", border=1)
        pdf.cell(30, 8, f"Rs.{amt + gst:,.0f}", border=1, ln=True)
        total += amt + gst
    
    pdf.set_font("Arial", "B", 10)
    pdf.cell(160, 8, "Total:", border=1)
    pdf.cell(30, 8, f"Rs.{total:,.0f}", border=1, ln=True)
    
    pdf.ln(8)
    pdf.set_font("Arial", "", 9)
    pdf.cell(0, 6, "Payment: UPI (yourname@upi) or bank transfer", ln=True)
    pdf.cell(0, 6, "Late fee: 2% per month after due date", ln=True)
    pdf.cell(0, 6, "Thank you for your business!", ln=True)
    
    filename = f"invoices/{invoice_number}.pdf"
    os.makedirs("invoices", exist_ok=True)
    pdf.output(filename)
    return filename, total

def main():
    # Read CSV
    df = pd.read_csv("invoices.csv")
    
    # Group by invoice number
    invoices = {}
    for _, row in df.iterrows():
        inv_num = row["invoice_number"]
        if inv_num not in invoices:
            invoices[inv_num] = {
                "client_name": row["client_name"],
                "client_email": row["client_email"],
                "client_address": row["client_address"],
                "due_days": row["due_days"],
                "items": [],
            }
        invoices[inv_num]["items"].append({
            "desc": row["description"],
            "qty": row["qty"],
            "rate": row["rate"],
            "gst_rate": row["gst_rate"],
        })
    
    # Generate PDFs
    results = []
    for inv_num, data in invoices.items():
        filename, total = generate_invoice_pdf(
            inv_num, data["client_name"], data["client_email"],
            data["client_address"], data["items"], data["due_days"]
        )
        results.append({"invoice": inv_num, "client": data["client_name"], "total": total, "file": filename})
        print(f"Generated: {filename} (Rs. {total:,.0f})")
    
    # Summary
    print(f"\n=== Summary ===")
    print(f"Total invoices: {len(results)}")
    print(f"Total amount: Rs. {sum(r['total'] for r in results):,.0f}")
    
    # Save summary
    summary_df = pd.DataFrame(results)
    summary_df.to_csv("invoice_summary.csv", index=False)
    print("Summary saved to invoice_summary.csv")

if __name__ == "__main__":
    main()

Usage

python bulk_invoices.py

Output:

Generated: invoices/INV-001.pdf (Rs. 39,780)
Generated: invoices/INV-002.pdf (Rs. 13,020)
Generated: invoices/INV-003.pdf (Rs. 7,080)

=== Summary ===
Total invoices: 3
Total amount: Rs. 59,880
Summary saved to invoice_summary.csv

Step 2: Email invoices automatically

import resend, os, base64

resend.api_key = os.environ["RESEND_API_KEY"]

def email_invoices(results):
    for r in results:
        with open(r["file"], "rb") as f:
            pdf_data = base64.b64encode(f.read()).decode()
        
        resend.Emails.send({
            "from": "Billing <[email protected]>",
            "to": [get_client_email(r["client"])],
            "subject": f"Invoice {r['invoice']} — Rs. {r['total']:,.0f}",
            "html": f"<p>Hi, please find attached invoice {r['invoice']}.</p>",
            "attachments": [{"filename": r["file"].split('/')[-1], "content": pdf_data}],
        })
        print(f"Email sent: {r['invoice']} to {r['client']}")

Step 3: Schedule with cron

# Generate and send invoices on the 1st of every month
0 9 1 * * cd /path/to/project && python bulk_invoices.py && python email_invoices.py

Excel input (alternative to CSV)

# Read from Excel instead of CSV
df = pd.read_excel("invoices.xlsx", sheet_name="Invoices")
# Same code works — pandas handles both CSV and Excel

Common mistakes

  • Not grouping line items — multiple rows with the same invoice number should be one invoice. The script handles this.
  • Wrong GST calculation — GST is calculated on taxable value, not on total. The script handles this.
  • No invoice numbering — use sequential numbers. The script uses the invoice number from the CSV.
  • Not saving a summary — always save a summary CSV for your records.
  • Hardcoding paths — use relative paths or environment variables.

Key Concepts

  • Bulk generation = creating multiple invoices from data
  • Grouping = combining multiple line items into one invoice
  • GST calculation = tax on taxable value (not total)
  • PDF generation = creating printable documents
  • Email automation = sending invoices automatically

What to Try Next

FAQ

Can I use this for GST invoices?

Yes — the script includes GST calculation. For full GST compliance (SAC codes, CGST/SGST/IGST breakdown), use the GST Invoice Generator post.

How do I handle different currencies?

Add a “currency” column to your CSV and format accordingly. For international clients, charge in USD/EUR and convert at the current exchange rate.

Can I customize the invoice design?

Yes — FPDF supports custom fonts, colors, logos, and layouts. Modify the generate_invoice_pdf function. For more advanced designs, use reportlab or weasyprint (HTML to PDF).

How do I send invoices to multiple clients at once?

The script generates all invoices first, then emails them. For large batches (100+), consider using a queue (Celery, RQ) to avoid rate limits. See Email Automation with Resend.