简体   繁体   中英

Convert multiple jupyter notebooks to pdf

I have multiple jupyter notebooks in a folder. They change over time due to my edits to them. I wish to save them repeatedly as PDFs. Is there a python script to do this cleanly? (Preferably using the nbconvert thing.)

from os import system, listdir
from shutil import move
from os import mkdir, getcwd


def jup2pdf():
    print("Please input a run_no ")
    print("Only integers allowed")
    run_no = int(input())
    run_dir_name = 'pdf' + str(run_no)

    mkdir(run_dir_name)

    other_stuff = []
    for f in listdir("."):
        if f.endswith("ipynb"):
            system("jupyter nbconvert --to pdf " + f)
            # convert to pdf
            f_pdf = '.'.join([f[: -6], 'pdf'])
            # make the corresponding pdf file name
            move(f_pdf, run_dir_name, )
            # move the corresponding pdf file
        else:
            print('You have something other than a Jupyter notebook.')
            # print(f)
            other_stuff.append(f)

    print('The following pdf files have been created.')
    print('in', run_dir_name)
    print()
    for f in listdir(run_dir_name):
        if f.endswith("pdf"):
            print(f)
        else:
            print('PDFs not found in ', getcwd())

    print('We also found the following')
    for other_item in other_stuff:
        print(other_item)

    return None


'''

'''
check_pres_of = [f.endswith("ipynb") for f in listdir(".")]

if (True in check_pres_of):
    print('Found Jupyter notebooks in', getcwd())
    jup2pdf()
    # print([f.endswith("ipynb") for f in listdir(".")])
else:
    print('Jupyter notebooks not found in ', getcwd())

This script should do your job. Firstly, it checks if there are any jupyter notebooks in your folder. If no, it says "Jupyter notebooks not found in " said folder. If yes, it proceeds forward to convert them. Then it tells you which jupyter notebooks have been converted to pdfs.

It also checks if there are some other files, subfolders in the said folder.

Check if below link can be useful. link

Following steps are provided in the article: Keep all the files in a folder and follow below steps in command prompt:

  1. Install necessary package:

    pip install -U notebook-as-pdf

  2. Install additional setup for chromium

    pyppeteer-install

  3. If all files are kept in a folder, run a command to convert all notebook files from *.ipynb to *.pdf:

    jupyter-nbconvert --to PDFviaHTML *.ipynb

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM