惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

L
LangChain Blog
Recent Announcements
Recent Announcements
GbyAI
GbyAI
H
Hackread – Cybersecurity News, Data Breaches, AI and More
Microsoft Azure Blog
Microsoft Azure Blog
N
Netflix TechBlog - Medium
人人都是产品经理
人人都是产品经理
MongoDB | Blog
MongoDB | Blog
D
DataBreaches.Net
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
WordPress大学
WordPress大学
U
Unit 42
腾讯CDC
D
Docker
The GitHub Blog
The GitHub Blog
阮一峰的网络日志
阮一峰的网络日志
Vercel News
Vercel News
I
InfoQ
Jina AI
Jina AI
爱范儿
爱范儿
宝玉的分享
宝玉的分享
博客园 - Franky
G
Google Developers Blog
P
Proofpoint News Feed

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
Python Invoice Generator: Automated PDF Billing With Paym...
Brad · 2026-05-14 · via DEV Community

Brad

Python Invoice Generator: Automated PDF Billing With Payment Reminders

Late invoices cause late payments. I automated my entire billing system with 150 lines of Python.

PDF Invoice Generator

from reportlab.lib import colors
from reportlab.lib.pagesizes import letter
from reportlab.platypus import SimpleDocTemplate, Table, TableStyle, Paragraph
from reportlab.lib.styles import getSampleStyleSheet
from datetime import datetime, timedelta

def create_invoice(client_name, client_email, services, invoice_num):
    filename = f"invoice_{invoice_num}.pdf"
    doc = SimpleDocTemplate(filename, pagesize=letter)
    styles = getSampleStyleSheet()
    elements = []

    elements.append(Paragraph(f"INVOICE #{invoice_num}", styles['Title']))
    elements.append(Paragraph(f"Date: {datetime.now().strftime('%B %d, %Y')}", styles['Normal']))
    elements.append(Paragraph(f"Due: {(datetime.now() + timedelta(days=30)).strftime('%B %d, %Y')}", styles['Normal']))
    elements.append(Paragraph(f"Bill To: {client_name} ({client_email})", styles['Normal']))

    rows = [['Description', 'Qty', 'Rate', 'Amount']]
    total = 0
    for s in services:
        amount = s['qty'] * s['rate']
        total += amount
        rows.append([s['desc'], str(s['qty']), f"${s['rate']:.2f}", f"${amount:.2f}"])
    rows.append(['', '', 'TOTAL', f"${total:.2f}"])

    table = Table(rows, colWidths=[250, 50, 100, 100])
    table.setStyle(TableStyle([
        ('BACKGROUND', (0, 0), (-1, 0), colors.darkblue),
        ('TEXTCOLOR', (0, 0), (-1, 0), colors.white),
        ('GRID', (0, 0), (-1, -1), 1, colors.black),
        ('FONTNAME', (0, -1), (-1, -1), 'Helvetica-Bold'),
    ]))
    elements.append(table)
    doc.build(elements)
    return filename, total

Enter fullscreen mode Exit fullscreen mode

Send Invoice by Email

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email import encoders

def email_invoice(invoice_file, client_email, client_name, total, due):
    msg = MIMEMultipart()
    msg['From'] = 'you@gmail.com'
    msg['To'] = client_email
    msg['Subject'] = f"Invoice - ${total:.2f} due {due}"
    msg.attach(MIMEText(f"Hi {client_name}, please find your invoice attached.", 'plain'))

    with open(invoice_file, 'rb') as f:
        part = MIMEBase('application', 'octet-stream')
        part.set_payload(f.read())
        encoders.encode_base64(part)
        part.add_header('Content-Disposition', f'attachment; filename={invoice_file}')
        msg.attach(part)

    with smtplib.SMTP('smtp.gmail.com', 587) as smtp:
        smtp.starttls()
        smtp.login('you@gmail.com', 'app-password')
        smtp.send_message(msg)

Enter fullscreen mode Exit fullscreen mode

Automated Payment Reminders

from datetime import datetime, timedelta
import sqlite3

def run_reminders():
    conn = sqlite3.connect('invoices.db')
    c = conn.cursor()

    # 3 days before due
    soon = (datetime.now() + timedelta(days=3)).strftime('%Y-%m-%d')
    c.execute('SELECT * FROM invoices WHERE due_date = ? AND paid = 0 AND r1_sent = 0', (soon,))
    for inv in c.fetchall():
        send_reminder(inv, 'upcoming')
        c.execute('UPDATE invoices SET r1_sent = 1 WHERE id = ?', (inv[0],))

    # 7 days overdue
    overdue = (datetime.now() - timedelta(days=7)).strftime('%Y-%m-%d')
    c.execute('SELECT * FROM invoices WHERE due_date < ? AND paid = 0 AND r2_sent = 0', (overdue,))
    for inv in c.fetchall():
        send_reminder(inv, 'overdue')
        c.execute('UPDATE invoices SET r2_sent = 1 WHERE id = ?', (inv[0],))
    conn.commit()

Enter fullscreen mode Exit fullscreen mode

Schedule

0 8 * * * /usr/bin/python3 invoice_reminders.py

Enter fullscreen mode Exit fullscreen mode

Result: Went from 4 hours/week on billing to 20 minutes.

The complete version with Stripe/PayPal integration, expense tracking, and profit/loss reports is in the toolkit below.


Get 50+ Python automation scripts for $9: Python Business Automation Toolkit