├── .editorconfig ├── .github └── ISSUE_TEMPLATE.md ├── .gitignore ├── .travis.yml ├── AUTHORS.rst ├── CONTRIBUTING.rst ├── HISTORY.rst ├── LICENSE ├── MANIFEST.in ├── Makefile ├── README.rst ├── ci └── linux.sh ├── docs ├── Makefile ├── conf.py ├── document-template.png ├── generated-document.png ├── http.rst ├── index.rst ├── looping-sample.png ├── make.bat ├── management-commands.rst ├── partial │ └── libffi-warning.rst ├── settings.rst ├── templates.rst └── templatetags.rst ├── example ├── db.sqlite3 ├── example │ ├── __init__.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── invoices │ ├── __init__.py │ ├── admin.py │ ├── apps.py │ ├── forms.py │ ├── migrations │ │ ├── 0001_initial.py │ │ └── __init__.py │ ├── models.py │ ├── templates │ │ └── invoices │ │ │ ├── form.html │ │ │ └── invoice.odt │ ├── tests.py │ └── views.py └── manage.py ├── requirements_dev.txt ├── setup.cfg ├── setup.py ├── templated_docs ├── __init__.py ├── http.py ├── management │ ├── __init__.py │ └── base.py └── templatetags │ ├── __init__.py │ └── templated_docs_tags.py ├── tests ├── __init__.py ├── manage.py ├── test_app │ ├── __init__.py │ ├── admin.py │ ├── apps.py │ ├── migrations │ │ └── __init__.py │ ├── models.py │ ├── templates │ │ └── correct_template.odt │ ├── tests.py │ └── views.py └── test_project │ ├── __init__.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── tox.ini └── travis_pypi_setup.py /.editorconfig: -------------------------------------------------------------------------------- 1 | # http://editorconfig.org 2 | 3 | root = true 4 | 5 | [*] 6 | indent_style = space 7 | indent_size = 4 8 | trim_trailing_whitespace = true 9 | insert_final_newline = true 10 | charset = utf-8 11 | end_of_line = lf 12 | 13 | [*.bat] 14 | indent_style = tab 15 | end_of_line = crlf 16 | 17 | [LICENSE] 18 | insert_final_newline = false 19 | 20 | [Makefile] 21 | indent_style = tab 22 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | * Templated-docs version: 2 | * Python version: 3 | * Operating System: 4 | 5 | ### Description 6 | 7 | Describe what you were trying to get done. 8 | Tell us what happened, what went wrong, and what you expected to happen. 9 | 10 | ### What I Did 11 | 12 | ``` 13 | Paste the command(s) you ran and the output. 14 | If there was a crash, please include the traceback here. 15 | ``` 16 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | env/ 12 | build/ 13 | develop-eggs/ 14 | dist/ 15 | downloads/ 16 | eggs/ 17 | .eggs/ 18 | lib/ 19 | lib64/ 20 | parts/ 21 | sdist/ 22 | var/ 23 | *.egg-info/ 24 | .installed.cfg 25 | *.egg 26 | 27 | # PyInstaller 28 | # Usually these files are written by a python script from a template 29 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 30 | *.manifest 31 | *.spec 32 | 33 | # Installer logs 34 | pip-log.txt 35 | pip-delete-this-directory.txt 36 | 37 | # Unit test / coverage reports 38 | htmlcov/ 39 | .tox/ 40 | .coverage 41 | .coverage.* 42 | .cache 43 | nosetests.xml 44 | coverage.xml 45 | *,cover 46 | .hypothesis/ 47 | 48 | # Translations 49 | *.mo 50 | *.pot 51 | 52 | # Django stuff: 53 | *.log 54 | 55 | # Sphinx documentation 56 | docs/_build/ 57 | 58 | # PyBuilder 59 | target/ 60 | 61 | # LibreOffice temporary files 62 | ~$*.odt 63 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: python 2 | python: 3.5 3 | env: 4 | global: 5 | LO_VERSION=5.1.1.3 6 | LO_PATH=/opt/libreoffice5.1/program 7 | matrix: 8 | - TOXENV=py27-django18 9 | - TOXENV=py27-django19 10 | - TOXENV=py27-django110 11 | - TOXENV=py34-django18 12 | - TOXENV=py34-django19 13 | - TOXENV=py34-django110 14 | - TOXENV=flake8 15 | install: pip install -U tox 16 | before_install: 17 | - sudo bash ci/linux.sh 18 | sudo: required 19 | script: tox -e ${TOXENV} 20 | deploy: 21 | provider: pypi 22 | distributions: sdist bdist_wheel 23 | password: 24 | secure: "M6mzV77Lp1YkqrWquW3BIwZxe+mF3pnxxV/eFlG/lu6gSEqqnNIGI4l8r/oGxJtVDXKAtALBBaZLJeLnwHvgtsWfkM8T8+9O5KUgAwC9XzIK5QZzFy9M/5O9q1S/z8Soh0jQMiJ8LfHiHBlMkB+f0Yjpd+LDjn/csUbucPYL0qy8sfDKkEHQxR+7N47ncJk2uKAZc5gKZRv6fxZT1SoD5zFlLGuTWGKMJh5PJpG/+enLrkTr6GntSYyY00+EiS0wuQq7N6ymlaN4nPf7vRoR/JaDGQ3LaAaDnwVFNC8cCQlTQP0gx/tcnUYwUmxfP4Ij1kZvfr+bYbEvnn4TA0g1cwap3eXMi6gkwgIh9A2NUS1SmkuhQRvgEXFaIFLyd+c1K8E/+QefI7mB+EG2EyuWo6iEJBiLiehWc+O1PuPkpak3FmZ0ayrK6AOdI0ZQ2rMPwb/Pms09v9r9qcTMLS8DIMH5P5tTmrI/4pG9nMpbhIUWkaWcuO+kSBqUGlqzEkzoPFOePUoxWXN6EAc6s5g/ndF618759vaQegJwLRhsptvHgRdyLNEn8175OBfKu20B2JA4EHDGp/O95Kla2N/U1ycO7xHkMsoPynpvvIs6LWU8tnRxeciVGoCRNWGLgKK7Nz13omiRqfuZrNFCaoV/zMF2QOWrwUG03zWZ0Vi7mHU=" 25 | user: inductor 26 | on: 27 | condition: $TOXENV == py34-django19 28 | repo: alexmorozov/templated-docs 29 | tags: true 30 | -------------------------------------------------------------------------------- /AUTHORS.rst: -------------------------------------------------------------------------------- 1 | ======= 2 | Credits 3 | ======= 4 | 5 | Development Lead 6 | ---------------- 7 | 8 | * Alex Morozov 9 | 10 | Contributors 11 | ------------ 12 | 13 | None yet. Why not be the first? 14 | -------------------------------------------------------------------------------- /CONTRIBUTING.rst: -------------------------------------------------------------------------------- 1 | .. highlight:: shell 2 | 3 | ============ 4 | Contributing 5 | ============ 6 | 7 | Contributions are welcome, and they are greatly appreciated! Every 8 | little bit helps, and credit will always be given. 9 | 10 | You can contribute in many ways: 11 | 12 | Types of Contributions 13 | ---------------------- 14 | 15 | Report Bugs 16 | ~~~~~~~~~~~ 17 | 18 | Report bugs at https://github.com/alexmorozov/templated-docs/issues. 19 | 20 | If you are reporting a bug, please include: 21 | 22 | * Your operating system name and version. 23 | * Any details about your local setup that might be helpful in troubleshooting. 24 | * Detailed steps to reproduce the bug. 25 | 26 | Fix Bugs 27 | ~~~~~~~~ 28 | 29 | Look through the GitHub issues for bugs. Anything tagged with "bug" 30 | is open to whoever wants to implement it. 31 | 32 | Implement Features 33 | ~~~~~~~~~~~~~~~~~~ 34 | 35 | Look through the GitHub issues for features. Anything tagged with "feature" 36 | is open to whoever wants to implement it. 37 | 38 | Write Documentation 39 | ~~~~~~~~~~~~~~~~~~~ 40 | 41 | Templated-docs could always use more documentation, whether as part of the 42 | official Templated-docs docs, in docstrings, or even on the web in blog posts, 43 | articles, and such. 44 | 45 | Submit Feedback 46 | ~~~~~~~~~~~~~~~ 47 | 48 | The best way to send feedback is to file an issue at https://github.com/alexmorozov/templated-docs/issues. 49 | 50 | If you are proposing a feature: 51 | 52 | * Explain in detail how it would work. 53 | * Keep the scope as narrow as possible, to make it easier to implement. 54 | * Remember that this is a volunteer-driven project, and that contributions 55 | are welcome :) 56 | 57 | Get Started! 58 | ------------ 59 | 60 | Ready to contribute? Here's how to set up `templated_docs` for local development. 61 | 62 | 1. Fork the `templated-docs` repo on GitHub. 63 | 2. Clone your fork locally:: 64 | 65 | $ git clone git@github.com:your_name_here/templated-docs.git 66 | 67 | 3. Install your local copy into a virtualenv. Assuming you have virtualenvwrapper installed, this is how you set up your fork for local development:: 68 | 69 | $ mkvirtualenv templated-docs 70 | $ cd templated-docs/ 71 | $ python setup.py develop 72 | 73 | 4. Create a branch for local development:: 74 | 75 | $ git checkout -b name-of-your-bugfix-or-feature 76 | 77 | Now you can make your changes locally. 78 | 79 | 5. When you're done making changes, check that your changes pass flake8 and the tests, including testing other Python versions with tox:: 80 | 81 | $ flake8 templated_docs tests 82 | $ python setup.py test or py.test 83 | $ tox 84 | 85 | To get flake8 and tox, just pip install them into your virtualenv. 86 | 87 | 6. Commit your changes and push your branch to GitHub:: 88 | 89 | $ git add . 90 | $ git commit -m "Your detailed description of your changes." 91 | $ git push origin name-of-your-bugfix-or-feature 92 | 93 | 7. Submit a pull request through the GitHub website. 94 | 95 | Pull Request Guidelines 96 | ----------------------- 97 | 98 | Before you submit a pull request, check that it meets these guidelines: 99 | 100 | 1. The pull request should include tests. 101 | 2. If the pull request adds functionality, the docs should be updated. Put 102 | your new functionality into a function with a docstring, and add the 103 | feature to the list in README.rst. 104 | 3. The pull request should work for Python 2.6, 2.7, 3.3, 3.4 and 3.5, and for PyPy. Check 105 | https://travis-ci.org/alexmorozov/templated-docs/pull_requests 106 | and make sure that the tests pass for all supported Python versions. 107 | 108 | Tips 109 | ---- 110 | 111 | To run a subset of tests:: 112 | 113 | 114 | $ python -m unittest tests.test_templated_docs 115 | -------------------------------------------------------------------------------- /HISTORY.rst: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alexmorozov/templated-docs/c2bd2d245b220e96d7533267ddd7ef77970b0c74/HISTORY.rst -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | MIT License 3 | 4 | Copyright (c) 2016, Alex Morozov 5 | 6 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 7 | 8 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 9 | 10 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 11 | 12 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include AUTHORS.rst 2 | include CONTRIBUTING.rst 3 | include HISTORY.rst 4 | include LICENSE 5 | include README.rst 6 | 7 | recursive-include tests * 8 | recursive-exclude * __pycache__ 9 | recursive-exclude * *.py[co] 10 | 11 | recursive-include docs *.rst conf.py Makefile make.bat *.jpg *.png *.gif 12 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | .PHONY: clean clean-test clean-pyc clean-build docs help 2 | .DEFAULT_GOAL := help 3 | define BROWSER_PYSCRIPT 4 | import os, webbrowser, sys 5 | try: 6 | from urllib import pathname2url 7 | except: 8 | from urllib.request import pathname2url 9 | 10 | webbrowser.open("file://" + pathname2url(os.path.abspath(sys.argv[1]))) 11 | endef 12 | export BROWSER_PYSCRIPT 13 | 14 | define PRINT_HELP_PYSCRIPT 15 | import re, sys 16 | 17 | for line in sys.stdin: 18 | match = re.match(r'^([a-zA-Z_-]+):.*?## (.*)$$', line) 19 | if match: 20 | target, help = match.groups() 21 | print("%-20s %s" % (target, help)) 22 | endef 23 | export PRINT_HELP_PYSCRIPT 24 | BROWSER := python -c "$$BROWSER_PYSCRIPT" 25 | 26 | help: 27 | @python -c "$$PRINT_HELP_PYSCRIPT" < $(MAKEFILE_LIST) 28 | 29 | clean: clean-build clean-pyc clean-test ## remove all build, test, coverage and Python artifacts 30 | 31 | 32 | clean-build: ## remove build artifacts 33 | rm -fr build/ 34 | rm -fr dist/ 35 | rm -fr .eggs/ 36 | find . -name '*.egg-info' -exec rm -fr {} + 37 | find . -name '*.egg' -exec rm -f {} + 38 | 39 | clean-pyc: ## remove Python file artifacts 40 | find . -name '*.pyc' -exec rm -f {} + 41 | find . -name '*.pyo' -exec rm -f {} + 42 | find . -name '*~' -exec rm -f {} + 43 | find . -name '__pycache__' -exec rm -fr {} + 44 | 45 | clean-test: ## remove test and coverage artifacts 46 | rm -fr .tox/ 47 | rm -f .coverage 48 | rm -fr htmlcov/ 49 | 50 | lint: ## check style with flake8 51 | flake8 templated_docs tests 52 | 53 | test: ## run tests quickly with the default Python 54 | 55 | python setup.py test 56 | 57 | test-all: ## run tests on every Python version with tox 58 | tox 59 | 60 | coverage: ## check code coverage quickly with the default Python 61 | 62 | coverage run --source templated_docs setup.py test 63 | 64 | coverage report -m 65 | coverage html 66 | $(BROWSER) htmlcov/index.html 67 | 68 | docs: ## generate Sphinx HTML documentation, including API docs 69 | rm -f docs/templated_docs.rst 70 | rm -f docs/modules.rst 71 | sphinx-apidoc -o docs/ templated_docs 72 | $(MAKE) -C docs clean 73 | $(MAKE) -C docs html 74 | $(BROWSER) docs/_build/html/index.html 75 | 76 | servedocs: docs ## compile the docs watching for changes 77 | watchmedo shell-command -p '*.rst' -c '$(MAKE) -C docs html' -R -D . 78 | 79 | release: clean ## package and upload a release 80 | python setup.py sdist upload 81 | python setup.py bdist_wheel upload 82 | 83 | dist: clean ## builds source and wheel package 84 | python setup.py sdist 85 | python setup.py bdist_wheel 86 | ls -l dist 87 | 88 | install: clean ## install the package to the active Python's site-packages 89 | python setup.py install 90 | -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | =============================== 2 | Templated-docs 3 | =============================== 4 | 5 | 6 | .. image:: https://badge.fury.io/py/templated-docs.svg 7 | :target: https://pypi.python.org/pypi/templated_docs 8 | 9 | .. image:: https://img.shields.io/travis/alexmorozov/templated-docs.svg 10 | :target: https://travis-ci.org/alexmorozov/templated-docs 11 | 12 | .. image:: https://readthedocs.org/projects/templated-docs/badge/?version=latest 13 | :target: https://templated-docs.readthedocs.io/en/latest/?badge=latest 14 | :alt: Documentation Status 15 | 16 | .. image:: https://requires.io/github/alexmorozov/templated-docs/requirements.svg?branch=master 17 | :target: https://requires.io/github/alexmorozov/templated-docs/requirements?branch=master 18 | :alt: Dependencies 19 | 20 | 21 | Generate templated documents within Django in any format supported by 22 | LibreOffice: texts, spreadsheets, presentations etc. 23 | 24 | 25 | * Free software: MIT license 26 | * Documentation: https://templated-docs.readthedocs.io. 27 | 28 | 29 | Requirements 30 | ------------ 31 | 32 | * Python 2.7 or 3.4+ 33 | * Django >= 1.8 34 | * A recent LibreOffice version (>=4.3.0) supporting LibreOfficeKit API. 35 | 36 | .. include:: docs/partial/libffi-warning.rst 37 | 38 | Example usage 39 | ------------- 40 | 41 | Create a ``sample.odt`` document (make sure it's in OpenDocument format) and 42 | put it in your Django templates folder. It should look something like this: 43 | 44 | .. image:: https://github.com/alexmorozov/templated-docs/raw/master/docs/document-template.png 45 | 46 | Then write a view to generate documents from this template: 47 | 48 | .. code-block:: python 49 | 50 | from templated_docs import fill_template 51 | from templated_docs.http import FileResponse 52 | 53 | def get_document(request): 54 | """ 55 | A view to get a document filled with context variables. 56 | """ 57 | context = {'user': request.user} # Just an example 58 | 59 | filename = fill_template('sample.odt', context, output_format='pdf') 60 | visible_filename = 'greeting.pdf' 61 | 62 | return FileResponse(filename, visible_filename) 63 | 64 | Navigate to the url your view is connected to, and you'll see a rendered and converted document: 65 | 66 | .. image:: https://github.com/alexmorozov/templated-docs/raw/master/docs/generated-document.png 67 | 68 | For more examples, see the ``examples/`` subfolder in the repository. More detailed documentation is available on https://templated-docs.readthedocs.io. 69 | 70 | Credits 71 | --------- 72 | 73 | Templated-docs was written by `Alex Morozov`_. 74 | 75 | This package was created with Cookiecutter_ and the `audreyr/cookiecutter-pypackage`_ project template. 76 | 77 | .. _Cookiecutter: https://github.com/audreyr/cookiecutter 78 | .. _`audreyr/cookiecutter-pypackage`: https://github.com/audreyr/cookiecutter-pypackage 79 | .. _pylokit: https://github.com/xrmx/pylokit 80 | .. _`Alex Morozov`: http://morozov.ca 81 | -------------------------------------------------------------------------------- /ci/linux.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # https://github.com/dagwieers/unoconv/blob/master/ci/linux.bash 4 | 5 | set -o errexit 6 | 7 | [[ $(uname) != 'Linux' ]] && exit 8 | 9 | pushd /tmp 10 | 11 | if [[ "$LO_VERSION" =~ ^3.3.* ]]; then 12 | urldir=https://downloadarchive.documentfoundation.org/libreoffice/old/$LO_VERSION/deb/x86_64 13 | cutversion=$(echo $LO_VERSION | sed 's/\.[0-9]$//') 14 | filename=LibO_${cutversion}_Linux_x86-64_install-deb_en-US 15 | elif [[ "$LO_VERSION" =~ ^3.[4-5].* ]]; then 16 | urldir=https://downloadarchive.documentfoundation.org/libreoffice/old/$LO_VERSION/deb/x86_64 17 | rcversion=$(echo $LO_VERSION | sed 's/\.2$/rc2/') 18 | filename=LibO_${rcversion}_Linux_x86-64_install-deb_en-US 19 | elif [[ "$LO_VERSION" =~ ^3.* ]]; then 20 | urldir=https://downloadarchive.documentfoundation.org/libreoffice/old/$LO_VERSION/deb/x86_64 21 | filename=LibO_${LO_VERSION}_Linux_x86-64_install-deb_en-US 22 | else 23 | urldir=https://downloadarchive.documentfoundation.org/libreoffice/old/$LO_VERSION/deb/x86_64 24 | filename=LibreOffice_${LO_VERSION}_Linux_x86-64_deb 25 | fi 26 | 27 | wget $urldir/${filename}.tar.gz 28 | tar xvf ${filename}.tar.gz 29 | dpkg -i Lib*_Linux_x86-64*deb*/DEBS/*.deb 30 | 31 | twodigitsversion=$(echo $LO_VERSION | cut -c 1-3) 32 | ln -s /opt/libreoffice${twodigitsversion}/program/python /tmp/python 33 | -------------------------------------------------------------------------------- /docs/Makefile: -------------------------------------------------------------------------------- 1 | # Makefile for Sphinx documentation 2 | # 3 | 4 | # You can set these variables from the command line. 5 | SPHINXOPTS = 6 | SPHINXBUILD = sphinx-build 7 | PAPER = 8 | BUILDDIR = _build 9 | 10 | # User-friendly check for sphinx-build 11 | ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1) 12 | $(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/) 13 | endif 14 | 15 | # Internal variables. 16 | PAPEROPT_a4 = -D latex_paper_size=a4 17 | PAPEROPT_letter = -D latex_paper_size=letter 18 | ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . 19 | # the i18n builder cannot share the environment and doctrees with the others 20 | I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . 21 | 22 | .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext 23 | 24 | help: 25 | @echo "Please use \`make ' where is one of" 26 | @echo " html to make standalone HTML files" 27 | @echo " dirhtml to make HTML files named index.html in directories" 28 | @echo " singlehtml to make a single large HTML file" 29 | @echo " pickle to make pickle files" 30 | @echo " json to make JSON files" 31 | @echo " htmlhelp to make HTML files and a HTML help project" 32 | @echo " qthelp to make HTML files and a qthelp project" 33 | @echo " devhelp to make HTML files and a Devhelp project" 34 | @echo " epub to make an epub" 35 | @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" 36 | @echo " latexpdf to make LaTeX files and run them through pdflatex" 37 | @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx" 38 | @echo " text to make text files" 39 | @echo " man to make manual pages" 40 | @echo " texinfo to make Texinfo files" 41 | @echo " info to make Texinfo files and run them through makeinfo" 42 | @echo " gettext to make PO message catalogs" 43 | @echo " changes to make an overview of all changed/added/deprecated items" 44 | @echo " xml to make Docutils-native XML files" 45 | @echo " pseudoxml to make pseudoxml-XML files for display purposes" 46 | @echo " linkcheck to check all external links for integrity" 47 | @echo " doctest to run all doctests embedded in the documentation (if enabled)" 48 | 49 | clean: 50 | rm -rf $(BUILDDIR)/* 51 | 52 | html: 53 | $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html 54 | @echo 55 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." 56 | 57 | dirhtml: 58 | $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml 59 | @echo 60 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." 61 | 62 | singlehtml: 63 | $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml 64 | @echo 65 | @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." 66 | 67 | pickle: 68 | $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle 69 | @echo 70 | @echo "Build finished; now you can process the pickle files." 71 | 72 | json: 73 | $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json 74 | @echo 75 | @echo "Build finished; now you can process the JSON files." 76 | 77 | htmlhelp: 78 | $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp 79 | @echo 80 | @echo "Build finished; now you can run HTML Help Workshop with the" \ 81 | ".hhp project file in $(BUILDDIR)/htmlhelp." 82 | 83 | qthelp: 84 | $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp 85 | @echo 86 | @echo "Build finished; now you can run "qcollectiongenerator" with the" \ 87 | ".qhcp project file in $(BUILDDIR)/qthelp, like this:" 88 | @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/templated_docs.qhcp" 89 | @echo "To view the help file:" 90 | @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/templated_docs.qhc" 91 | 92 | devhelp: 93 | $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp 94 | @echo 95 | @echo "Build finished." 96 | @echo "To view the help file:" 97 | @echo "# mkdir -p $$HOME/.local/share/devhelp/templated_docs" 98 | @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/templated_docs" 99 | @echo "# devhelp" 100 | 101 | epub: 102 | $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub 103 | @echo 104 | @echo "Build finished. The epub file is in $(BUILDDIR)/epub." 105 | 106 | latex: 107 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 108 | @echo 109 | @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." 110 | @echo "Run \`make' in that directory to run these through (pdf)latex" \ 111 | "(use \`make latexpdf' here to do that automatically)." 112 | 113 | latexpdf: 114 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 115 | @echo "Running LaTeX files through pdflatex..." 116 | $(MAKE) -C $(BUILDDIR)/latex all-pdf 117 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 118 | 119 | latexpdfja: 120 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 121 | @echo "Running LaTeX files through platex and dvipdfmx..." 122 | $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja 123 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 124 | 125 | text: 126 | $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text 127 | @echo 128 | @echo "Build finished. The text files are in $(BUILDDIR)/text." 129 | 130 | man: 131 | $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man 132 | @echo 133 | @echo "Build finished. The manual pages are in $(BUILDDIR)/man." 134 | 135 | texinfo: 136 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 137 | @echo 138 | @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." 139 | @echo "Run \`make' in that directory to run these through makeinfo" \ 140 | "(use \`make info' here to do that automatically)." 141 | 142 | info: 143 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 144 | @echo "Running Texinfo files through makeinfo..." 145 | make -C $(BUILDDIR)/texinfo info 146 | @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." 147 | 148 | gettext: 149 | $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale 150 | @echo 151 | @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." 152 | 153 | changes: 154 | $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes 155 | @echo 156 | @echo "The overview file is in $(BUILDDIR)/changes." 157 | 158 | linkcheck: 159 | $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck 160 | @echo 161 | @echo "Link check complete; look for any errors in the above output " \ 162 | "or in $(BUILDDIR)/linkcheck/output.txt." 163 | 164 | doctest: 165 | $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest 166 | @echo "Testing of doctests in the sources finished, look at the " \ 167 | "results in $(BUILDDIR)/doctest/output.txt." 168 | 169 | xml: 170 | $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml 171 | @echo 172 | @echo "Build finished. The XML files are in $(BUILDDIR)/xml." 173 | 174 | pseudoxml: 175 | $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml 176 | @echo 177 | @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml." 178 | -------------------------------------------------------------------------------- /docs/conf.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # 4 | # templated_docs documentation build configuration file, created by 5 | # sphinx-quickstart on Tue Jul 9 22:26:36 2013. 6 | # 7 | # This file is execfile()d with the current directory set to its 8 | # containing dir. 9 | # 10 | # Note that not all possible configuration values are present in this 11 | # autogenerated file. 12 | # 13 | # All configuration values have a default; values that are commented out 14 | # serve to show the default. 15 | 16 | import sys 17 | import os 18 | 19 | # If extensions (or modules to document with autodoc) are in another 20 | # directory, add these directories to sys.path here. If the directory is 21 | # relative to the documentation root, use os.path.abspath to make it 22 | # absolute, like shown here. 23 | #sys.path.insert(0, os.path.abspath('.')) 24 | 25 | # Get the project root dir, which is the parent dir of this 26 | cwd = os.getcwd() 27 | project_root = os.path.dirname(cwd) 28 | 29 | # Insert the project root dir as the first element in the PYTHONPATH. 30 | # This lets us ensure that the source package is imported, and that its 31 | # version is used. 32 | sys.path.insert(0, project_root) 33 | 34 | import templated_docs 35 | 36 | # -- General configuration --------------------------------------------- 37 | 38 | # If your documentation needs a minimal Sphinx version, state it here. 39 | #needs_sphinx = '1.0' 40 | 41 | # Add any Sphinx extension module names here, as strings. They can be 42 | # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom ones. 43 | extensions = ['sphinx.ext.autodoc', 'sphinx.ext.viewcode'] 44 | 45 | # Add any paths that contain templates here, relative to this directory. 46 | templates_path = ['_templates'] 47 | 48 | # The suffix of source filenames. 49 | source_suffix = '.rst' 50 | 51 | # The encoding of source files. 52 | #source_encoding = 'utf-8-sig' 53 | 54 | # The master toctree document. 55 | master_doc = 'index' 56 | 57 | # General information about the project. 58 | project = u'Templated-docs' 59 | copyright = u"2016, Alex Morozov" 60 | 61 | # The version info for the project you're documenting, acts as replacement 62 | # for |version| and |release|, also used in various other places throughout 63 | # the built documents. 64 | # 65 | # The short X.Y version. 66 | version = templated_docs.__version__ 67 | # The full version, including alpha/beta/rc tags. 68 | release = templated_docs.__version__ 69 | 70 | # The language for content autogenerated by Sphinx. Refer to documentation 71 | # for a list of supported languages. 72 | #language = None 73 | 74 | # There are two options for replacing |today|: either, you set today to 75 | # some non-false value, then it is used: 76 | #today = '' 77 | # Else, today_fmt is used as the format for a strftime call. 78 | #today_fmt = '%B %d, %Y' 79 | 80 | # List of patterns, relative to source directory, that match files and 81 | # directories to ignore when looking for source files. 82 | exclude_patterns = ['_build'] 83 | 84 | # The reST default role (used for this markup: `text`) to use for all 85 | # documents. 86 | #default_role = None 87 | 88 | # If true, '()' will be appended to :func: etc. cross-reference text. 89 | #add_function_parentheses = True 90 | 91 | # If true, the current module name will be prepended to all description 92 | # unit titles (such as .. function::). 93 | #add_module_names = True 94 | 95 | # If true, sectionauthor and moduleauthor directives will be shown in the 96 | # output. They are ignored by default. 97 | #show_authors = False 98 | 99 | # The name of the Pygments (syntax highlighting) style to use. 100 | pygments_style = 'sphinx' 101 | 102 | # A list of ignored prefixes for module index sorting. 103 | #modindex_common_prefix = [] 104 | 105 | # If true, keep warnings as "system message" paragraphs in the built 106 | # documents. 107 | #keep_warnings = False 108 | 109 | 110 | # -- Options for HTML output ------------------------------------------- 111 | 112 | # The theme to use for HTML and HTML Help pages. See the documentation for 113 | # a list of builtin themes. 114 | html_theme = 'default' 115 | 116 | # Theme options are theme-specific and customize the look and feel of a 117 | # theme further. For a list of options available for each theme, see the 118 | # documentation. 119 | #html_theme_options = {} 120 | 121 | # Add any paths that contain custom themes here, relative to this directory. 122 | #html_theme_path = [] 123 | 124 | # The name for this set of Sphinx documents. If None, it defaults to 125 | # " v documentation". 126 | #html_title = None 127 | 128 | # A shorter title for the navigation bar. Default is the same as 129 | # html_title. 130 | #html_short_title = None 131 | 132 | # The name of an image file (relative to this directory) to place at the 133 | # top of the sidebar. 134 | #html_logo = None 135 | 136 | # The name of an image file (within the static path) to use as favicon 137 | # of the docs. This file should be a Windows icon file (.ico) being 138 | # 16x16 or 32x32 pixels large. 139 | #html_favicon = None 140 | 141 | # Add any paths that contain custom static files (such as style sheets) 142 | # here, relative to this directory. They are copied after the builtin 143 | # static files, so a file named "default.css" will overwrite the builtin 144 | # "default.css". 145 | html_static_path = ['_static'] 146 | 147 | # If not '', a 'Last updated on:' timestamp is inserted at every page 148 | # bottom, using the given strftime format. 149 | #html_last_updated_fmt = '%b %d, %Y' 150 | 151 | # If true, SmartyPants will be used to convert quotes and dashes to 152 | # typographically correct entities. 153 | #html_use_smartypants = True 154 | 155 | # Custom sidebar templates, maps document names to template names. 156 | #html_sidebars = {} 157 | 158 | # Additional templates that should be rendered to pages, maps page names 159 | # to template names. 160 | #html_additional_pages = {} 161 | 162 | # If false, no module index is generated. 163 | #html_domain_indices = True 164 | 165 | # If false, no index is generated. 166 | #html_use_index = True 167 | 168 | # If true, the index is split into individual pages for each letter. 169 | #html_split_index = False 170 | 171 | # If true, links to the reST sources are added to the pages. 172 | #html_show_sourcelink = True 173 | 174 | # If true, "Created using Sphinx" is shown in the HTML footer. 175 | # Default is True. 176 | #html_show_sphinx = True 177 | 178 | # If true, "(C) Copyright ..." is shown in the HTML footer. 179 | # Default is True. 180 | #html_show_copyright = True 181 | 182 | # If true, an OpenSearch description file will be output, and all pages 183 | # will contain a tag referring to it. The value of this option 184 | # must be the base URL from which the finished HTML is served. 185 | #html_use_opensearch = '' 186 | 187 | # This is the file name suffix for HTML files (e.g. ".xhtml"). 188 | #html_file_suffix = None 189 | 190 | # Output file base name for HTML help builder. 191 | htmlhelp_basename = 'templated_docsdoc' 192 | 193 | 194 | # -- Options for LaTeX output ------------------------------------------ 195 | 196 | latex_elements = { 197 | # The paper size ('letterpaper' or 'a4paper'). 198 | #'papersize': 'letterpaper', 199 | 200 | # The font size ('10pt', '11pt' or '12pt'). 201 | #'pointsize': '10pt', 202 | 203 | # Additional stuff for the LaTeX preamble. 204 | #'preamble': '', 205 | } 206 | 207 | # Grouping the document tree into LaTeX files. List of tuples 208 | # (source start file, target name, title, author, documentclass 209 | # [howto/manual]). 210 | latex_documents = [ 211 | ('index', 'templated_docs.tex', 212 | u'Templated-docs Documentation', 213 | u'Alex Morozov', 'manual'), 214 | ] 215 | 216 | # The name of an image file (relative to this directory) to place at 217 | # the top of the title page. 218 | #latex_logo = None 219 | 220 | # For "manual" documents, if this is true, then toplevel headings 221 | # are parts, not chapters. 222 | #latex_use_parts = False 223 | 224 | # If true, show page references after internal links. 225 | #latex_show_pagerefs = False 226 | 227 | # If true, show URL addresses after external links. 228 | #latex_show_urls = False 229 | 230 | # Documents to append as an appendix to all manuals. 231 | #latex_appendices = [] 232 | 233 | # If false, no module index is generated. 234 | #latex_domain_indices = True 235 | 236 | 237 | # -- Options for manual page output ------------------------------------ 238 | 239 | # One entry per manual page. List of tuples 240 | # (source start file, name, description, authors, manual section). 241 | man_pages = [ 242 | ('index', 'templated_docs', 243 | u'Templated-docs Documentation', 244 | [u'Alex Morozov'], 1) 245 | ] 246 | 247 | # If true, show URL addresses after external links. 248 | #man_show_urls = False 249 | 250 | 251 | # -- Options for Texinfo output ---------------------------------------- 252 | 253 | # Grouping the document tree into Texinfo files. List of tuples 254 | # (source start file, target name, title, author, 255 | # dir menu entry, description, category) 256 | texinfo_documents = [ 257 | ('index', 'templated_docs', 258 | u'Templated-docs Documentation', 259 | u'Alex Morozov', 260 | 'templated_docs', 261 | 'One line description of project.', 262 | 'Miscellaneous'), 263 | ] 264 | 265 | # Documents to append as an appendix to all manuals. 266 | #texinfo_appendices = [] 267 | 268 | # If false, no module index is generated. 269 | #texinfo_domain_indices = True 270 | 271 | # How to display URL addresses: 'footnote', 'no', or 'inline'. 272 | #texinfo_show_urls = 'footnote' 273 | 274 | # If true, do not generate a @detailmenu in the "Top" node's menu. 275 | #texinfo_no_detailmenu = False 276 | -------------------------------------------------------------------------------- /docs/document-template.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alexmorozov/templated-docs/c2bd2d245b220e96d7533267ddd7ef77970b0c74/docs/document-template.png -------------------------------------------------------------------------------- /docs/generated-document.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alexmorozov/templated-docs/c2bd2d245b220e96d7533267ddd7ef77970b0c74/docs/generated-document.png -------------------------------------------------------------------------------- /docs/http.rst: -------------------------------------------------------------------------------- 1 | Serving generated documents over HTTP 2 | ===================================== 3 | 4 | A common task is to serve user a created file. To facilitate this, a handy ``FileResponse`` response class is available:: 5 | 6 | from templated_docs.http import FileResponse 7 | 8 | def your_view(self): 9 | filename = get_my_document() 10 | return FileResponse(filename, visible_name='document.pdf') 11 | 12 | A ``FileResponse`` constructor is a subclass of Django's ``HttpResponse``, providing the following arguments: 13 | 14 | * ``actual_file`` - the real filename to serve 15 | * ``visible_name`` - the name a user will see in the browser 16 | * ``delete`` - set this to `False` to skip file deletion 17 | 18 | .. Important:: 19 | The `actual_file` **is deleted by default** after being served, as usually this is the wanted behaviour. To keep the file, pass the ``delete=False`` argument to the ``HttpResponse`` constructor. 20 | -------------------------------------------------------------------------------- /docs/index.rst: -------------------------------------------------------------------------------- 1 | .. templated_docs documentation master file, created by 2 | sphinx-quickstart on Tue Jul 9 22:26:36 2013. 3 | You can adapt this file completely to your liking, but it should at least 4 | contain the root `toctree` directive. 5 | 6 | Templated-docs: office documents for Django 7 | =========================================== 8 | 9 | **Templated-docs** is a Django package that allows you to generate documents, 10 | including texts, spreadsheets and presentations, from templates. It utilises 11 | LibreOffice as an underlying conversion document mechanism. 12 | 13 | Features 14 | -------- 15 | 16 | * Generate any LibreOffice-supported document from within Django. 17 | * Use Django template language inside office documents. 18 | * Create custom generation management commands to integrate with other systems. 19 | 20 | 21 | Installation 22 | ------------ 23 | 24 | To install templated-docs: 25 | 26 | 1. Make sure you have LibreOffice >= 4.3.0 installed on the same machine 27 | 2. Install a package with ``pip install templated-docs`` 28 | 3. Add ``templated_docs`` to ``INSTALLED_APPS`` 29 | 30 | .. include:: partial/libffi-warning.rst 31 | 32 | Usage 33 | ----- 34 | 35 | To generate a document from a template ``sample.odt`` you can write a view 36 | like this: 37 | 38 | .. code:: python 39 | 40 | from templated_docs import fill_template 41 | from templated_docs.http import FileResponse 42 | 43 | def get_document(request): 44 | """ 45 | A view to get a document filled with context variables. 46 | """ 47 | context = {'user': request.user, 'foo': 'bar'} 48 | filename = fill_template('sample.odt', context, output_format='pdf') 49 | visible_filename = 'greeting.pdf' 50 | return FileResponse(filename, visible_filename) 51 | 52 | ``templated_docs.fill_template(template_name, context, output_format='odt')`` 53 | Fill a template ``template_name`` using a ``context`` dictionary as a context, optionally converting it to the ``output_format``. Returns a filename of a generated file. 54 | 55 | 56 | More information 57 | ---------------- 58 | 59 | .. toctree:: 60 | :maxdepth: 2 61 | 62 | templates 63 | templatetags 64 | http 65 | management-commands 66 | settings 67 | -------------------------------------------------------------------------------- /docs/looping-sample.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alexmorozov/templated-docs/c2bd2d245b220e96d7533267ddd7ef77970b0c74/docs/looping-sample.png -------------------------------------------------------------------------------- /docs/make.bat: -------------------------------------------------------------------------------- 1 | @ECHO OFF 2 | 3 | REM Command file for Sphinx documentation 4 | 5 | if "%SPHINXBUILD%" == "" ( 6 | set SPHINXBUILD=sphinx-build 7 | ) 8 | set BUILDDIR=_build 9 | set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% . 10 | set I18NSPHINXOPTS=%SPHINXOPTS% . 11 | if NOT "%PAPER%" == "" ( 12 | set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS% 13 | set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS% 14 | ) 15 | 16 | if "%1" == "" goto help 17 | 18 | if "%1" == "help" ( 19 | :help 20 | echo.Please use `make ^` where ^ is one of 21 | echo. html to make standalone HTML files 22 | echo. dirhtml to make HTML files named index.html in directories 23 | echo. singlehtml to make a single large HTML file 24 | echo. pickle to make pickle files 25 | echo. json to make JSON files 26 | echo. htmlhelp to make HTML files and a HTML help project 27 | echo. qthelp to make HTML files and a qthelp project 28 | echo. devhelp to make HTML files and a Devhelp project 29 | echo. epub to make an epub 30 | echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter 31 | echo. text to make text files 32 | echo. man to make manual pages 33 | echo. texinfo to make Texinfo files 34 | echo. gettext to make PO message catalogs 35 | echo. changes to make an overview over all changed/added/deprecated items 36 | echo. xml to make Docutils-native XML files 37 | echo. pseudoxml to make pseudoxml-XML files for display purposes 38 | echo. linkcheck to check all external links for integrity 39 | echo. doctest to run all doctests embedded in the documentation if enabled 40 | goto end 41 | ) 42 | 43 | if "%1" == "clean" ( 44 | for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i 45 | del /q /s %BUILDDIR%\* 46 | goto end 47 | ) 48 | 49 | 50 | %SPHINXBUILD% 2> nul 51 | if errorlevel 9009 ( 52 | echo. 53 | echo.The 'sphinx-build' command was not found. Make sure you have Sphinx 54 | echo.installed, then set the SPHINXBUILD environment variable to point 55 | echo.to the full path of the 'sphinx-build' executable. Alternatively you 56 | echo.may add the Sphinx directory to PATH. 57 | echo. 58 | echo.If you don't have Sphinx installed, grab it from 59 | echo.http://sphinx-doc.org/ 60 | exit /b 1 61 | ) 62 | 63 | if "%1" == "html" ( 64 | %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html 65 | if errorlevel 1 exit /b 1 66 | echo. 67 | echo.Build finished. The HTML pages are in %BUILDDIR%/html. 68 | goto end 69 | ) 70 | 71 | if "%1" == "dirhtml" ( 72 | %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml 73 | if errorlevel 1 exit /b 1 74 | echo. 75 | echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml. 76 | goto end 77 | ) 78 | 79 | if "%1" == "singlehtml" ( 80 | %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml 81 | if errorlevel 1 exit /b 1 82 | echo. 83 | echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml. 84 | goto end 85 | ) 86 | 87 | if "%1" == "pickle" ( 88 | %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle 89 | if errorlevel 1 exit /b 1 90 | echo. 91 | echo.Build finished; now you can process the pickle files. 92 | goto end 93 | ) 94 | 95 | if "%1" == "json" ( 96 | %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json 97 | if errorlevel 1 exit /b 1 98 | echo. 99 | echo.Build finished; now you can process the JSON files. 100 | goto end 101 | ) 102 | 103 | if "%1" == "htmlhelp" ( 104 | %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp 105 | if errorlevel 1 exit /b 1 106 | echo. 107 | echo.Build finished; now you can run HTML Help Workshop with the ^ 108 | .hhp project file in %BUILDDIR%/htmlhelp. 109 | goto end 110 | ) 111 | 112 | if "%1" == "qthelp" ( 113 | %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp 114 | if errorlevel 1 exit /b 1 115 | echo. 116 | echo.Build finished; now you can run "qcollectiongenerator" with the ^ 117 | .qhcp project file in %BUILDDIR%/qthelp, like this: 118 | echo.^> qcollectiongenerator %BUILDDIR%\qthelp\templated_docs.qhcp 119 | echo.To view the help file: 120 | echo.^> assistant -collectionFile %BUILDDIR%\qthelp\templated_docs.ghc 121 | goto end 122 | ) 123 | 124 | if "%1" == "devhelp" ( 125 | %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp 126 | if errorlevel 1 exit /b 1 127 | echo. 128 | echo.Build finished. 129 | goto end 130 | ) 131 | 132 | if "%1" == "epub" ( 133 | %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub 134 | if errorlevel 1 exit /b 1 135 | echo. 136 | echo.Build finished. The epub file is in %BUILDDIR%/epub. 137 | goto end 138 | ) 139 | 140 | if "%1" == "latex" ( 141 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex 142 | if errorlevel 1 exit /b 1 143 | echo. 144 | echo.Build finished; the LaTeX files are in %BUILDDIR%/latex. 145 | goto end 146 | ) 147 | 148 | if "%1" == "latexpdf" ( 149 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex 150 | cd %BUILDDIR%/latex 151 | make all-pdf 152 | cd %BUILDDIR%/.. 153 | echo. 154 | echo.Build finished; the PDF files are in %BUILDDIR%/latex. 155 | goto end 156 | ) 157 | 158 | if "%1" == "latexpdfja" ( 159 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex 160 | cd %BUILDDIR%/latex 161 | make all-pdf-ja 162 | cd %BUILDDIR%/.. 163 | echo. 164 | echo.Build finished; the PDF files are in %BUILDDIR%/latex. 165 | goto end 166 | ) 167 | 168 | if "%1" == "text" ( 169 | %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text 170 | if errorlevel 1 exit /b 1 171 | echo. 172 | echo.Build finished. The text files are in %BUILDDIR%/text. 173 | goto end 174 | ) 175 | 176 | if "%1" == "man" ( 177 | %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man 178 | if errorlevel 1 exit /b 1 179 | echo. 180 | echo.Build finished. The manual pages are in %BUILDDIR%/man. 181 | goto end 182 | ) 183 | 184 | if "%1" == "texinfo" ( 185 | %SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo 186 | if errorlevel 1 exit /b 1 187 | echo. 188 | echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo. 189 | goto end 190 | ) 191 | 192 | if "%1" == "gettext" ( 193 | %SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale 194 | if errorlevel 1 exit /b 1 195 | echo. 196 | echo.Build finished. The message catalogs are in %BUILDDIR%/locale. 197 | goto end 198 | ) 199 | 200 | if "%1" == "changes" ( 201 | %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes 202 | if errorlevel 1 exit /b 1 203 | echo. 204 | echo.The overview file is in %BUILDDIR%/changes. 205 | goto end 206 | ) 207 | 208 | if "%1" == "linkcheck" ( 209 | %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck 210 | if errorlevel 1 exit /b 1 211 | echo. 212 | echo.Link check complete; look for any errors in the above output ^ 213 | or in %BUILDDIR%/linkcheck/output.txt. 214 | goto end 215 | ) 216 | 217 | if "%1" == "doctest" ( 218 | %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest 219 | if errorlevel 1 exit /b 1 220 | echo. 221 | echo.Testing of doctests in the sources finished, look at the ^ 222 | results in %BUILDDIR%/doctest/output.txt. 223 | goto end 224 | ) 225 | 226 | if "%1" == "xml" ( 227 | %SPHINXBUILD% -b xml %ALLSPHINXOPTS% %BUILDDIR%/xml 228 | if errorlevel 1 exit /b 1 229 | echo. 230 | echo.Build finished. The XML files are in %BUILDDIR%/xml. 231 | goto end 232 | ) 233 | 234 | if "%1" == "pseudoxml" ( 235 | %SPHINXBUILD% -b pseudoxml %ALLSPHINXOPTS% %BUILDDIR%/pseudoxml 236 | if errorlevel 1 exit /b 1 237 | echo. 238 | echo.Build finished. The pseudo-XML files are in %BUILDDIR%/pseudoxml. 239 | goto end 240 | ) 241 | 242 | :end 243 | -------------------------------------------------------------------------------- /docs/management-commands.rst: -------------------------------------------------------------------------------- 1 | Management commands for generating documents 2 | ============================================ 3 | 4 | Todo: describe ``templated_docs.management.base.DocumentGenerationCommand``. 5 | -------------------------------------------------------------------------------- /docs/partial/libffi-warning.rst: -------------------------------------------------------------------------------- 1 | If you are using cpython you may need the ``libffi`` development package in 2 | order to compile this module's dependencies. 3 | 4 | * **Ubuntu**: ``apt-get install libffi-dev`` 5 | * **MacOS**: ``brew install libffi`` 6 | -------------------------------------------------------------------------------- /docs/settings.rst: -------------------------------------------------------------------------------- 1 | Templated-docs settings 2 | ======================= 3 | 4 | Some settings can be utilised to alter the package behaviour: 5 | 6 | * **TEMPLATED_DOCS_LIBREOFFICE_PATH** - a path to the LibreOffice installation's `program` folder. Defaults to ``/usr/share/libreoffice/program``. 7 | -------------------------------------------------------------------------------- /docs/templates.rst: -------------------------------------------------------------------------------- 1 | Working with document templates 2 | =============================== 3 | 4 | Supported formats 5 | ----------------- 6 | 7 | .. Important:: 8 | The templates themselves **must** be in on of the OpenDocument formats: ``.odt``, ``.ods``, ``.odp`` or ``.odg``. 9 | 10 | Templated-docs can generate documents in any format LibreOffice itself supports. For the moment they are: 11 | 12 | **Text documents**: doc, docx, fodt, html, odt, ott, pdf, txt, xhtml, png 13 | 14 | **Spreadsheets**: csv, fods, html, ods, ots, pdf, xhtml, xls, xlsx, png 15 | 16 | **Presentations**: fodp, html, odg, odp, otp, pdf, potm, pot, pptx, pps, ppt, svg, swf, xhtml, png 17 | 18 | **Drawings**: fodg, html, odg, pdf, svg, swf, xhtml, png 19 | 20 | 21 | Where to put templates 22 | ---------------------- 23 | 24 | Templated-docs uses a standard Django template discovery mechanism, so you should place your documents at a path where other templates reside. Usually it's either a ``templates`` directory at the project level, or ``templates`` folders in each applications. 25 | 26 | 27 | What subset of templating language is supported 28 | ----------------------------------------------- 29 | 30 | Django templating language is fully supported, including filters and tags. Keep in mind, though, that in order to use custom template tags you should load them first using a standard ``{% load %}`` tag. 31 | 32 | 33 | Looping 34 | ------- 35 | 36 | Generating lines in loops is supported via the standard ``{% for %}`` tag. Here's the picture that illustrates the concept: 37 | 38 | .. image:: looping-sample.png 39 | :align: center 40 | -------------------------------------------------------------------------------- /docs/templatetags.rst: -------------------------------------------------------------------------------- 1 | Useful template tags 2 | ==================== 3 | 4 | To use these template tags, load them first with ``{% load templated_docs_tags %}``. 5 | 6 | lolinebreaks 7 | ------------ 8 | 9 | To keep newlines in a multiline text, use this tag instead of a default ``linebreaks`` filter:: 10 | 11 | {{ variable|lolinebreaks }} 12 | 13 | image 14 | ----- 15 | 16 | Inserting images from models' ImageField is supported. Assuming you have a ``claim`` model instance with a ``stamp`` ImageField in it:: 17 | 18 | {% image claim.stamp %} 19 | -------------------------------------------------------------------------------- /example/db.sqlite3: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alexmorozov/templated-docs/c2bd2d245b220e96d7533267ddd7ef77970b0c74/example/db.sqlite3 -------------------------------------------------------------------------------- /example/example/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alexmorozov/templated-docs/c2bd2d245b220e96d7533267ddd7ef77970b0c74/example/example/__init__.py -------------------------------------------------------------------------------- /example/example/settings.py: -------------------------------------------------------------------------------- 1 | """ 2 | Django settings for example project. 3 | 4 | Generated by 'django-admin startproject' using Django 1.9.7. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/1.9/topics/settings/ 8 | 9 | For the full list of settings and their values, see 10 | https://docs.djangoproject.com/en/1.9/ref/settings/ 11 | """ 12 | 13 | import os 14 | import os.path 15 | 16 | # Build paths inside the project like this: os.path.join(BASE_DIR, ...) 17 | BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 18 | 19 | 20 | def path(*bits): 21 | return os.path.join(BASE_DIR, *bits) 22 | 23 | 24 | # Quick-start development settings - unsuitable for production 25 | # See https://docs.djangoproject.com/en/1.9/howto/deployment/checklist/ 26 | 27 | # SECURITY WARNING: keep the secret key used in production secret! 28 | SECRET_KEY = '+j3$qetw$tx^6)db-es91#@2!ru5j!7mfahym)b&j1z0eamlm5' 29 | 30 | # SECURITY WARNING: don't run with debug turned on in production! 31 | DEBUG = True 32 | 33 | ALLOWED_HOSTS = [] 34 | 35 | 36 | # Application definition 37 | 38 | INSTALLED_APPS = [ 39 | 'django.contrib.admin', 40 | 'django.contrib.auth', 41 | 'django.contrib.contenttypes', 42 | 'django.contrib.sessions', 43 | 'django.contrib.messages', 44 | 'django.contrib.staticfiles', 45 | 'templated_docs', 46 | 'invoices', 47 | ] 48 | 49 | MIDDLEWARE_CLASSES = [ 50 | 'django.middleware.security.SecurityMiddleware', 51 | 'django.contrib.sessions.middleware.SessionMiddleware', 52 | 'django.middleware.common.CommonMiddleware', 53 | 'django.middleware.csrf.CsrfViewMiddleware', 54 | 'django.contrib.auth.middleware.AuthenticationMiddleware', 55 | 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 56 | 'django.contrib.messages.middleware.MessageMiddleware', 57 | 'django.middleware.clickjacking.XFrameOptionsMiddleware', 58 | ] 59 | 60 | ROOT_URLCONF = 'example.urls' 61 | 62 | TEMPLATES = [ 63 | { 64 | 'BACKEND': 'django.template.backends.django.DjangoTemplates', 65 | 'DIRS': [path('example/templates'), ], 66 | 'APP_DIRS': True, 67 | 'OPTIONS': { 68 | 'context_processors': [ 69 | 'django.template.context_processors.debug', 70 | 'django.template.context_processors.request', 71 | 'django.contrib.auth.context_processors.auth', 72 | 'django.contrib.messages.context_processors.messages', 73 | ], 74 | }, 75 | }, 76 | ] 77 | 78 | WSGI_APPLICATION = 'example.wsgi.application' 79 | 80 | 81 | # Database 82 | # https://docs.djangoproject.com/en/1.9/ref/settings/#databases 83 | 84 | DATABASES = { 85 | 'default': { 86 | 'ENGINE': 'django.db.backends.sqlite3', 87 | 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), 88 | } 89 | } 90 | 91 | 92 | # Password validation 93 | # https://docs.djangoproject.com/en/1.9/ref/settings/#auth-password-validators 94 | 95 | AUTH_PASSWORD_VALIDATORS = [ 96 | { 97 | 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', 98 | }, 99 | { 100 | 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', 101 | }, 102 | { 103 | 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', 104 | }, 105 | { 106 | 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', 107 | }, 108 | ] 109 | 110 | 111 | # Internationalization 112 | # https://docs.djangoproject.com/en/1.9/topics/i18n/ 113 | 114 | LANGUAGE_CODE = 'en-us' 115 | 116 | TIME_ZONE = 'UTC' 117 | 118 | USE_I18N = True 119 | 120 | USE_L10N = True 121 | 122 | USE_TZ = True 123 | 124 | 125 | # Static files (CSS, JavaScript, Images) 126 | # https://docs.djangoproject.com/en/1.9/howto/static-files/ 127 | 128 | STATIC_URL = '/static/' 129 | -------------------------------------------------------------------------------- /example/example/urls.py: -------------------------------------------------------------------------------- 1 | from django.conf.urls import url 2 | 3 | from invoices.views import invoice_view 4 | 5 | 6 | urlpatterns = [ 7 | url(r'^$', invoice_view), 8 | ] 9 | -------------------------------------------------------------------------------- /example/example/wsgi.py: -------------------------------------------------------------------------------- 1 | """ 2 | WSGI config for example project. 3 | 4 | It exposes the WSGI callable as a module-level variable named ``application``. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/1.9/howto/deployment/wsgi/ 8 | """ 9 | 10 | import os 11 | 12 | from django.core.wsgi import get_wsgi_application 13 | 14 | os.environ.setdefault("DJANGO_SETTINGS_MODULE", "example.settings") 15 | 16 | application = get_wsgi_application() 17 | -------------------------------------------------------------------------------- /example/invoices/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alexmorozov/templated-docs/c2bd2d245b220e96d7533267ddd7ef77970b0c74/example/invoices/__init__.py -------------------------------------------------------------------------------- /example/invoices/admin.py: -------------------------------------------------------------------------------- 1 | from django.contrib import admin 2 | 3 | # Register your models here. 4 | -------------------------------------------------------------------------------- /example/invoices/apps.py: -------------------------------------------------------------------------------- 1 | from django.apps import AppConfig 2 | 3 | 4 | class InvoicesConfig(AppConfig): 5 | name = 'invoices' 6 | -------------------------------------------------------------------------------- /example/invoices/forms.py: -------------------------------------------------------------------------------- 1 | #--coding: utf8-- 2 | 3 | from django import forms 4 | 5 | from invoices.models import Customer 6 | 7 | 8 | class InvoiceForm(forms.Form): 9 | FORMAT_CHOICES = ( 10 | ('pdf', 'PDF'), 11 | ('docx', 'MS Word'), 12 | ('html', 'HTML'), 13 | ) 14 | number = forms.CharField(label='Invoice #') 15 | customer = forms.ModelChoiceField(queryset=Customer.objects.all()) 16 | subject = forms.CharField() 17 | amount = forms.DecimalField() 18 | format = forms.ChoiceField(choices=FORMAT_CHOICES) 19 | -------------------------------------------------------------------------------- /example/invoices/migrations/0001_initial.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Generated by Django 1.9.7 on 2016-07-14 10:29 3 | from __future__ import unicode_literals 4 | 5 | from django.db import migrations, models 6 | 7 | 8 | def create_customers(apps, schema_editor): 9 | Customer = apps.get_model('invoices', 'Customer') 10 | Customer.objects.create(name='John Doe', address='Some street\nSome town') 11 | Customer.objects.create(name='Apple', address='Other street\nOther town') 12 | 13 | 14 | class Migration(migrations.Migration): 15 | 16 | initial = True 17 | 18 | dependencies = [ 19 | ] 20 | 21 | operations = [ 22 | migrations.CreateModel( 23 | name='Customer', 24 | fields=[ 25 | ('id', models.AutoField(auto_created=True, primary_key=True, 26 | serialize=False, verbose_name='ID')), 27 | ('name', models.CharField(max_length=200)), 28 | ('address', models.TextField()), 29 | ], 30 | ), 31 | migrations.RunPython(create_customers), 32 | ] 33 | -------------------------------------------------------------------------------- /example/invoices/migrations/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alexmorozov/templated-docs/c2bd2d245b220e96d7533267ddd7ef77970b0c74/example/invoices/migrations/__init__.py -------------------------------------------------------------------------------- /example/invoices/models.py: -------------------------------------------------------------------------------- 1 | from django.db import models 2 | 3 | 4 | class Customer(models.Model): 5 | name = models.CharField(max_length=200) 6 | address = models.TextField() 7 | 8 | def __str__(self): 9 | return self.name 10 | -------------------------------------------------------------------------------- /example/invoices/templates/invoices/form.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Print an invoice and get rich 8 | 9 | 10 | 11 | 12 | 13 | 14 | 18 | 19 | 20 |
21 |

