Reputation: 35
I'm new to Django and would like to create a form where users can input some data, and have a Word document be created for download.
I was using the templated-docs library (https://pypi.org/project/templateddocs/) to accomplish this task, but I'm receiving an error.
in my views.py:
from templated_docs import fill_template
from templated_docs.http import FileResponse
def get_document(request):
"""
A view to get a document filled with context variables.
"""
context = {'user': request.user} # Just an example
filename = fill_template('sample.odt', context, output_format='pdf')
visible_filename = 'greeting.pdf'
return FileResponse(filename, visible_filename)
After the user inputs information in the form, I'm getting this error:
get_template_sources() takes 2 positional arguments but 3 were given
the error is produced from the variable that's in views.py: filename = fill_template('sample.odt', context, output_format='pdf')
Upvotes: 2
Views: 1129
Reputation: 5508
The library was written 3 years back and no longer seems to be maintained.
It used LibreOffice via pylokit
for parsing source and generating output.
Alternatively you can use Pandoc (universal document converter) + Pandoc Filters for parsing source, doing modifications and generating output.
The whole of the above code can be accomplished with something like below.
import io
import pypandoc
import panflute as pf
from django.http import FileResponse
def generate_invoice(request):
template = 'files/invoice.docx'
output_path = '/tmp/invoice - {}.pdf'.format(request.user.id)
context = {
'{{name}}': 'Foo'
}
# parse input file
data = pypandoc.convert_file(template, 'json')
f = io.StringIO(data)
doc = pf.load(f)
# do replacements
for key, value in context.items():
doc = doc.replace_keyword(key, pf.Str(value))
# generate output
with io.StringIO() as f:
pf.dump(doc, f)
contents = f.getvalue()
pypandoc.convert_text(contents, 'pdf', format='json', outputfile=output_path)
return FileResponse(open(output_path, 'rb'), filename='invoice.pdf')
Upvotes: 3