-
-
Save lucasrcezimbra/e902a1bf0750ad2182d9bde87066bfa9 to your computer and use it in GitHub Desktop.
creating pdf with python and jinja
This file contains 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
from jinja2 import Environment | |
from jinja2 import FileSystemLoader | |
from pdfkit import from_string | |
def create_pdf(): | |
template_vars = { | |
'template_title': 'A template example', | |
'template_description': 'Lorem ipsum dolor sit amet, consectetur adipisicing elit' | |
} | |
env = Environment(loader=FileSystemLoader('your_template_path')) | |
template = env.get_template('your_template_file.html') | |
html_out = template.render(template_vars) | |
file_content = from_string( | |
html_out, | |
False, | |
options='here_a_dict_with_special_page_properties', | |
css='here_your_css_file_path' # its a list e.g ['my_css.css', 'my_other_css.css'] | |
) | |
return file_content | |
def save_pdf(file_content): | |
try: | |
with open('your_pdf_file_here.pdf', 'wb+') as file: | |
file.write(file_content) | |
except Exception as error: | |
logging.error(f'Error saving file to disc. Error: {error}') | |
raise error | |
if __name__ == '__main__': | |
pdf_file = create_pdf() | |
save_pdf(pdf_file) |
This file contains 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
<head></head> | |
<body> | |
<h1>Interest Rate: {{ template_title }}%</h1> | |
<p>{{ template_description }}</p> | |
</body> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment