95 lines
3.4 KiB
Python
95 lines
3.4 KiB
Python
import datetime
|
|
import io
|
|
import os
|
|
|
|
import fitz
|
|
from django.core.files import File
|
|
|
|
from .models import Bill, Wiref
|
|
|
|
|
|
def generate_pdf(wiref):
|
|
if wiref is not None and wiref.status == Wiref.Status.OPENED:
|
|
bills = Bill.objects.filter(wiref=wiref).order_by("date")
|
|
|
|
data = {}
|
|
for count, elem in enumerate(bills):
|
|
data.update(
|
|
{
|
|
f"Datum.{count}": str(elem.date.strftime("%d.%m.%Y")),
|
|
f"Aussteller.{count}": elem.invoice,
|
|
f"Verwendungszweck.{count}": elem.purpose,
|
|
# replace decimal separator from '.' to ','
|
|
f"Betrag.{count}": str(elem.amount).replace(".", ","),
|
|
}
|
|
)
|
|
|
|
# get budget year
|
|
today = datetime.date.today()
|
|
if today.month < 7:
|
|
budget_year = f"{today.year - 1}-{today.year}"
|
|
else:
|
|
budget_year = f"{today.year}-{today.year + 1}"
|
|
|
|
# get total of all bills of wiref form
|
|
total = 0
|
|
for elem in bills:
|
|
total += elem.amount
|
|
|
|
data.update(
|
|
{
|
|
"Laufende Nummer": str(wiref.wiref_id),
|
|
"Budgetjahr": budget_year,
|
|
# replace decimal separator from '.' to ','
|
|
"Summe": str(total).replace(".", ","),
|
|
}
|
|
)
|
|
|
|
pdf_path = os.path.join(os.path.dirname(__file__), "static/Vorlage.pdf")
|
|
with fitz.open(pdf_path) as doc:
|
|
for page in doc:
|
|
widgets = page.widgets()
|
|
for widget in widgets:
|
|
if widget.field_name in data:
|
|
# removing '\r' is important for textbox in pdf file
|
|
widget.field_value = data[widget.field_name].replace("\r", "")
|
|
fontsize = widget.text_fontsize
|
|
|
|
# update font size if there are more than one newlines in string
|
|
count = widget.field_value.count("\n") + 1
|
|
if count > 1:
|
|
fontsize = 0.7 * widget.rect.height / count
|
|
|
|
if (
|
|
widget.text_fontsize == 0
|
|
or fontsize < widget.text_fontsize
|
|
):
|
|
widget.text_fontsize = fontsize
|
|
|
|
# get max length of one line of multi-line text
|
|
max_len = 0
|
|
for elem in widget.field_value.split("\n"):
|
|
length = fitz.get_text_length(elem)
|
|
if length > max_len:
|
|
max_len = length
|
|
|
|
# update fontsize if length of text is longer than rectangle width
|
|
if max_len > widget.rect.width:
|
|
fontsize = widget.rect.width / max_len * 10
|
|
|
|
if (
|
|
widget.text_fontsize == 0
|
|
or fontsize < widget.text_fontsize
|
|
):
|
|
widget.text_fontsize = fontsize
|
|
|
|
widget.update()
|
|
|
|
dist = doc.tobytes()
|
|
wiref_name = f"{wiref.wiref_id}.pdf"
|
|
wiref.file_field.save(wiref_name, File(io.BytesIO(dist), wiref_name))
|
|
|
|
return True
|
|
|
|
return False
|