first try
This commit is contained in:
38
src/invoice_generator/html_generator.py
Normal file
38
src/invoice_generator/html_generator.py
Normal 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
|
||||
Reference in New Issue
Block a user