# HTML-based Invoice Generator
import io
import os
import zipfile
import tempfile
import shutil
from typing import Dict, List
import base64
import subprocess
import sys
import pandas as pd
import streamlit as st
from num2words import num2words
# Try to import Playwright for PDF conversion
PLAYWRIGHT_AVAILABLE = False
try:
from playwright.sync_api import sync_playwright
PLAYWRIGHT_AVAILABLE = True
except ImportError:
pass
# Install Playwright browsers at runtime (disabled by default for hosted envs)
_playwright_flag = os.path.join(tempfile.gettempdir(), 'playwright_installed')
_allow_runtime_install = os.environ.get('PLAYWRIGHT_RUNTIME_INSTALL') == '1'
if PLAYWRIGHT_AVAILABLE and _allow_runtime_install and not os.path.exists(_playwright_flag):
try:
cmd = [sys.executable, "-m", "playwright", "install", "chromium"]
subprocess.run(cmd, check=True)
with open(_playwright_flag, 'w') as f:
f.write('installed')
print("✅ Playwright browsers installed!")
except Exception as e:
print(f"⚠️ Failed to install Playwright browsers: {e}")
else:
if not _allow_runtime_install:
print("ℹ️ Skipping runtime Playwright install (build-time install expected).")
# Try to import PyPDF for PDF page extraction
PYPDF_AVAILABLE = False
try:
from pypdf import PdfReader, PdfWriter
PYPDF_AVAILABLE = True
except ImportError:
pass
# -------------------------
# Utility helpers
# -------------------------
def safe_str(x):
if pd.isna(x):
return ""
return str(x)
def format_amount(x):
"""Format amount as Indian currency format"""
try:
num = float(x)
if num == 0:
return "0.00"
return f"{num:,.2f}"
except Exception:
return "0.00"
def to_words(value):
"""Convert number to words"""
try:
num = float(value)
if num == 0:
return "Zero Rupees Only"
if num.is_integer():
num = int(num)
return num2words(num, to="cardinal", lang="en").title() + " Only"
except Exception:
return "Zero Rupees Only"
# -------------------------
# HTML Template Processing
# -------------------------
def fill_html_template(template_path: str, invoice_data: dict, output_path: str):
"""Fill HTML template with invoice data and save"""
# Read the HTML template
with open(template_path, 'r', encoding='utf-8') as f:
html_content = f.read()
# Prepare data for injection
data = {
'invoice_no': invoice_data.get('Invoice No', ''),
'invoice_date': invoice_data.get('Invoice Date', ''),
'customer_name': invoice_data.get('Customer Name', ''),
'buyer_gstin': invoice_data.get('Customer GSTIN', ''),
'buyer_pan': invoice_data.get('Customer PAN', ''),
'buyer_cin': invoice_data.get('Customer CIN', ''),
'po_no': invoice_data.get('PO No', ''),
'buyer_state': invoice_data.get('Customer State', ''),
}
# Handle customer address (split into multiple lines)
address = invoice_data.get('Customer Address', '')
if address:
address_parts = [p.strip() for p in address.split(',')]
data['customer_address_1'] = address_parts[0] if len(address_parts) > 0 else ''
data['customer_address_2'] = address_parts[1] if len(address_parts) > 1 else ''
data['customer_address_3'] = ', '.join(address_parts[2:]) if len(address_parts) > 2 else ''
else:
data['customer_address_1'] = data['customer_address_2'] = data['customer_address_3'] = ''
# Calculate totals dynamically
items = invoice_data.get('Items', [])
total_taxable = 0
total_cgst = 0
total_sgst = 0
total_igst = 0
for item in items:
taxable_value = float(item.get('Taxable Value', 0))
cgst_percentage = float(item.get('CGST %', 0))
sgst_percentage = float(item.get('SGST %', 0))
igst_percentage = float(item.get('IGST %', 0))
# Calculate tax amounts dynamically
cgst_amount = round((taxable_value * cgst_percentage / 100), 2)
sgst_amount = round((taxable_value * sgst_percentage / 100), 2)
igst_amount = round((taxable_value * igst_percentage / 100), 2)
# Add to totals
total_taxable += taxable_value
total_cgst += cgst_amount
total_sgst += sgst_amount
total_igst += igst_amount
# Calculate grand total
grand_total = total_taxable + total_cgst + total_sgst + total_igst
# Add totals to data
data.update({
'total_taxable': format_amount(total_taxable),
'total_cgst': format_amount(total_cgst),
'total_sgst': format_amount(total_sgst),
'total_igst': format_amount(total_igst),
'grand_total': format_amount(grand_total),
'rounding': format_amount(0), # Can be calculated if needed
'net_amount': format_amount(grand_total),
'words_total': to_words(grand_total),
'words_cgst': to_words(total_cgst),
'words_sgst': to_words(total_sgst),
'words_igst': to_words(total_igst),
})
# Prepare items data for JavaScript injection
items_js = []
for i, item in enumerate(items):
taxable_value = float(item.get('Taxable Value', 0))
cgst_percentage = float(item.get('CGST %', 0))
sgst_percentage = float(item.get('SGST %', 0))
igst_percentage = float(item.get('IGST %', 0))
# Calculate tax amounts dynamically from percentages
cgst_amount = round((taxable_value * cgst_percentage / 100), 2)
sgst_amount = round((taxable_value * sgst_percentage / 100), 2)
igst_amount = round((taxable_value * igst_percentage / 100), 2)
# Calculate total amount
total_amount = taxable_value + cgst_amount + sgst_amount + igst_amount
items_js.append({
'sr': i + 1,
'desc': item.get('Service Details', ''),
'hsn': item.get('HSN', ''),
'tax': taxable_value,
'cgst_p': cgst_percentage,
'cgst_a': cgst_amount, # Dynamically calculated
'sgst_p': sgst_percentage,
'sgst_a': sgst_amount, # Dynamically calculated
'igst_p': igst_percentage,
'igst_a': igst_amount, # Dynamically calculated
'total': round(total_amount, 2), # Dynamically calculated
})
# Create JavaScript injection code
js_injection = f"""
"""
# Insert the injection script before the closing body tag
html_content = html_content.replace('