first try

This commit is contained in:
Torsten Ueberschar
2024-02-07 17:05:53 +01:00
parent 17346d5197
commit 2c2066450c
15 changed files with 556 additions and 162 deletions

View File

@@ -0,0 +1,38 @@
from pathlib import Path
from jinja2 import FileSystemLoader, TemplateNotFound, Environment
from xhtml2pdf import pisa
class HtmlTemplate:
def __init__(self, templates):
self.template_name = 'invoice.html'
if not Path(templates).exists():
raise FileNotFoundError(f'Inivalid path to template files: {templates}')
self.templates = templates
def prepare_template(self, invoice_data, envelope_data):
try:
loader = FileSystemLoader(self.templates)
env = Environment(loader=loader)
template = env.get_template(self.template_name)
return template.render(invoice=invoice_data, envelope=envelope_data)
except TemplateNotFound:
raise FileNotFoundError(f'Could not find template file: {self.template_name}')
@staticmethod
def convert_html_to_pdf(source_html, output_filename):
# open output file for writing (truncated binary)
result_file = open(output_filename, "w+b")
# convert HTML to PDF
pisa_status = pisa.CreatePDF(
source_html, # the HTML to convert
dest=result_file) # file handle to recieve result
# close output file
result_file.close() # close output file
# return False on success and True on errors
return pisa_status.err