1

I have a Plotly Multipage(tabs) Dash Application. I would like to convert this to a PDF file. I know there is the dash_snapshot_engine module, which is not for free. Therefore I am looking for a free alternative. As my Dash application will be an executable, I can't use external software such as wkhtmltopdf, I can only use Python only libraries.

Has anybody any suggestions on how to convert a html file to pdf with Python libraries?

Thanks in advance!

abc
  • 157
  • 1
  • 13

1 Answers1

-1

You could add wkhtmltopdf to your exe using PyInstaller:

import subprocess
import sys

htmlPath = 'C:/temp/test.html'
pdfPath = 'C:/temp/test_through_exe.pdf'

if getattr(sys, 'frozen', False):
    # Change wkhtmltopdf path for exe!
    wkPath = os.path.join(sys._MEIPASS, "wkhtmltopdf.exe")
else:
    wkPath = 'C:/.../Downloads/wkhtmltopdf.exe'

with open(htmlPath, 'w') as f:
    f.write('<html><body><h1>%s</h1></body></html>' % sys.version)

cmd = '%s %s %s' % (wkPath, htmlPath, pdfPath)
print(cmd)

proc = subprocess.Popen(cmd, stderr=subprocess.PIPE, stdout=subprocess.PIPE, shell=True)
stdout, stderr = proc.communicate()

print(proc.returncode, stdout)
print(proc.returncode, stderr)

Building the exe (wkhtmltopdf and your script in the same directory):

PyInstaller --onefile --add-data ./wkhtmltopdf.exe;. test.py

Out:

C:\Users\xxx\AppData\Local\Temp\_MEI33842\wkhtmltopdf.exe C:/temp/test.html C:/temp/test_through_exe.pdf
0 b''
0 b'Loading pages (1/6)\r\n[>                                                           ] 0%\r[======>
     ] 10%\r[==============================>                             ] 50%\r[============================================================] 100%\rCounting pages (2/6)                                               \r\n[============================================================] Object 1 of 1\rResolving links (4/6)                                                       \r\n[============================================================] Object 1 of 1\rLoading headers and footers (5/6)                                           \r\nPrinting pages (6/6)\r\n[>
                     ] Preparing\r[============================================================] Page 1 of 1\rDone
                                  \r\n'

enter image description here

Maurice Meyer
  • 17,279
  • 4
  • 30
  • 47
  • Thank you for this idea. Is it also working with cx_freeze? Can I add .exe files the same way? – abc Nov 22 '21 at 11:23
  • @abc: I never used `cx_freeze`, just `PyInstaller`, `nuitka` or `py2exe` (for Python 2.x). Might be helpful: https://stackoverflow.com/questions/2553886/how-can-i-bundle-other-files-when-using-cx-freeze – Maurice Meyer Nov 22 '21 at 11:57
  • Is it possible that `wkhtmltopdf` uses web-service to convert the html to pdf? - In this case it is not an option, as the converter should use "offline" methods... – abc Nov 22 '21 at 13:36
  • no `wkhtmltpdf` does all processing locally itself. – Ryan Dec 02 '21 at 03:49