# jupyter_html_to_pdf.py (C) 2021 MIT license
''' Purpose: Generates relatively well-formated PDF file out of a HTML file 
    generated by a Jupyter notebook. Adds display: block to CSS, then exports
    using pdfkit
    Requires:
        * BeautifulSoup4
        * The wkhtmltopdf commandline utility
'''

from uuid import uuid4
import os
from bs4 import BeautifulSoup
from sys import argv
import subprocess

if len(argv) != 3:
    raise ValueError('Usage: print.py in_html out_pdf')
in_html = argv[1]
out_pdf = argv[2]
tempfile = f'{uuid4()}.html'

# Add display: block to HTML

with open(in_html) as fp:
    htdoc = fp.read()
    soup = BeautifulSoup(htdoc, 'html.parser')
    del htdoc

if soup.style != None:
    soup.style.string += '.jp-Cell-outputWrapper {\n\tdisplay:block;\npage-break-before:auto;\npage-break-after:auto;\nbreak-inside:avoid;\n}'
    with open(tempfile, 'w') as fp:
        fp.write(str(soup))
else:
    raise ValueError('A jupyter notebook without a style tag?')
subprocess.call(['wkhtmltopdf', '--no-stop-slow-scripts', '--page-size', 'A4', 
                 tempfile, out_pdf])
                 
# Clean up after ourselves
os.remove(tempfile)
