[python] How to convert IPython notebooks to PDF and HTML?

I want to convert my ipython-notebooks to print them, or simply send them in html format. I have noticed that there exists a tool to do that already, nbconvert. Although I have downloaded it, I have no idea how to convert the notebook, with nbconvert2.py since nbconvert says that it is deprecated. nbconvert2.py says that I need a profile to convert the notebook, what is it? Does there exist a documentation about this tool?

This question is related to python jupyter-notebook ipython

The answer is


I can't get pdf to work yet. The docs imply I should be able to get it to work with latex, so maybe my latex is not working.

$ ipython --version
1.1.0
$ ipython nbconvert --to latex  --post PDF myfile.ipynb
[NbConvertApp] ...
    raise child_exception
    OSError: [Errno 2] No such file or directory
$ ipython nbconvert --to pdf myfile.ipynb
  [NbConvertApp] CRITICAL | Bad config encountered during initialization:
  [NbConvertApp] CRITICAL | The 'export_format' trait of a NbConvertApp instance must be any of ['custom', 'html', 'latex', 'markdown', 'python', 'rst', 'slides'] or None, but a value of u'pdf' <type 'unicode'> was specified.

However, HTML works great using 'slides', and it is beautiful!

$ ipython nbconvert --to slides myfile.ipynb
...
[NbConvertApp] Writing 215220 bytes to myfile.slides.html

Update 2014-11-07Fri.: The IPython v3 syntax differs, it is simpler:

$ ipython nbconvert --to PDF myfile.ipynb

In all cases, it appears that I was missing the library 'pdflatex'. I'm investigating that.


I combined some answers above in inline python that u can add to ~/.bashrc or ~/.zshrc to compile and convert many notebooks to a single pdf file

function convert_notebooks(){
  # read anything on this folder that ends on ipynb and run pdf formatting for it  
  python -c 'import os; [os.system("jupyter nbconvert --to pdf " + f) for f in os.listdir (".") if f.endswith("ipynb")]'
  # to convert to pdf u must have installed latex and that means u have pdfjam installed
  pdfjam * 
}

Other suggested approaches:

  1. Using the 'Print and then select save as pdf.' from your HTML file will result in loss of border edges, highlighting of syntax, trimming of plots etc.

  2. Some other libraries have shown to be broken when it comes to using obsolete versions.

Solution: A better, hassle-free option is to use an online converter which will convert the *.html version of your *.ipynb to *.pdf.

Steps:

  1. First, from your Jupyter notebook interface, convert your *.ipynb to *.html using:

File > Download as > HTML(.html)

  1. Upload the newly created *.html file here and then select the option HTML to PDF.

  2. Your pdf file is now ready for download.

  3. You now have .ipynb, .html and .pdf files


Also pass the --execute flag to generate the output cells

jupyter nbconvert --execute --to html notebook.ipynb
jupyter nbconvert --execute --to pdf notebook.ipynb

The best practice is to keep the output out of the notebook for version control, see: Using IPython notebooks under version control

But then, if you don't pass --execute, the output won't be present in the HTML, see also: How to run an .ipynb Jupyter Notebook from terminal?

For an HTML fragment without header: How to export an IPython notebook to HTML for a blog post?

Tested in Jupyter 4.4.0.


You can do it by 1st converting the notebook into HTML and then into PDF format:

Following steps I have implemented on: OS: Ubuntu, Anaconda-Jupyter notebook, Python 3

1 Save Notebook in HTML format:

  1. Start the jupyter notebook that you want to save in HTML format. First save the notebook properly so that HTML file will have a latest saved version of your code/notebook.

  2. Run the following command from the notebook itself:

    !jupyter nbconvert --to html your_notebook_name.ipynb

After execution will create HTML version of your notebook and will save it in the current working directory. You will see one html file will be added into the current directory with your_notebook_name.html name

(your_notebook_name.ipynb --> your_notebook_name.html).

2 Save html as PDF:

  1. Now open that your_notebook_name.html file (click on it). It will be opened in a new tab of your browser.
  2. Now go to print option. From here you can save this file in pdf file format.

Note that from print option we also have the flexibility of selecting a portion of a notebook to save in pdf format.


Only this answer would be useful to you if you have math, scientific formulae in your document. Even if you don't have them it works fine.

GUI way

  • open the jupyter notebook open the jupyter notebook

  • Go to Files > Download as > HTML or PDF via LaTeX Go to Files > Download as > HTML or PDF via LaTeX

  • Then check your Downloads folder for the file. PS: If LaTeX had any errors while compiling the PDF, it will fail. If this happens, download the HTML file and then use Web page to PDF tool or any other similar service to convert the HTML to PDF.

Command-Line way

  • Open the terminal
  • Navigate to the folder containing the jupyter notebook
  • type "jupyter nbconvert --to pdf your_jupyter_notebook.ipynb "

PS: If it fails, try Yogesh's answer.


I find that the easiest method to convert a notebook which is on the web to pdf is to first view it on the web service nbviewer. You can then print it to a pdf file. If the notebook is on your local drive, then upload it to a github repository first and use its url for nbviewer.


From the docs:

If you want to provide others with a static HTML or PDF view of your notebook, use the Print button. This opens a static view of the document, which you can print to PDF using your operating system’s facilities, or save to a file with your web browser’s ‘Save’ option (note that typically, this will create both an html file and a directory called notebook_name_files next to it that contains all the necessary style information, so if you intend to share this, you must send the directory along with the main html file).


notebook-as-pdfInstall

python -m pip install notebook-as-pdf pyppeteer-install

Use it

You can also use it with nbconvert:

jupyter-nbconvert --to PDFviaHTML filename.ipynb

which will create a file called filename.pdf.

