Jupyter notebook can export as HTML but it comes with a lot of stuffs that are not so compatible with blogs.

Here is how I tried to remove all of those while still keeping the styles of the notebooks.

Idea:

  • export with basic template, this will give only minimal html output
  • manually, capture the CSS styles part from the richer export version
  • combine them

Caution: There will be some side effects to the styles of the blog!

Export with basic template

jupyter nbconvert --to html --template basic <path>

If you want to get it in stdout, you can add --stdout to the command.

Capture the CSS styles

Here is the CSS styles I took from the normally exported html: https://gist.github.com/phizaz/8f05ede652b8fa58b87e108a65a772a5

Note: If you want to use the script below, please save the file as head.html in the same place of the script below.

Combine them!

You can either do it by hand, or create your own script to do this.

In fact I have written a small Python script for this:

Filename blog-convert:

#! /usr/bin/env python

import subprocess
import os
import pyperclip
import argparse


def shell(cmd):
    return subprocess.check_output(cmd, shell=True)


def nbconvert(path):
    cmd = 'jupyter nbconvert --stdout --to html --template basic {}'.format(
        path)
    return shell(cmd)


def get_header():
    this = os.path.dirname(os.path.realpath(__file__))
    with open(os.path.join(this, 'head.html')) as file:
        content = file.read()
    return content


def clipboard(content):
    print('clipboard for {} bytes'.format(len(content.encode('utf-8'))))
    pyperclip.copy(content)


def main():
    parser = argparse.ArgumentParser(description="convert ipynb to html for blogging")
    parser.add_argument('path', type=str, help="path to your ipynb file")
    args = parser.parse_args()

    header = get_header()
    body = nbconvert(args.path)
    clipboard(header + body.decode('utf8'))


main()

Usage

blog-convert <file>.ipynb

You will get your results in the clipboard.

Example of this method

In [2]:
a = 10
b = 20
In [3]:
print(a + b)
30