Search code examples
pythonpdfgraphjupyter-notebookfile-conversion

Graphs in a jupyter notebook to pdf


I have a jupyter notebook running python and I want all the graphs that I construct outputted to one pdf file. Does anybody know how to do this?

Kind regards,


Solution

  • I could not find some way to directly convert all the plots in pdf but this way I am going to tell is perfectly working and tested. First, you need to import matplotlib.

    import matplotlib.pyplot as plt
    

    Now write this code in all the blocks of jupyter notebook which are plotting some graphs. Images name should be different for all blocks, you can save as plt1.png , plt2.png etc.

    plt.save('imagename.png')
    

    please note imagename should be different for all blocks.

    Don't worry you would not be left with plot images. Now run this code in the last of the notebook.

    from PIL import Image
    import glob
    import os
    images = glob.glob("*.png")
    print(images)
    imlist = []
    for img in images:
        im = Image.open(img)
        im = im.convert('RGB')
        imlist.append(im)
    imlist[0].save('plots.pdf',save_all=True, append_images=imlist[1:])
    map(os.remove(img),[img for img in images])
    

    What is basically being here, you are saving images of all plots one by one then this code will convert all those images into pdf, and os.remove will remove all the taken images. Note: you should not have other png files in the same folder otherwise those will be also included in pdf and get removed as well.