update logging, update docuprint add new ui for generating documents

This commit is contained in:
2025-05-09 11:57:18 +02:00
parent f7ea6f5d34
commit 468e8674ab
16 changed files with 843 additions and 187 deletions

View File

@@ -8,6 +8,7 @@ import os
from os.path import basename
from loguru import logger as log
import sys
from src import settings
logger = log
@@ -22,11 +23,46 @@ log.add(
# logger.add(sys.stderr, format="{time} {level} {message}", level="INFO")
logger.add(sys.stdout)
font = "Cascadia Mono"
def print_document(file: str):
# send document to printer as attachment of email
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
from email.mime.text import MIMEText
smtp = settings.mail.smtp_server
port = settings.mail.port
sender_email = settings.mail.sender
password = settings.mail.password
receiver = settings.mail.printer_mail
message = MIMEMultipart()
message["From"] = sender_email
message["To"] = receiver
message["cc"] = settings.mail.sender
message["Subject"] = "."
mail_body = "."
message.attach(MIMEText(mail_body, "html"))
with open(file, "rb") as fil:
part = MIMEApplication(fil.read(), Name=basename(file))
# After the file is closed
part["Content-Disposition"] = 'attachment; filename="%s"' % basename(file)
message.attach(part)
mail = message.as_string()
with smtplib.SMTP_SSL(smtp, port) as server:
server.connect(smtp, port)
server.login(settings.mail.user_name, password)
server.sendmail(sender_email, receiver, mail)
server.quit()
logger.success("Mail sent")
class SemesterError(Exception):
"""Custom exception for semester-related errors."""
def __init__(self, message):
def __init__(self, message: str):
super().__init__(message)
logger.error(message)
@@ -39,8 +75,7 @@ class SemesterDocument:
self,
apparats: list[tuple[int, str]],
semester: str,
filename,
config,
filename: str,
full: bool = False,
):
assert isinstance(apparats, list), SemesterError(
@@ -62,25 +97,26 @@ class SemesterDocument:
self.doc = Document()
self.apparats = apparats
self.semester = semester
self.table_font = "Arial"
self.header_font = "Times New Roman"
self.table_font_normal = font
self.table_font_bold = font
self.header_font = font
self.header_font_size = Pt(26)
self.sub_header_font_size = Pt(18)
self.table_font_size = Pt(10)
self.color_red = RGBColor(255, 0, 0)
self.color_blue = RGBColor(0, 0, 255)
self.filename = filename
self.settings = config
if full:
logger.info("Full document generation")
self.make_document()
logger.info("Document created")
self.create_pdf()
logger.info("PDF created")
self.print_document()
print_document(self.filename + ".pdf")
logger.info("Document printed")
self.cleanup()
self.cleanup
logger.info("Cleanup done")
def set_table_border(self, table):
"""
Adds a full border to the table.
@@ -110,7 +146,7 @@ class SemesterDocument:
table.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
# Set column widths by directly modifying the cell properties
widths = [Cm(1.19), Cm(10.39)]
widths = [Cm(1.19), Cm(18)]
for col_idx, width in enumerate(widths):
for cell in table.columns[col_idx].cells:
cell_width_element = cell._element.xpath(".//w:tcPr")[0]
@@ -136,7 +172,7 @@ class SemesterDocument:
# Set font for the first column (number)
cell_number_paragraph = row.cells[0].paragraphs[0]
cell_number_run = cell_number_paragraph.add_run(str(number))
cell_number_run.font.name = self.table_font
cell_number_run.font.name = self.table_font_bold
cell_number_run.font.size = self.table_font_size
cell_number_run.font.bold = True
cell_number_run.font.color.rgb = self.color_red
@@ -149,13 +185,13 @@ class SemesterDocument:
# Add the first word in bold
bold_run = cell_name_paragraph.add_run(words[0])
bold_run.font.bold = True
bold_run.font.name = self.table_font
bold_run.font.name = self.table_font_bold
bold_run.font.size = self.table_font_size
# Add the rest of the words normally
if len(words) > 1:
normal_run = cell_name_paragraph.add_run(" " + " ".join(words[1:]))
normal_run.font.name = self.table_font
normal_run.font.name = self.table_font_normal
normal_run.font.size = self.table_font_size
cell_name_paragraph.alignment = WD_PARAGRAPH_ALIGNMENT.LEFT
@@ -198,42 +234,6 @@ class SemesterDocument:
def save_document(self, name):
# Save the document
self.doc.save(name)
print(f"Document saved as {name}")
def print_document(self):
# send document to printer as attachment of email
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
from email.mime.text import MIMEText
config = self.settings
smtp = config.mail.smtp_server
port = config.mail.port
sender_email = config.mail.sender
password = config.mail.password
receiver = config.mail.printer_mail
message = MIMEMultipart()
message["From"] = sender_email
message["To"] = receiver
message["cc"] = config.mail.sender
message["Subject"] = "."
mail_body = "."
message.attach(MIMEText(mail_body, "html"))
with open(self.filename + ".pdf", "rb") as fil:
part = MIMEApplication(fil.read(), Name=basename(self.filename + "pdf"))
# After the file is closed
part["Content-Disposition"] = 'attachment; filename="%s"' % basename(
self.filename + ".pdf"
)
message.attach(part)
mail = message.as_string()
with smtplib.SMTP_SSL(smtp, port) as server:
server.connect(smtp, port)
server.login(config.mail.user_name, password)
server.sendmail(sender_email, receiver, mail)
server.quit()
print("Mail sent")
def create_pdf(self):
# Save the document
@@ -249,29 +249,112 @@ class SemesterDocument:
word.Quit()
logger.debug("PDF saved")
@property
def cleanup(self):
os.remove(f"{self.filename}.docx")
os.remove(f"{self.filename}.pdf")
@property
def send(self):
print_document(self.filename + ".pdf")
logger.debug("Document sent to printer")
class SemapSchilder:
def __init__(self, entries: list[str]):
self.entries = entries
self.filename = "Schilder"
self.font_size = Pt(23)
self.font_name = font
self.doc = Document()
self.define_doc_properties()
self.add_entries()
self.cleanup()
self.create_pdf()
def define_doc_properties(self):
# set the doc to have a top margin of 1cm, left and right are 0.5cm, bottom is 0cm
section = self.doc.sections[0]
section.top_margin = Cm(1)
section.bottom_margin = Cm(0)
section.left_margin = Cm(0.5)
section.right_margin = Cm(0.5)
# set the font to Times New Roman, size 23 bold, color black
for paragraph in self.doc.paragraphs:
for run in paragraph.runs:
run.font.name = self.font_name
run.font.size = self.font_size
run.font.bold = True
run.font.color.rgb = RGBColor(0, 0, 0)
paragraph.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
# if the length of the text is
def add_entries(self):
for entry in self.entries:
paragraph = self.doc.add_paragraph(entry)
paragraph.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
paragraph.paragraph_format.line_spacing = Pt(20) # Set fixed line spacing
paragraph.paragraph_format.space_before = Pt(4) # Remove spacing before
paragraph.paragraph_format.space_after = Pt(4) # Remove spacing after
run = paragraph.runs[0]
run.font.name = self.font_name
run.font.size = self.font_size
run.font.bold = True
run.font.color.rgb = RGBColor(0, 0, 0)
# Add a line to be used as a guideline for cutting
line = self.doc.add_paragraph()
line.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
line.paragraph_format.line_spacing = Pt(20) # Match line spacing
line.paragraph_format.space_before = Pt(4) # Remove spacing before
line.paragraph_format.space_after = Pt(4) # Remove spacing after
line.add_run("--------------------------")
for paragraph in self.doc.paragraphs:
content = paragraph.text.strip()
if len(content) > 45:
paragraph.runs[0].font.size = Pt(20)
def save_document(self):
# Save the document
self.doc.save(f"{self.filename}.docx")
logger.debug(f"Document saved as {self.filename}.docx")
def create_pdf(self):
# Save the document
import comtypes.client
word = comtypes.client.CreateObject("Word.Application")
self.save_document()
docpath = os.path.abspath(f"{self.filename}.docx")
doc = word.Documents.Open(docpath)
curdir = os.getcwd()
doc.SaveAs(f"{curdir}/{self.filename}.pdf", FileFormat=17)
doc.Close()
word.Quit()
logger.debug("PDF saved")
def cleanup(self):
if os.path.exists(f"{self.filename}.docx"):
os.remove(f"{self.filename}.docx")
if os.path.exists(f"{self.filename}.pdf"):
os.remove(f"{self.filename}.pdf")
@property
def send(self):
print_document(self.filename + ".pdf")
logger.debug("Document sent to printer")
if __name__ == "__main__":
pass
# apparat = [(i, f"Item {i}") for i in range(405, 438)]
# doc = SemesterDocument(
# apparat,
# "WiSe 24/25",
# "semap",
# )
# doc.make_document()
# doc.create_pdf()
# doc.print_document()
# def printers():
# printers = win32print.EnumPrinters(
# win32print.PRINTER_ENUM_LOCAL | win32print.PRINTER_ENUM_CONNECTIONS
# )
# for i, printer in enumerate(printers):
# print(f"{i}: {printer[2]}")
# list printers
entries = [
"Schlenke (Glaube und Handels. Luthers Freiheitsschrift)",
"Lüsebrink (Theorie und Praxis der Leichtathletik)",
"Tester (Apparatstester)",
"Entry 4",
"Entry 5",
]
doc = SemapSchilder(entries).send