Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automating ipython output to pdf

I have a little program that basically does all kinds of statistical calculation and prints out results and charts.

At present, a convenient way to get a nice pdf output of my program is to run my code in Jupyter IPython Notebook using magic command %matplotlib inline and save as pdf by doing "PDF via LaTex(.pdf) "

But, the problem is I have to do it manually every time I run the program. In addition, I cannot deliver the program as binary executable to other people, which is my final goal.

Is there a way to do this programmatically? Just to be clear, all I want is output of my program in pdf format so that when the executable is run, the output is pdf. I don't want the end user to create ipython notebook. The end user will not have access to the source code.

enter image description here

like image 701
nyan314sn Avatar asked May 02 '16 18:05

nyan314sn


2 Answers

As of now there's not a programming language API to convert notebooks to PDF. However, a command line utility exists called nbconvert. It has the same functionality as the web interface's format converters. To convert to PDF, you can do jupyter nbconvert notebook.ipynb --to pdf.

Luckily, Python has a handy subprocess module which allows you to spawn new processes, check their inputs and outputs, and get their return codes. So you could do something like:

import subprocess
subprocess.call("jupyter nbconvert notebook.ipynb --to pdf")

Kind of a hacky way, but it will work. If you're using Windows, you may need to add the additional kwarg shell=True to subprocess.call()

like image 172
Tyler Sanderson Avatar answered Oct 02 '22 16:10

Tyler Sanderson


If you have an IPython notebook, you can make a small python or bash script that first executes and then produces the PDF. For me, this bash script works:

jupyter nbconvert --ExecutePreprocessor.timeout=500 --to notebook --execute my_file.ipynb
jupyter nbconvert --to pdf my_file.nbconvert.ipynb
rm my_file.nbconvert.ipynb

If you want to customise the output using a template, I have found that converting the file first to markdown and then using pandoc to create a PDF avoids some issues:

jupyter nbconvert --ExecutePreprocessor.timeout=500 --to notebook --execute my_file.ipynb
jupyter nbconvert  --to markdown my_file.nbconvert.ipynb  --template="mytemplate.tpl"
pandoc --toc --template=mytemplate.tex markdown my_file.nbconvert.ipynb --latex-engine=pdflatex -o final file.pdf
like image 38
Byte_Monster Avatar answered Oct 02 '22 17:10

Byte_Monster