Sunday, 10 February 2019

Render Jupyter Notebook to HTML or PDF

The following shows how to render a Jupyter Notebook into a static form, such as HTML or PDF document. 

Render to HTML

To render a Jupyter Notebook to HTML:
jupyter nbconvert --exec --to html --output document.html document.ipynb
You can also specify an output directory:
jupyter nbconvert --exec --to html --output document.html --output-dir target document.ipynb
The HTML has all images embedded. This makes sharing easy is the HTML is fully self contained.

Render to PDF

I have had mixed results converting a notebook directly to PDF. The conversion complained that embedded images were not found. Instead I suggest first converting it to LaTeX and then to a PDF.
To convert to Tex run:
jupyter nbconvert --exec --to latex --output document.tex document.ipynb
Now, it is an easy matter to convert TeX to PDF with pdflatex:
pdflatex document.tex

Build using Makefile

A generic Makefile that can be used in a Jupyter project to perform this task is:

Makefile
#!/usr/bin/env make
 
.PHONY: html pdf clean
.SUFFIXES: .ipynb .tex .pdf .html
.DEFAULT: html
 
IPYNB := $(wildcard *.ipynb)
TEXS := $(patsubst %.ipynb, %.tex, $(IPYNB))
HTMLS := $(patsubst %.tex, %.html, $(TEXS))
PDFS := $(patsubst %.tex, %.pdf, $(TEXS))
 
.ipynb.tex:
 -jupyter nbconvert --to=latex $<
 
.tex.pdf:
 -latexmk -f -gg -quiet -pdf \
  -interaction=nonstopmode -shell-escape \
  -pdflatex="pdflatex %O %S" $<
 
.ipynb.html:
 -jupyter nbconvert --exec --to html --output $@ $<
 
html: $(HTMLS)
 
pdf: $(PDFS)
 
clean:
 -latexmk -quiet -f -c $(TEXS)
 @$(RM) -rf $(wildcard *_files)
ifneq ("$(TEXS)", "")
 @$(RM) $(patsubst %.tex, %.*.*, $(TEXS))
 @$(RM) $(TEXS)
endif

Note

Use tabs (default is set to 8) and not spaces as make is whitespace sensitive.

Dependencies

Assuming you have Jupyter installed, then the other Debian Linux dependencies for this project are:



No comments: