Skip to content

Instantly share code, notes, and snippets.

@CloudCray
Last active November 23, 2018 07:25
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save CloudCray/994dd361dece0463f64a to your computer and use it in GitHub Desktop.
Save CloudCray/994dd361dece0463f64a to your computer and use it in GitHub Desktop.
Quick script to convert IPython Notebooks to PDFs
# Author: Cloud Cray
# 2014-12-30
# Run this script in the same folder as the notebook(s) you wish to convert
# This will create both an HTML and a PDF file
#
# You'll need wkhtmltopdf (this will keep syntax highlighting, etc)
# http://wkhtmltopdf.org/downloads.html
import subprocess
import os
WKHTMLTOPDF_PATH = "C:/Program Files/wkhtmltopdf/bin/wkhtmltopdf" # or wherever you keep it
def get_notebook(): # recursive function to show all notebooks in directory
files = os.listdir()
notebooks = [x for x in files if x.lower().endswith(".ipynb")]
if len(notebooks) == 0:
return None
for i in range(len(notebooks)):
print("{0}: {1}".format(str(i+1), notebooks[i]))
print("0: None")
nb_index = input(" Select > ")
if nb_index.isnumeric():
if int(nb_index) == 0:
return None
elif int(nb_index) > 0 and int(nb_index) < len(notebooks) +1:
return notebooks[int(nb_index) - 1]
else:
print("Invalid!")
return get_notebook()
else:
return get_notebook()
def export_to_html(filename):
cmd = 'ipython nbconvert --to html "{0}"'
subprocess.call(cmd.format(filename))
return filename.replace(".ipynb", ".html")
def convert_to_pdf(filename):
cmd = '"{0}" "{1}" "{2}"'.format(WKHTMLTOPDF_PATH, filename, filename.replace(".html", ".pdf"))
subprocess.call(cmd)
return filename.replace(".html", ".pdf")
def export_to_pdf(filename):
fn = export_to_html(filename)
return convert_to_pdf(fn)
def main():
print("Export IPython notebook to PDF")
print(" Please select a notebook:")
x = get_notebook()
if not x:
print("No notebook selected.")
return 0
else:
fn = export_to_pdf(x)
print("File exported as:\n\t{0}".format(fn))
return 1
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment