Search code examples
pdfjupyter-notebooknbconvert

minimal example of how to export a jupyter notebook to pdf using nbconvert and PDFExporter()


I am trying to export a pdf copy of a jupyter notebook using nbconvert from within a notebook cell. I have read the documentation, but I just cannot find some basic code to actually execute the nbconvert command and export to pdf.

I was able to get this far, but I was hoping that someone could just fill in the final gaps.

from nbconvert import PDFExporter
notebook_pdf = PDFExporter()
notebook_pdf.template_file = '../print_script/pdf_nocode.tplx'

Note sure how to get from here to actually getting the pdf created.

Any help would be appreciated.


Solution

  • I'm no expert, but managed to get this working. The key is that you need to preprocess the notebook which will allow you to use the PDFExporter.from_notebook_node() function. This will give you your pdf_data in byte format that can then be written to file:

    import nbformat
    from nbconvert.preprocessors import ExecutePreprocessor
    from nbconvert import PDFExporter
    
    notebook_filename = "notebook.ipynb"
    
    with open(notebook_filename) as f:
        nb = nbformat.read(f, as_version=4)
    
    ep = ExecutePreprocessor(timeout=600, kernel_name='python3')
    
    ep.preprocess(nb, {'metadata': {'path': 'notebooks/'}})
    
    pdf_exporter = PDFExporter()
    
    pdf_data, resources = pdf_exporter.from_notebook_node(nb)
    
    with open("notebook.pdf", "wb") as f:
        f.write(pdf_data)
        f.close()
    

    It's worth noting that the ExecutePreprocessor requires the resources dict, but we don't use it in this example.