Print an invoice and get rich (no guarantee)

22 |

23 | Fill out the form below and get a brand new document with your data! 24 |

25 |
26 | {% csrf_token %} 27 | {{ form.as_p }} 28 | 29 |
30 |
31 | 32 | 33 | 34 | 35 | 36 | -------------------------------------------------------------------------------- /example/invoices/templates/invoices/invoice.odt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alexmorozov/templated-docs/c2bd2d245b220e96d7533267ddd7ef77970b0c74/example/invoices/templates/invoices/invoice.odt -------------------------------------------------------------------------------- /example/invoices/tests.py: -------------------------------------------------------------------------------- 1 | from django.test import TestCase 2 | 3 | # Create your tests here. 4 | -------------------------------------------------------------------------------- /example/invoices/views.py: -------------------------------------------------------------------------------- 1 | #--coding: utf8-- 2 | 3 | from django.shortcuts import render 4 | 5 | from templated_docs import fill_template 6 | from templated_docs.http import FileResponse 7 | 8 | from invoices.forms import InvoiceForm 9 | 10 | 11 | def invoice_view(request): 12 | form = InvoiceForm(request.POST or None) 13 | 14 | if form.is_valid(): 15 | doctype = form.cleaned_data['format'] 16 | filename = fill_template( 17 | 'invoices/invoice.odt', form.cleaned_data, 18 | output_format=doctype) 19 | visible_filename = 'invoice.{}'.format(doctype) 20 | 21 | return FileResponse(filename, visible_filename) 22 | else: 23 | return render(request, 'invoices/form.html', {'form': form}) 24 | -------------------------------------------------------------------------------- /example/manage.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import os 4 | import os.path 5 | import sys 6 | 7 | if __name__ == "__main__": 8 | BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 9 | sys.path.append(BASE_DIR) 10 | os.environ.setdefault("DJANGO_SETTINGS_MODULE", "example.settings") 11 | from django.core.management import execute_from_command_line 12 | execute_from_command_line(sys.argv) 13 | -------------------------------------------------------------------------------- /requirements_dev.txt: -------------------------------------------------------------------------------- 1 | pip==8.1.2 2 | bumpversion==0.5.3 3 | wheel==0.29.0 4 | watchdog==0.8.3 5 | flake8==2.6.2 6 | tox==2.3.1 7 | coverage==4.1 8 | Sphinx>=1.4,<1.5 9 | cryptography==1.4 10 | PyYAML==3.11 11 | -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [bumpversion] 2 | current_version = 0.3.1 3 | commit = True 4 | tag = True 5 | tag_name = {new_version} 6 | 7 | [bumpversion:file:setup.py] 8 | search = version='{current_version}' 9 | replace = version='{new_version}' 10 | 11 | [bumpversion:file:templated_docs/__init__.py] 12 | search = __version__ = '{current_version}' 13 | replace = __version__ = '{new_version}' 14 | 15 | [wheel] 16 | universal = 1 17 | 18 | [flake8] 19 | exclude = docs 20 | 21 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | 5 | from setuptools import setup, find_packages 6 | 7 | 8 | with open('README.rst') as readme_file: 9 | readme = readme_file.read() 10 | 11 | with open('HISTORY.rst') as history_file: 12 | history = history_file.read() 13 | 14 | requirements = [ 15 | 'pylokit==0.8.1', 16 | 'django>=1.8,<1.11', 17 | ] 18 | 19 | test_requirements = [ 20 | # TODO: put package test requirements here 21 | ] 22 | 23 | setup( 24 | name='templated_docs', 25 | version='0.3.1', 26 | description=('Generate PDF, MS Word and Excel documents from templates ' 27 | 'in Django.'), 28 | long_description=readme + '\n\n' + history, 29 | author="Alex Morozov", 30 | author_email='alex@morozov.ca', 31 | url='https://github.com/alexmorozov/templated-docs', 32 | packages=find_packages(), 33 | include_package_data=True, 34 | install_requires=requirements, 35 | license="MIT license", 36 | zip_safe=False, 37 | keywords='templated_docs', 38 | classifiers=[ 39 | 'Development Status :: 2 - Pre-Alpha', 40 | 'Intended Audience :: Developers', 41 | 'License :: OSI Approved :: MIT License', 42 | 'Natural Language :: English', 43 | 'Programming Language :: Python :: 2', 44 | 'Programming Language :: Python :: 2.7', 45 | 'Programming Language :: Python :: 3', 46 | 'Programming Language :: Python :: 3.3', 47 | 'Programming Language :: Python :: 3.4', 48 | 'Programming Language :: Python :: 3.5', 49 | ], 50 | test_suite='tests.test_app.tests', 51 | tests_require=test_requirements 52 | ) 53 | -------------------------------------------------------------------------------- /templated_docs/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | from multiprocessing import Process, Queue 4 | import os.path 5 | import re 6 | from tempfile import NamedTemporaryFile 7 | import zipfile 8 | 9 | from django.conf import settings 10 | from django.template import Template 11 | 12 | try: 13 | # Django 1.9+ 14 | from django.template.exceptions import TemplateDoesNotExist 15 | except ImportError: 16 | from django.template import TemplateDoesNotExist 17 | 18 | from django.template import Context, engines 19 | 20 | from django.utils.encoding import smart_bytes, smart_str 21 | 22 | from pylokit import Office 23 | 24 | import logging 25 | log = logging.getLogger(__name__) 26 | 27 | __version__ = '0.3.1' 28 | 29 | 30 | IMAGES_CONTEXT_KEY = '_templated_docs_imgs' 31 | 32 | 33 | def _get_template_loaders(): 34 | """ 35 | Get all available template loaders for the Django engine. 36 | """ 37 | loaders = [] 38 | 39 | for loader_name in engines['django'].engine.loaders: 40 | loader = engines['django'].engine.find_template_loader(loader_name) 41 | if loader is not None and hasattr(loader, 'get_template_sources'): 42 | loaders.append(loader) 43 | return tuple(loaders) 44 | 45 | 46 | def fix_inline_tags(content): 47 | """ 48 | Replace broken entities within Django template constructs. 49 | 50 | MS Word likes to replace some entities just in case, and we end up with 51 | broken Django constructs. To remedy that, we find all the Django tags and 52 | variables and fix entities inside them. 53 | """ 54 | def repl(match): 55 | text = match.group(0) 56 | text = text.replace('', ' ') 57 | text = text.replace(''', "'") 58 | text = text.replace('"', '"') 59 | return re.sub(r'<[^>]+>', '', text) 60 | 61 | django_tag_re = r'(\{[\{\%].+?[\%\}]\})' 62 | return re.sub(django_tag_re, repl, content) 63 | 64 | 65 | def find_template_file(template_name): 66 | """ 67 | Return a full path to the specified template file. 68 | 69 | The key difference from the stock `find_template` is that we don't try to 70 | load a template in memory, because we'll deal with it ourselves. 71 | """ 72 | for loader in _get_template_loaders(): 73 | for origin in loader.get_template_sources(template_name, None): 74 | path = getattr(origin, 'name', origin) # Django <1.9 compatibility 75 | if os.path.exists(path): 76 | return path 77 | raise TemplateDoesNotExist(template_name) 78 | 79 | 80 | def _convert_subprocess(filename, format, result_queue): 81 | """ 82 | Subprocess helper to convert a file via LOKit. 83 | 84 | We need it until LO doesn't crash randomly after conversion, terminating 85 | the calling process as well. 86 | """ 87 | lo_path = getattr( 88 | settings, 89 | 'TEMPLATED_DOCS_LIBREOFFICE_PATH', 90 | '/usr/lib/libreoffice/program/') 91 | 92 | with Office(lo_path) as lo: 93 | conv_file = NamedTemporaryFile(delete=False, 94 | suffix='.%s' % format) 95 | with lo.documentLoad(filename) as doc: 96 | doc.saveAs(str(conv_file.name)) 97 | os.unlink(filename) 98 | result_queue.put(conv_file.name) 99 | 100 | 101 | def fill_template(template_name, context, output_format='odt'): 102 | """ 103 | Fill a document with data and convert it to the requested format. 104 | 105 | Returns an absolute path to the generated file. 106 | """ 107 | 108 | if not isinstance(context, Context): 109 | context = Context(context) 110 | 111 | context['output_format'] = output_format 112 | 113 | source_file = find_template_file(template_name) 114 | source_extension = os.path.splitext(source_file)[1] 115 | source = zipfile.ZipFile(source_file, 'r') 116 | 117 | dest_file = NamedTemporaryFile(delete=False, suffix=source_extension) 118 | dest = zipfile.ZipFile(dest_file, 'w') 119 | 120 | manifest_data = '' 121 | for name in source.namelist(): 122 | data = source.read(name) 123 | if name.endswith('.xml'): 124 | data = smart_str(data) 125 | 126 | if any(name.endswith(file) for file in ('content.xml', 'styles.xml')): 127 | template = Template(fix_inline_tags(data)) 128 | data = template.render(context) 129 | elif name == 'META-INF/manifest.xml': 130 | manifest_data = data[:-20] # Cut off the closing tag 131 | continue # We will append it at the very end 132 | dest.writestr(name, smart_bytes(data)) 133 | 134 | for _, image in context.dicts[0].get(IMAGES_CONTEXT_KEY, {}).items(): 135 | filename = os.path.basename(image.name) 136 | ext = os.path.splitext(filename)[1][1:] 137 | manifest_data += ('\n' 140 | ) % locals() 141 | image.open() 142 | dest.writestr('Pictures/%s' % filename, image.read()) 143 | image.close() 144 | 145 | manifest_data += '' 146 | dest.writestr('META-INF/manifest.xml', manifest_data) 147 | 148 | source.close() 149 | dest.close() 150 | 151 | if source_extension[1:] != output_format: 152 | results = Queue() 153 | convertor = Process(target=_convert_subprocess, 154 | args=(str(dest_file.name), output_format, results)) 155 | convertor.start() 156 | return results.get() 157 | else: 158 | return dest_file.name 159 | -------------------------------------------------------------------------------- /templated_docs/http.py: -------------------------------------------------------------------------------- 1 | # --coding: utf8-- 2 | 3 | import os 4 | import mimetypes 5 | 6 | from django.http import HttpResponse 7 | 8 | 9 | class FileResponse(HttpResponse): 10 | """ 11 | One-time HTTP response with a generated file. DELETES A FILE AFTERWARDS! 12 | """ 13 | def __init__(self, actual_file, visible_name, delete=True, 14 | *args, **kwargs): 15 | super(FileResponse, self).__init__(*args, **kwargs) 16 | 17 | self['Content-type'] = mimetypes.guess_type(actual_file)[0] 18 | self['Content-disposition'] = 'attachment; filename=%s' % visible_name 19 | with open(actual_file, 'rb') as f: 20 | self.content = f.read() 21 | self['Content-length'] = len(self.content) 22 | if delete: 23 | os.unlink(actual_file) 24 | -------------------------------------------------------------------------------- /templated_docs/management/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alexmorozov/templated-docs/c2bd2d245b220e96d7533267ddd7ef77970b0c74/templated_docs/management/__init__.py -------------------------------------------------------------------------------- /templated_docs/management/base.py: -------------------------------------------------------------------------------- 1 | # --coding: utf8-- 2 | 3 | import os 4 | 5 | from django.core.management.base import BaseCommand 6 | 7 | from templated_docs import fill_template 8 | 9 | 10 | class DocumentGenerationCommand(BaseCommand): 11 | """ 12 | A management command which generates a document using the context specified 13 | in the ``get_document_context()`` method. 14 | """ 15 | 16 | def add_arguments(self, parser): 17 | parser.add_argument('template_name', type=str) 18 | parser.add_argument('--format', type=str, default='odt', 19 | help='Convert a document to specified format') 20 | parser.add_argument('--output_file', type=str, default=None, 21 | help='Put the result into this file.') 22 | 23 | def handle(self, template_name, **options): 24 | output_format = options['format'] 25 | temp_name = fill_template( 26 | template_name, 27 | self.get_document_context(template_name, **options), 28 | output_format) 29 | 30 | out_file = options['output_file'] or temp_name 31 | if out_file != temp_name: 32 | os.rename(temp_name, out_file) 33 | print(out_file) 34 | 35 | def get_document_context(self, template_name, **options): 36 | """ 37 | Fill the context for passing in the document template. 38 | """ 39 | raise NotImplementedError( 40 | 'subclasses of GenerateDocumentCommand must provide a ' 41 | 'get_document_context() method') 42 | -------------------------------------------------------------------------------- /templated_docs/templatetags/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alexmorozov/templated-docs/c2bd2d245b220e96d7533267ddd7ef77970b0c74/templated_docs/templatetags/__init__.py -------------------------------------------------------------------------------- /templated_docs/templatetags/templated_docs_tags.py: -------------------------------------------------------------------------------- 1 | # --coding: utf8-- 2 | 3 | import os.path 4 | 5 | from django.db.models.fields.files import ImageFieldFile 6 | from django.utils.safestring import mark_safe 7 | from django.utils.html import escape 8 | from django import template 9 | register = template.Library() 10 | 11 | PIXEL_TO_CM = 0.00846666 12 | 13 | 14 | class ImageNode(template.Node): 15 | def __init__(self, value): 16 | self.value = template.Variable(value) 17 | 18 | def render(self, context): 19 | try: 20 | self.value = self.value.resolve(context) 21 | if not isinstance(self.value, ImageFieldFile): 22 | raise template.VariableDoesNotExist( 23 | 'Image argument should be an ImageField') 24 | images = context.dicts[0].setdefault('ootemplate_imgs', {}) 25 | 26 | id = len(images) 27 | z_index = id + 3 # Magic 28 | width = self.value.width * PIXEL_TO_CM 29 | height = self.value.height * PIXEL_TO_CM 30 | filename = os.path.basename(self.value.name) 31 | basename = os.path.splitext(filename)[0] 32 | 33 | images[self.value.path] = self.value 34 | return ('' 39 | '') % locals() 42 | except template.VariableDoesNotExist: 43 | return '' 44 | 45 | 46 | @register.tag 47 | def image(parser, token): 48 | """ 49 | Insert an image from a ImageField into a document. 50 | """ 51 | try: 52 | tag_name, value = token.split_contents() 53 | except ValueError: 54 | raise template.TemplateSyntaxError( 55 | '%r tag requires a file as an argument' % tag_name) 56 | return ImageNode(value) 57 | 58 | 59 | @register.filter 60 | def lolinebreaks(value): 61 | """ 62 | LibreOffice-flavored ``linebreaks`` filter. 63 | """ 64 | if not value: 65 | return '' 66 | paragraphs = [line for line in escape(value).splitlines()] 67 | return mark_safe(''.join(paragraphs)) 68 | -------------------------------------------------------------------------------- /tests/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | -------------------------------------------------------------------------------- /tests/manage.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import os 3 | import sys 4 | 5 | if __name__ == "__main__": 6 | os.environ.setdefault("DJANGO_SETTINGS_MODULE", "test_project.settings") 7 | 8 | from django.core.management import execute_from_command_line 9 | 10 | execute_from_command_line(sys.argv) 11 | -------------------------------------------------------------------------------- /tests/test_app/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alexmorozov/templated-docs/c2bd2d245b220e96d7533267ddd7ef77970b0c74/tests/test_app/__init__.py -------------------------------------------------------------------------------- /tests/test_app/admin.py: -------------------------------------------------------------------------------- 1 | from django.contrib import admin 2 | 3 | # Register your models here. 4 | -------------------------------------------------------------------------------- /tests/test_app/apps.py: -------------------------------------------------------------------------------- 1 | from django.apps import AppConfig 2 | 3 | 4 | class TestAppConfig(AppConfig): 5 | name = 'test_app' 6 | -------------------------------------------------------------------------------- /tests/test_app/migrations/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alexmorozov/templated-docs/c2bd2d245b220e96d7533267ddd7ef77970b0c74/tests/test_app/migrations/__init__.py -------------------------------------------------------------------------------- /tests/test_app/models.py: -------------------------------------------------------------------------------- 1 | from django.db import models 2 | 3 | # Create your models here. 4 | -------------------------------------------------------------------------------- /tests/test_app/templates/correct_template.odt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alexmorozov/templated-docs/c2bd2d245b220e96d7533267ddd7ef77970b0c74/tests/test_app/templates/correct_template.odt -------------------------------------------------------------------------------- /tests/test_app/tests.py: -------------------------------------------------------------------------------- 1 | # --coding: utf8-- 2 | 3 | import os 4 | 5 | from django.test import TestCase 6 | 7 | from templated_docs import fill_template 8 | 9 | 10 | class InternalsTestCase(TestCase): 11 | def test_fill_correct_template(self): 12 | """ 13 | Creating a document from a correct template doesn't raise any 14 | exception. 15 | """ 16 | filename = fill_template('correct_template.odt', {'name': 'John'}, 17 | output_format='pdf') 18 | os.unlink(filename) 19 | -------------------------------------------------------------------------------- /tests/test_app/views.py: -------------------------------------------------------------------------------- 1 | from django.shortcuts import render 2 | 3 | # Create your views here. 4 | -------------------------------------------------------------------------------- /tests/test_project/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alexmorozov/templated-docs/c2bd2d245b220e96d7533267ddd7ef77970b0c74/tests/test_project/__init__.py -------------------------------------------------------------------------------- /tests/test_project/settings.py: -------------------------------------------------------------------------------- 1 | """ 2 | Django settings for test_project project. 3 | 4 | Generated by 'django-admin startproject' using Django 1.9.7. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/1.9/topics/settings/ 8 | 9 | For the full list of settings and their values, see 10 | https://docs.djangoproject.com/en/1.9/ref/settings/ 11 | """ 12 | 13 | import os 14 | 15 | # Build paths inside the project like this: os.path.join(BASE_DIR, ...) 16 | BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 17 | 18 | 19 | TEMPLATED_DOCS_LIBREOFFICE_PATH = os.environ.get( 20 | 'LO_PATH', '/usr/lib/libreoffice/program/') 21 | 22 | 23 | # Quick-start development settings - unsuitable for production 24 | # See https://docs.djangoproject.com/en/1.9/howto/deployment/checklist/ 25 | 26 | # SECURITY WARNING: keep the secret key used in production secret! 27 | SECRET_KEY = '$r!+yaw2eflbyn%5*4r)0sy45pi9*m9gk*o64vuy)f83o_$84j' 28 | 29 | # SECURITY WARNING: don't run with debug turned on in production! 30 | DEBUG = True 31 | 32 | ALLOWED_HOSTS = [] 33 | 34 | 35 | # Application definition 36 | 37 | INSTALLED_APPS = [ 38 | 'django.contrib.admin', 39 | 'django.contrib.auth', 40 | 'django.contrib.contenttypes', 41 | 'django.contrib.sessions', 42 | 'django.contrib.messages', 43 | 'django.contrib.staticfiles', 44 | 'templated_docs', 45 | 'test_app', 46 | ] 47 | 48 | MIDDLEWARE_CLASSES = [ 49 | 'django.middleware.security.SecurityMiddleware', 50 | 'django.contrib.sessions.middleware.SessionMiddleware', 51 | 'django.middleware.common.CommonMiddleware', 52 | 'django.middleware.csrf.CsrfViewMiddleware', 53 | 'django.contrib.auth.middleware.AuthenticationMiddleware', 54 | 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 55 | 'django.contrib.messages.middleware.MessageMiddleware', 56 | 'django.middleware.clickjacking.XFrameOptionsMiddleware', 57 | ] 58 | 59 | ROOT_URLCONF = 'test_project.urls' 60 | 61 | TEMPLATES = [ 62 | { 63 | 'BACKEND': 'django.template.backends.django.DjangoTemplates', 64 | 'DIRS': [], 65 | 'APP_DIRS': True, 66 | 'OPTIONS': { 67 | 'context_processors': [ 68 | 'django.template.context_processors.debug', 69 | 'django.template.context_processors.request', 70 | 'django.contrib.auth.context_processors.auth', 71 | 'django.contrib.messages.context_processors.messages', 72 | ], 73 | }, 74 | }, 75 | ] 76 | 77 | WSGI_APPLICATION = 'test_project.wsgi.application' 78 | 79 | 80 | # Database 81 | # https://docs.djangoproject.com/en/1.9/ref/settings/#databases 82 | 83 | DATABASES = { 84 | 'default': { 85 | 'ENGINE': 'django.db.backends.sqlite3', 86 | 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), 87 | } 88 | } 89 | 90 | 91 | # Password validation 92 | # https://docs.djangoproject.com/en/1.9/ref/settings/#auth-password-validators 93 | 94 | AUTH_PASSWORD_VALIDATORS = [ 95 | { 96 | 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', 97 | }, 98 | { 99 | 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', 100 | }, 101 | { 102 | 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', 103 | }, 104 | { 105 | 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', 106 | }, 107 | ] 108 | 109 | 110 | # Internationalization 111 | # https://docs.djangoproject.com/en/1.9/topics/i18n/ 112 | 113 | LANGUAGE_CODE = 'en-us' 114 | 115 | TIME_ZONE = 'UTC' 116 | 117 | USE_I18N = True 118 | 119 | USE_L10N = True 120 | 121 | USE_TZ = True 122 | 123 | 124 | # Static files (CSS, JavaScript, Images) 125 | # https://docs.djangoproject.com/en/1.9/howto/static-files/ 126 | 127 | STATIC_URL = '/static/' 128 | -------------------------------------------------------------------------------- /tests/test_project/urls.py: -------------------------------------------------------------------------------- 1 | """test_project URL Configuration 2 | 3 | The `urlpatterns` list routes URLs to views. For more information please see: 4 | https://docs.djangoproject.com/en/1.9/topics/http/urls/ 5 | Examples: 6 | Function views 7 | 1. Add an import: from my_app import views 8 | 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') 9 | Class-based views 10 | 1. Add an import: from other_app.views import Home 11 | 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') 12 | Including another URLconf 13 | 1. Import the include() function: from django.conf.urls import url, include 14 | 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) 15 | """ 16 | from django.conf.urls import url 17 | from django.contrib import admin 18 | 19 | urlpatterns = [ 20 | url(r'^admin/', admin.site.urls), 21 | ] 22 | -------------------------------------------------------------------------------- /tests/test_project/wsgi.py: -------------------------------------------------------------------------------- 1 | """ 2 | WSGI config for test_project project. 3 | 4 | It exposes the WSGI callable as a module-level variable named ``application``. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/1.9/howto/deployment/wsgi/ 8 | """ 9 | 10 | import os 11 | 12 | from django.core.wsgi import get_wsgi_application 13 | 14 | os.environ.setdefault("DJANGO_SETTINGS_MODULE", "test_project.settings") 15 | 16 | application = get_wsgi_application() 17 | -------------------------------------------------------------------------------- /tox.ini: -------------------------------------------------------------------------------- 1 | [tox] 2 | envlist = py{27,34}-django{18,19,110}, flake8 3 | 4 | [testenv:flake8] 5 | deps=flake8 6 | commands=flake8 templated_docs 7 | 8 | [testenv] 9 | passenv = LO_PATH 10 | deps = 11 | django18: Django>=1.8,<1.9 12 | django19: Django>=1.9,<1.10 13 | django110: Django>=1.10,<1.11 14 | commands = python tests/manage.py test 15 | python example/manage.py check 16 | -------------------------------------------------------------------------------- /travis_pypi_setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | """Update encrypted deploy password in Travis config file 4 | """ 5 | 6 | 7 | from __future__ import print_function 8 | import base64 9 | import json 10 | import os 11 | from getpass import getpass 12 | import yaml 13 | from cryptography.hazmat.primitives.serialization import load_pem_public_key 14 | from cryptography.hazmat.backends import default_backend 15 | from cryptography.hazmat.primitives.asymmetric.padding import PKCS1v15 16 | 17 | 18 | try: 19 | from urllib import urlopen 20 | except: 21 | from urllib.request import urlopen 22 | 23 | 24 | GITHUB_REPO = 'alexmorozov/templated-docs' 25 | TRAVIS_CONFIG_FILE = os.path.join( 26 | os.path.dirname(os.path.abspath(__file__)), '.travis.yml') 27 | 28 | 29 | def load_key(pubkey): 30 | """Load public RSA key, with work-around for keys using 31 | incorrect header/footer format. 32 | 33 | Read more about RSA encryption with cryptography: 34 | https://cryptography.io/latest/hazmat/primitives/asymmetric/rsa/ 35 | """ 36 | try: 37 | return load_pem_public_key(pubkey.encode(), default_backend()) 38 | except ValueError: 39 | # workaround for https://github.com/travis-ci/travis-api/issues/196 40 | pubkey = pubkey.replace('BEGIN RSA', 'BEGIN').replace('END RSA', 'END') 41 | return load_pem_public_key(pubkey.encode(), default_backend()) 42 | 43 | 44 | def encrypt(pubkey, password): 45 | """Encrypt password using given RSA public key and encode it with base64. 46 | 47 | The encrypted password can only be decrypted by someone with the 48 | private key (in this case, only Travis). 49 | """ 50 | key = load_key(pubkey) 51 | encrypted_password = key.encrypt(password, PKCS1v15()) 52 | return base64.b64encode(encrypted_password) 53 | 54 | 55 | def fetch_public_key(repo): 56 | """Download RSA public key Travis will use for this repo. 57 | 58 | Travis API docs: http://docs.travis-ci.com/api/#repository-keys 59 | """ 60 | keyurl = 'https://api.travis-ci.org/repos/{0}/key'.format(repo) 61 | data = json.loads(urlopen(keyurl).read().decode()) 62 | if 'key' not in data: 63 | errmsg = "Could not find public key for repo: {}.\n".format(repo) 64 | errmsg += "Have you already added your GitHub repo to Travis?" 65 | raise ValueError(errmsg) 66 | return data['key'] 67 | 68 | 69 | def prepend_line(filepath, line): 70 | """Rewrite a file adding a line to its beginning. 71 | """ 72 | with open(filepath) as f: 73 | lines = f.readlines() 74 | 75 | lines.insert(0, line) 76 | 77 | with open(filepath, 'w') as f: 78 | f.writelines(lines) 79 | 80 | 81 | def load_yaml_config(filepath): 82 | with open(filepath) as f: 83 | return yaml.load(f) 84 | 85 | 86 | def save_yaml_config(filepath, config): 87 | with open(filepath, 'w') as f: 88 | yaml.dump(config, f, default_flow_style=False) 89 | 90 | 91 | def update_travis_deploy_password(encrypted_password): 92 | """Update the deploy section of the .travis.yml file 93 | to use the given encrypted password. 94 | """ 95 | config = load_yaml_config(TRAVIS_CONFIG_FILE) 96 | 97 | config['deploy']['password'] = dict(secure=encrypted_password) 98 | 99 | save_yaml_config(TRAVIS_CONFIG_FILE, config) 100 | 101 | line = ('# This file was autogenerated and will overwrite' 102 | ' each time you run travis_pypi_setup.py\n') 103 | prepend_line(TRAVIS_CONFIG_FILE, line) 104 | 105 | 106 | def main(args): 107 | public_key = fetch_public_key(args.repo) 108 | password = args.password or getpass('PyPI password: ') 109 | update_travis_deploy_password(encrypt(public_key, password.encode())) 110 | print("Wrote encrypted password to .travis.yml -- you're ready to deploy") 111 | 112 | 113 | if '__main__' == __name__: 114 | import argparse 115 | parser = argparse.ArgumentParser(description=__doc__) 116 | parser.add_argument('--repo', default=GITHUB_REPO, 117 | help='GitHub repo (default: %s)' % GITHUB_REPO) 118 | parser.add_argument('--password', 119 | help='PyPI password (will prompt if not provided)') 120 | 121 | args = parser.parse_args() 122 | main(args) 123 | --------------------------------------------------------------------------------