or pip install notebook-as-pdf

create pdf from notebook jupyter-nbconvert-toPDFviaHTML


nbconvert is not yet fully replaced by nbconvert2, you can still use it if you wish, otherwise we would have removed the executable. It's just a warning that we do not bugfix nbconvert1 anymore.

The following should work :

./nbconvert.py --format=pdf yourfile.ipynb 

If you are on a IPython recent enough version, do not use print view, just use the the normal print dialog. Graph beeing cut in chrome is a known issue (Chrome does not respect some print css), and works much better with firefox, not all versions still.

As for nbconvert2, it still highly dev and docs need to be written.

Nbviewer use nbconvert2 so it's pretty decent with HTML.

List of current available profiles:

$ ls -l1 profile|cut -d. -f1

base_html
blogger_html
full_html
latex_base
latex_sphinx_base
latex_sphinx_howto
latex_sphinx_manual
markdown
python
reveal
rst

Give you the existing profiles. (You can create your own, cf future doc, ./nbconvert2.py --help-all should give you some option you can use in your profile.)

then

$ ./nbconvert2.py [profilename] --no-stdout --write=True <yourfile.ipynb>

And it should write your (tex) files as long as extracted figures in cwd. Yes I know this is not obvious, and it will probably change hence no doc...

The reason for that is that nbconvert2 will mainly be a python library where in pseudo code you can do :

 MyConverter = NBConverter(config=config)
 ipynb = read(ipynb_file)
 converted_files = MyConverter.convert(ipynb)
 for file in converted_files :
     write(file)

Entry point will come later, once the API is stabilized.

I'll just point out that @jdfreder (github profile) is working on tex/pdf/sphinx export and is the expert to generate PDF from ipynb file at the time of this writing.


The plain python version of partizanos's answer.

  • open Terminal (Linux, MacOS) or get to point where you can execute python files in Windows
  • Type the following code in a .py file (say tejas.py)
import os

[os.system("jupyter nbconvert --to pdf " + f) for f in os.listdir(".") if f.endswith("ipynb")]
  • Navigate to the folder containing the jupyter notebooks
  • Ensure that tejas.py is in the current folder. Copy it to the current folder if necessary.
  • type "python tejas.py"
  • Job done

  1. Save as HTML ;
  2. Ctrl + P ;
  3. Save as PDF.

For those who can't install wkhtmltopdf in their systems, one more method other than many already mentioned in the answers to this question is to simply download the file as an html file from the jupyter notebook, upload that to HTML to PDF, and download the converted pdf files from there.

Here you have your IPython notebook(.ipynb) converted to both PDF(.pdf) & HTML(.html) formats.


If you are using sagemath cloud version, you can simply go to the left corner,
select File ? Download as ? Pdf via LaTeX (.pdf)
Check the screenshot if you want.

Screenshot Convert ipynb to pdf

If it dosn't work for any reason, you can try another way.
select File ? Print Preview and then on the preview
right click ? Print and then select save as pdf.


You can use this simple online service. It supports both HTML and PDF.


The simplest way I think is 'Ctrl+P' > save as 'pdf'. That's it.


If you have LaTeX installed you can download as PDF directly from Jupyter notebook with File -> Download as -> PDF via LaTeX (.pdf). Otherwise follow these two steps.

  1. For HTML output, you should now use Jupyter in place of IPython and select File -> Download as -> HTML (.html) or run the following command:

    jupyter nbconvert --to html notebook.ipynb  
    

    This will convert the Jupyter document file notebook.ipynb into the html output format.

    Google Colaboratory is Google's free Jupyter notebook environment that requires no setup and runs entirely in the cloud. If you are using Google Colab the commands are the same, but Google Colab only lets you download .ipynb or .py formats.

  2. Convert the html file notebook.html into a pdf file called notebook.pdf. In Windows, Mac or Linux, install wkhtmltopdf. wkhtmltopdf is a command line utility to convert html to pdf using WebKit. You can download wkhtmltopdf from the linked webpage, or in many Linux distros it can be found in their repositories.

    wkhtmltopdf notebook.html notebook.pdf   
    

Original (now almost obsolete) revision: Convert the IPython notebook file to html.

ipython nbconvert --to html notebook.ipynb


I've been searching for a way to save notebooks as html, since whenever I try to download as html with my new Jupyter installation, I always get a 500 : Internal Server Error The error was: nbconvert failed: validate() got an unexpected keyword argument 'relax_add_props' error. Oddly enough, I've found that downloading as html is as simple as:

  1. Left click in the notebook
  2. Click 'Save As...' in the dropdown menu
  3. Save accordingly

No print preview, no print, no nbconvert. Using Jupyter Version: 1.0.0. Just a suggestion to try (obviously not all setups are the same).


Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to jupyter-notebook

How to prevent Google Colab from disconnecting? Jupyter Notebook not saving: '_xsrf' argument missing from post How do I install Python packages in Google's Colab? What is the difference between Jupyter Notebook and JupyterLab? Importing .py files in Google Colab Display all dataframe columns in a Jupyter Python Notebook How to open local file on Jupyter? how to open Jupyter notebook in chrome on windows Change the Theme in Jupyter Notebook? Jupyter notebook not running code. Stuck on In [*]

Examples related to ipython

How to increase image size of pandas.DataFrame.plot in jupyter notebook? Importing .py files in Google Colab Selection with .loc in python IOPub data rate exceeded in Jupyter notebook (when viewing image) Purpose of "%matplotlib inline" Installing a pip package from within a Jupyter Notebook not working convert json ipython notebook(.ipynb) to .py file In which conda environment is Jupyter executing? How to make inline plots in Jupyter Notebook larger? %matplotlib line magic causes SyntaxError in Python script