Created
May 16, 2021 17:30
-
-
Save JuliColombo/1002d3698da208d75d3604c200ac1379 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import pdfkit | |
| import os | |
| import base64 | |
| from django.core.files import File | |
| from django.template.loader import render_to_string | |
| class Exporter: | |
| def params(self): | |
| return {} | |
| def logo(self): | |
| path = os.path.join(os.path.dirname(__file__), 'static/logo.png') | |
| with open(path, 'rb') as logo: | |
| encoded_logo = base64.b64encode(logo.read()).decode() | |
| logo.close() | |
| return encoded_logo | |
| def generate_pdf(self, template_name, pdf_name, css_name=None): | |
| html = render_to_string(template_name, self.params()) | |
| css_path = 'static/style.css' | |
| if css_name: | |
| css_path = css_name | |
| css = os.path.join(os.path.dirname(__file__), css_path) | |
| pdfkit.from_string(html, pdf_name, css=css) | |
| return File(open(pdf_name, 'rb')) | |
| class InvoiceExporter(Exporter): | |
| def __init__(self, order): | |
| self.order = order | |
| def params(self): | |
| return { | |
| 'order': self.order, | |
| 'logo': self.logo() | |
| } | |
| def generate(self): | |
| return self.generate_pdf('invoice.html', 'Invoice.pdf') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment