All Projects → weinbusch → django-tex

weinbusch / django-tex

Licence: MIT license
A simple Django app to render LaTeX templates and compile them into PDF files.

Programming Languages

python
139335 projects - #7 most used programming language
TeX
3793 projects
emacs lisp
2029 projects

Projects that are alternatives of or similar to django-tex

Staticjinja
Minimalist Python library for building static websites with Jinja
Stars: ✭ 218 (+220.59%)
Mutual labels:  jinja2
cmdb
Jerikan: a configuration management system for network teams
Stars: ✭ 141 (+107.35%)
Mutual labels:  jinja2
gpp
General PreProcessor
Stars: ✭ 25 (-63.24%)
Mutual labels:  jinja2
jinja.dart
Jinja2 template engine port for Dart.
Stars: ✭ 38 (-44.12%)
Mutual labels:  jinja2
pymzn
A Python wrapper for the MiniZinc tool pipeline.
Stars: ✭ 54 (-20.59%)
Mutual labels:  jinja2
pyLODE
An OWL ontology documentation tool using Python and templating, based on LODE
Stars: ✭ 116 (+70.59%)
Mutual labels:  jinja2
Yadm
Yet Another Dotfiles Manager
Stars: ✭ 2,982 (+4285.29%)
Mutual labels:  jinja2
gen-cisco
🧨 Generates Cisco scripts based on YAML files
Stars: ✭ 29 (-57.35%)
Mutual labels:  jinja2
nunjucks-template
This is a vscode extension for nunjucks template language which is also available to all Jinja style templates
Stars: ✭ 36 (-47.06%)
Mutual labels:  jinja2
chm-documentation
chm documentation PostgreSQL pgadmin3 SQLAlchemy Django Flask jinja2 webpy doc chm compiled html help Postgres Postgre документация russian
Stars: ✭ 17 (-75%)
Mutual labels:  jinja2
pelican-alchemy
A ✨ functional, clean, responsive Pelican theme
Stars: ✭ 129 (+89.71%)
Mutual labels:  jinja2
pylodon
Flask-based ActivityPub server
Stars: ✭ 86 (+26.47%)
Mutual labels:  jinja2
junos-automation-with-ansible
How to automate Junos with Ansible. This project has many ready-to-use Ansible playbooks to interact with Junos devices.
Stars: ✭ 69 (+1.47%)
Mutual labels:  jinja2
Statik
Multi-purpose static web site generator aimed at developers.
Stars: ✭ 249 (+266.18%)
Mutual labels:  jinja2
apprise-ga
GitHub Action to send a dynamic push notification to every single platform thanks to the Apprise library
Stars: ✭ 18 (-73.53%)
Mutual labels:  jinja2
Django Webpush
Web Push Notification Package for Django
Stars: ✭ 217 (+219.12%)
Mutual labels:  jinja2
flask-tweeeter
A full-stack Twitter clone made using the Flask framework for Python 🐦
Stars: ✭ 28 (-58.82%)
Mutual labels:  jinja2
Prinder
Free Pull Request reminder for Github. Has configurations to post reminders to Slack and email along with jinja templating
Stars: ✭ 21 (-69.12%)
Mutual labels:  jinja2
nene
Nēnē: A no-frills static site generator
Stars: ✭ 22 (-67.65%)
Mutual labels:  jinja2
xltpl
A python module to generate xls/x files from a xls/x template.
Stars: ✭ 46 (-32.35%)
Mutual labels:  jinja2

django-tex

django-tex is a simple Django app to render LaTeX templates and compile them into PDF files.

Django-tex requires a local LaTeX installation and uses the jinja2 templating engine for template rendering.

Installation

django-tex is available on pypi.org. It can be installed by:

pip install django_tex

Quick start

  1. Add "django_tex" to your INSTALLED_APPS setting:
INSTALLED_APPS = [
    ...
    'django_tex',
]
  1. Configure a template engine named tex in settings.py:
TEMPLATES = [
    {
        'NAME': 'tex',
        'BACKEND': 'django_tex.engine.TeXEngine', 
        'APP_DIRS': True,
    },
]
  1. Create a LaTeX template in your template directory:
# test.tex
\documentclass{article}

\begin{document}

\section{ {{- foo -}} }

\end{document}
  1. Use "compile_template_to_pdf" in your code to get the PDF file as a bytes object:
from django_tex.core import compile_template_to_pdf

template_name = 'test.tex'
context = {'foo': 'Bar'}
PDF = compile_template_to_pdf(template_name, context)

Or use render_to_pdf to generate a HTTPResponse containing the PDF file:

from django_tex.shortcuts import render_to_pdf

def view(request):
    template_name = 'test.tex'
    context = {'foo': 'Bar'}
    return render_to_pdf(request, template_name, context, filename='test.pdf')

Some notes on usage

Latex binary

The default LaTeX interpreter is set to lualatex. This can be changed by the setting LATEX_INTERPRETER, for instance: LATEX_INTERPRETER = 'pdflatex'. Of course, the interpreter needs to be installed on your system for django-tex to work properly.

Interpreter arguments

You can pass additional arguments to the latex interpreter by using the LATEX_INTERPRETER_OPTIONS setting.

Whitespace control

Since django-tex uses jinja, you can use jinja's whitespace control in LaTeX templates. For example, \section{ {{ foo }} } would be rendered as \section{ Bar } with the above context; \section{ {{- foo -}} }, however, gets rendered nicely as \section{Bar}.

Built-in filters

Django's built-in filters are available. So you can use {{ foo|date('d. F Y') }} to get 1. Januar 2018, for instance.

Further, django-tex adds the custom filter localize to the jinja environment. This runs its input through django.utils.formats.localize_input to create a localized representation. The output depends on the USE_L10N and LANGUAGE_CODE settings. Use the filter like this: {{ foo|localize }}.

If you want to convert linebreaks into LaTeX linebreaks (\\), use the linebreaks filter ({{ foo | linebreaks }}).

Escaping LaTeX special characters

To escape LaTeX special characters, use the latex_escape filter, i.e. {{ foo | latex_escape }}s. This escapes the following characters: &$%#_{}\^~ (see also this SO question) Using this filter all printable character should lead to a successful LaTeX build. Spacing for the characters \^~ is automatically adopted as an end user would expect it.

Please note Jinja's autoescaping is turned off in the default django-tex environment.

Custom filters

Custom filters can be defined as explained in the jinja documentation here. For example, the following filter formats a datetime.timedelta object as a hh:mm string:

def hhmm_format(value):
    total_seconds = value.total_seconds()
    hours, remainder = divmod(total_seconds, 3600)
    minutes, seconds = divmod(remainder, 60)
    return '{:n}:{:02n}'.format(hours, minutes)

The filter has to be added to a custom environment and the django-tex templating engine has to be made aware of the environment. This can be achieved, for example, by defining a custom environment callable in an environment.py module in your app:

# environment.py
from django_tex.environment import environment

def hhmm_format(value):
    pass # as above

def my_environment(**options):
    env = environment(**options)
    env.filters.update({
        'hhmm_format': hhmm_format
    })
    return env

... and passing the dotted path to my_environment to the TEMPLATES settings:

# settings.py

TEMPLATES = [
    {
        'NAME': 'tex',
        'BACKEND': 'django_tex.engine.TeXEngine', 
        'APP_DIRS': True,
        'OPTIONS': {
            'environment': 'myapp.environment.my_environment',
        }
    },
]

Including graphics files

Graphics can be included in LaTeX documents using the \includegraphics{<filename>} command provided by the graphicx package. Normally, LaTeX looks for graphics files in the current working directory, i.e. the directory including the source .tex file. The problem here is that django-tex creates a temporary directory to store the source file so that the LaTeX compiler does not see any graphics files provided by the Django application. This problem can be solved by specifying the absolute path to one or more directories including the graphics files using the \graphicspath command.

Django-tex allows the user to specify the absolute paths to one or more directories in the LATEX_GRAPHICSPATH setting. This setting should contain a list of one or more paths:

# settings.py

LATEX_GRAPHICSPATH = ['c:\foo\bar', 'c:\bar\foo']

Of course, a good way of constructing those paths is to use os.path.join(BASE_DIR, <path>).

Using the template tag {% graphicspath %}, the correct \graphicspath command can be inserted into the .tex template. In the above case, {% graphicspath %} turns into \graphicspath{ {"c:/foo/bar/"} {"c:/bar/foo/"} }. Use
{% graphicspath %} like this:

\documentclass{article}
\usepackage{graphicx}

{% graphicspath %}

\begin{document}

\includegraphics{foo}

\end{document}

If LATEX_GRAPHICSPATH is not specified, django-tex takes the BASE_DIR instead.

Note: There might be a problem if the path to the graphics directory contains whitespaces. To my knowledge, lualatex cannot handle whitespaces in the \graphicspath command, but pdflatex can.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].