Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Google Colab notebook to PDF / HTML?

I would like to know if there is a way in Google Colab that can collate outputs nicely, just like Markdown in R and how IPython Notebook can be converted to pdf and html format?

My output consists of multiple tables, graphs etc. I would like to preferably pretty print them into one file, of which some part are presentable enough to be used in a report.If there's no such method, what is the best alternative?

like image 598
nilsinelabore Avatar asked Mar 02 '23 16:03

nilsinelabore


1 Answers

You can also create a pdf in colab itself using nbconvert.

!apt update
!apt install texlive-xetex texlive-fonts-recommended texlive-generic-recommended

import re, pathlib, shutil

# Get a list of all your Notebooks
notebooks = [x for x in pathlib.Path("/content/drive/My Drive/Colab Notebooks").iterdir() if 
             re.search(r"\.ipynb", x.name, flags = re.I)]

for i, n in enumerate(notebooks):
    print(f"\nProcessing  [{i+1:{len(str(len(notebooks)))}d}/{len(notebooks)}]  {n.name}\n")

    # Optionally copy your notebooks from gdrive to your vm
    shutil.copy(n, n.name)
    n = pathlib.Path(n.name)

    !jupyter nbconvert "{n.as_posix()}" --to pdf --output "{n.stem.replace(" ", "_")}"

Instead of using a magic to run nbconvert you could also use subprocess

s = subprocess.Popen(shlex.split(
    f'jupyter nbconvert "{n.as_posix()}" --to pdf --output "{n.stem.replace(" ", "_")}"'
    ), shell = False, stdout = subprocess.PIPE, stderr = subprocess.PIPE)
s.wait()
s.stdout.read()

There are also more packages available regarding xetex in case you use a very sophisticated template.

sudo apt install pandoc nbconvert texlive texlive-latex-extra texlive-generic-extra
like image 62
Night Train Avatar answered Mar 05 '23 15:03

Night Train