Skip to content

Instantly share code, notes, and snippets.

@parthi2929
Created September 5, 2018 13:37
Show Gist options
  • Save parthi2929/331eb549a1edf2e5214940d2e9a7bea2 to your computer and use it in GitHub Desktop.
Save parthi2929/331eb549a1edf2e5214940d2e9a7bea2 to your computer and use it in GitHub Desktop.
This is to convert a notebook to latex using nbconvert api. Currently not yet exports individual file images. Note the references in resulting tex file also in same folder.
sourcefile = r"../../test.ipynb" # file to be converted
with open(sourcefile) as nb_file:
nb_contents = nb_file.read()
import nbformat
# Convert using the ordinary exporter
notebook = nbformat.reads(nb_contents, as_version=4)
# create a configuration object to extract figures as files
from traitlets.config import Config
c = Config()
c.LatexExporter.preprocessors = ['nbconvert.preprocessors.ExtractOutputPreprocessor']
# ref: https://nbconvert.readthedocs.io/en/latest/nbconvert_library.html#Quick-overview
# 1. Import the exporter
from nbconvert import LatexExporter
# 2. Instantiate the exporter.
latex_exporter = LatexExporter(config=c)
latex_exporter.template_file = 'ipy2tex_converter.tplx'
# 3. Process the notebook we loaded earlier
(body, resources) = latex_exporter.from_notebook_node(notebook)
# 4. write the tex file
import ntpath
foldername = ntpath.basename(sourcefile).split('.ipynb')[0]
basename = foldername +'.tex'
with open(basename, 'w') as output_file:
output_file.write(body)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment