2

I'm trying to convert an HTML file to PFD with the pdfkit package. Here is my python code:

                location = os.path.join(files_path, f'user_data/temp/{code_generator(8)}')
                with app.app_context():
                    html = render_template('email_templates/invoice.html', invoice=invoice)
                    with open(f"{location}.html",'w',encoding = 'utf-8') as f:
                        f.write(html)
                    pdfkit.from_file(f"{location}.html", f"{location}.pdf")

But I'm getting this error:

Traceback (most recent call last):
  File "/var/www/ifileshifts/run.py", line 3, in <module>
    from ifileshifts import app, socketio#, manager
  File "/var/www/ifileshifts/ifileshifts/__init__.py", line 53, in <module>
    from ifileshifts.main.routes import main
  File "/var/www/ifileshifts/ifileshifts/main/routes.py", line 6, in <module>
    from .functions import first_otp_email, duplicate_handler, share_data, convert_size, get_size, is_integer
  File "/var/www/ifileshifts/ifileshifts/main/functions.py", line 371, in <module>
    invoice_genarator()
  File "/var/www/ifileshifts/ifileshifts/main/functions.py", line 353, in invoice_genarator
    pdfkit.from_file(f"{location}.html", f"{location}.pdf")
  File "/usr/local/lib/python3.6/dist-packages/pdfkit/api.py", line 51, in from_file
    return r.to_pdf(output_path)
  File "/usr/local/lib/python3.6/dist-packages/pdfkit/pdfkit.py", line 201, in to_pdf
    self.handle_error(exit_code, stderr)
  File "/usr/local/lib/python3.6/dist-packages/pdfkit/pdfkit.py", line 155, in handle_error
    raise IOError('wkhtmltopdf reported an error:\n' + stderr)
OSError: wkhtmltopdf reported an error:
Exit with code 1 due to network error: ProtocolUnknownError

What is wrong here? What is the solution?

Kute Konok
  • 51
  • 4

1 Answers1

2

Edit your code where you wrote this

pdfkit.from_file(f"{location}.html", f"{location}.pdf")
#to 
pdfkit.from_file(f"{location}.html", f"{location}.pdf", options={"enable-local-file-access": ""})
Zobaer
  • 21
  • 3
  • Can you provide some context on why this works? Also check to see if this has been asked already, see https://stackoverflow.com/questions/62315246/wkhtmltopdf-0-12-6-warning-blocked-access-to-file – Chris Mungall Sep 23 '22 at 03:47
  • See https://github.com/wkhtmltopdf/wkhtmltopdf/issues/2660#issuecomment-663063752 for a discussion of the issue in `wkhtmltopdf` which pdfkit is wrapping. – Att Righ Jan 25 '23 at 15:35