nyan314sn
nyan314sn

Reputation: 1936

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

Upvotes: 10

Views: 11590

Answers (3)

kris2k
kris2k

Reputation: 345

On windows if you want to convert recursively you can use git-bash window and do something like this:

$ find /d/we_are_on_disk_d/path_to_ipynb_files/ -name '*.ipynb' | xargs jupyter nbconvert --to [script|pdf]

Upvotes: 0

Byte_Monster
Byte_Monster

Reputation: 313

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

Upvotes: 3

Tyler Sanderson
Tyler Sanderson

Reputation: 121

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()

Upvotes: 12

Related Questions