How to convert to PDF IOCaml notebooks
Explanation :sunglasses:
- I use the unofficial IOCaml kernel for my teaching activities, to use the awesome Jupyter notebooks with the OCaml language,
- I like to write solutions to my practical sessions in a notebook, so it can be nicely viewed online.
Issue :boom: !
- But by default the PDF generation was not perfect: the
stdout
output was kept fine, but the type annotations were removed from the output of the PDF. See for instance, this HTML notebook and this PDF notebook to see what was missing. - And without the type annotations, the solution is not complete and not understandable.
Solution :rocket: !
- I wrote this small Python script to pre-process a
.ipynb
notebook file before callingjupyter-nbconvert --to pdf
, and keep the type annotations. - Now, instead of using this Bash alias to do
j2pdf My_OCaml_notebook.ipynb
:
alias j2pdf='jupyter-nbconvert --to pdf'
- I use this Bash function the same way:
function j2pdf() { for old in "$@"; do new="${old%.ipynb}__fix-iocaml-notebook-exports-to-pdf.ipynb" [ -f "$new" ] && mv -vf "$new" /tmp/ fix-iocaml-notebook-exports-to-pdf.py "$old" "$new" if [ $? = 0 ]; then jupyter-nbconvert --to pdf "$new" [ -f "${old%.ipynb}.pdf" ] && mv -vf "${old%.ipynb}.pdf" /tmp/ mv -vf "${new%.ipynb}.pdf" "${old%.ipynb}.pdf" mv -vf "$new" /tmp/ else jupyter-nbconvert --to pdf "$old" fi done }
- It tries to fix the notebook, and convert either the new one to PDF or the old one.
Note: I also use this Bash function:
function j2html() { for old in "$@"; do jupyter-nbconvert --to html "$old" done }
Test
With this Makefile, run the tests with:
make -B test
- It runs the script on two example notebooks, one using the IOCaml kernel, one using another kernel (Python 3),
- It converts them to PDF and to HTML, and open the results,
- You should check manually that the PDF of the
test_input_ocaml.ipynb
notebook has bothstdout
output and type annotations.
:scroll: License ?
MIT Licensed (file LICENSE). © Lilian Besson, 2017.