Roman
Roman

Reputation: 3941

Flask Pdfkit create pdf from template and save it

I use pdfkit to create an invoice pdf. At the moment I just want to save it. Later I will save the invoice filename in the DB and store in on AWS3.

But for now I get an IO Error when trying to save the file, probably because I request it the wrong way:

pdfkit.from_file(render_template('invoice_template.html', invoice_id=1, invioce_date_start=str(date.today()),
                                     invioce_date_end=str(date.today()), invioce_company_name=form.zahlung_firma.data, invioce_user_vorename=form.vorname.data,
                                     invioce_user_surname=form.nachname.data, invioce_user_email=current_user.email), str(current_user.id) + '-invoice.pdf')

The Error:

    Traceback (most recent call last):
  File "C:\Python27\lib\site-packages\flask\app.py", line 1988, in wsgi_app
    response = self.full_dispatch_request()
  File "C:\Python27\lib\site-packages\flask\app.py", line 1641, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "C:\Python27\lib\site-packages\flask\app.py", line 1544, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "C:\Python27\lib\site-packages\flask\app.py", line 1639, in full_dispatch_request
    rv = self.dispatch_request()
  File "C:\Python27\lib\site-packages\flask\app.py", line 1625, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "C:\Python27\lib\site-packages\flask_login.py", line 758, in decorated_view
    return func(*args, **kwargs)
  File "C:\Users\User\Eclipse-Workspace\Monteurzimmer\main.py", line 114, in decorated_function
    return func(*args, **kwargs)
  File "C:\Users\User\Eclipse-Workspace\Monteurzimmer\main.py", line 1252, in logged_in
    invioce_user_surname=form.nachname.data, invioce_user_email=current_user.email), str(current_user.id) + '-invoice.pdf')
  File "C:\Python27\lib\site-packages\pdfkit\api.py", line 47, in from_file
    configuration=configuration, cover_first=cover_first)
  File "C:\Python27\lib\site-packages\pdfkit\pdfkit.py", line 41, in __init__
    self.source = Source(url_or_file, type_)
  File "C:\Python27\lib\site-packages\pdfkit\source.py", line 12, in __init__
    self.checkFiles()
  File "C:\Python27\lib\site-packages\pdfkit\source.py", line 32, in checkFiles
    raise IOError('No such file: %s' % self.source)
IOError: No such file: <!doctype html>

The template itself can be found here, I just edited the jinja variables:

Upvotes: 1

Views: 5218

Answers (1)

Nathan Wailes
Nathan Wailes

Reputation: 12222

pdfkit.from_file() expects a file object as its input, but render_template() returns a string. Try pdfkit.from_string() instead.

More information: pypi - pdfkit

Upvotes: 4

Related Questions