from IPython.html import widgets
from IPython.display import display, Javascript, clear_output
from IPython.nbconvert import get_export_names, export_by_name
from IPython.nbconvert.writers import FilesWriter
from IPython.nbformat import current
Create and display a StringWidget without a view. The StringWidget will be used to store the notebook name which is otherwise only available in the front-end.
notebook_name = widgets.StringWidget(default_view_name='')
display(notebook_name)
Get the current notebook's name by pushing JavaScript to the browser that sets the notebook name in a string widget.
js = """var model = IPython.notebook.kernel.comm_manager.comms['{comm_id}'].model;
model.set('value', IPython.notebook.notebook_name);
model.save();""".format(comm_id=notebook_name._comm.comm_id)
display(Javascript(data=js))
filename = notebook_name.value
filename
Create the widget that will allow the user to Export the current notebook.
container = widgets.ContainerWidget()
container.vbox()
container.align_center()
options = widgets.ContainerWidget(parent=container)
options.hbox()
options.align_center()
exporter_names = widgets.SelectionWidget(parent=options, values=get_export_names(), value='html')
export_button = widgets.ButtonWidget(parent=options, description="Export")
download_link = widgets.StringWidget(parent=container, default_view_name="HTMLView", visible=False)
Export the notebook when the export button is clicked.
file_writer = FilesWriter()
def export(name, nb):
# Get a unique key for the notebook and set it in the resources object.
notebook_name = name[:name.rfind('.')]
resources = {}
resources['unique_key'] = notebook_name
resources['output_files_dir'] = '%s_files' % notebook_name
# Try to export
try:
output, resources = export_by_name(exporter_names.value, nb)
except ConversionException as e:
download_link.value = "<br>Could not export notebook!"
else:
write_results = file_writer.write(output, resources, notebook_name=notebook_name)
download_link.value = "<br>Results: <a href='files/{filename}'><i>\"{filename}\"</i></a>".format(filename=write_results)
download_link.visible = True
def handle_export():
with open(filename, 'r') as f:
export(filename, current.read(f, 'json'))
export_button.on_click(handle_export)
download_link.visible = False
display(container)