Как сохранить jupiter notebook в pdf
Перейти к содержимому

Как сохранить jupiter notebook в pdf

  • автор:

4 ways to export Jupyter Notebook as PDF

Run Mercury to convert Jupyter Notebooks to web apps

Export Jupyter Notebook as PDF banner

Have you ever wanted to export your Jupyter Notebook to PDF file? The PDF is an abbreviation for Portable Document Format. It can be displayed on any operating system. That makes it format of choice for many who wants to share their results. In this post I will show you 4 different ways how to export Jupyter Notebook as PDF file.

1. Print Jupyter Notebook to PDF

The most straightforward way is just to use web browser feature of print to PDF. There is no need to install any additional packages.

The big advantage of this approach is that we don’t need to install additional libraries to make it works! However, it is manual approach — hard to automate. What is more, we can’t control the process of export (for example, we can’t hide code in the exported file).

2. Download Jupyter Notebook as PDF

The Jupyter Notebook has an option to export the notebook to many formats. It can be accessed by clicking File -> Download as -> PDF via LaTeX (or PDF via HTML — not visible in the screenshot).

Print Jupyter Notebook to PDF

This approach requires you to install some additional packages. For me, the option that exports with LaTeX is difficult. It requires you to install much more packages than option of export via HTML. If you don’t have required packages you will get the error message:

nbconvert failed: xelatex not found on PATH, if you have not installed xelatex you may need to do so. Find further instructions at https://nbconvert.readthedocs.io/en/latest/install.html#installing-tex. 

Jupyter Notebook error when exporting to pdf

This is scary, isn’t it? The option to export via HTML requires you to download Chromium (headless browser).

I rarely use this approach to be honest. It requires additional installation (that is not trivial) and is manual. This approach under the hood is using nbconvert tool.

3. Export to PDF with nbconvert

That’s one of my favourite approaches. Why? Because it is a command line tool that can be used in the scripts 🙂

Still you need to install additional packages to make it work. The same as in Jupyter Notebook GUI there are two options:

  • export to PDF via LaTex,
  • export to PDF via HTML.

The latter is my choice. It requires pyppeteer and Chromium to be download. This can be easily achieved by running:

pip install nbconvert[webpdf] 

and adding a flag —allow-chromium-download when converting a notebook:

jupyter nbconvert --to webpdf --allow-chromium-download your-notebook-file.ipynb 

The flag should be added only one time. It is not necessary after Chromium installation. The nbconvert has many optional arguments that control the export. For example, you can easily hide the code with —no-input flag:

jupyter nbconvert --to webpdf --no-input your-notebook-file.ipynb 

Additionally, you can apply more options to the export like removing selected cells or change the templates.

4. Share Notebook with Mercury

There is an open-source framework Mercury that makes Python notebooks sharing painless. It converts notebooks to interactive documents (web apps, reports, slides, dashboards). You can share a notebook with interactive widgets. Your end-users can tweak widgets values and execute the notebook with new values (without changing the code). The Mercury allows to export the executed notebook into standalone HTML or PDF file. The end-user just need to clik the Download button.

Summary

Saving notebooks to PDF is a great way to persist results in a shareble format. PDFs can be easily published online or send in the email. There are several ways to convert Jupyter Notebook as PDF. The automatic conversion can be easily achieved with nbconvert tool. Notebooks shared with Mercury framework can be easily converted to PDF. The PDF notebook can be manually downloaded from the website.

Экспорт из ipynb в PDF с сохранением русского языка. Python nbconvert

из библиотеки nbconvert При экспорте не сохраняются символы русского алфавита. В итоге я должен был бы получить что-то такое: просто вырезка из юпитер ноутбука, который нужно экспортировать А получаю это: вырезка из полученного PDF файла Подскажите пожалуйста, как избежать этого? MIKTeX скачан и русский язык там есть, Pandoc тоже.

Отслеживать
задан 19 апр 2020 в 16:44
Antivist Home Antivist Home
75 1 1 золотой знак 3 3 серебряных знака 11 11 бронзовых знаков

1 ответ 1

Сортировка: Сброс на вариант по умолчанию

Этому вопросу больше двух лет, но, возможно, ответ кому-то пригодится.

Jupyter использует xelatex для того, чтобы генерировать PDF из тетрадки. xelatex — это LaTeX, сделанный на основе XeTeX — версии TeX, в которой используется Unicode для кодировки символов, а не байтовые кодировки, как в оригинальном TeXе.

Встроенная поддержка Unicode — это хорошо, но нужны ещё шрифты, в которых есть кириллические буквы. К сожалению, стандартный формат xelatex использует шрифты, в которых нет нужных символов.

Для решения проблемы можно воспользоваться тем, что Jupyter генерирует TeX-файл из тетрадки ipynb, используя шаблон Jinja2, который хранится в файле index.tex.j2 . Место расположения этого файла и выбор шрифтов на замену зависит от окружения.

Linux + TeXLive

В Linux Jupyter ищет этот шаблон по списку директорий, первое место в котором занимает директория ~/.local/share/jupyter/nbconvert/templates/latex .

Хорошие шрифты для Linux — это шрифты семейства Droid.

В директорию с шаблонами нужно положить файл примерно такого содержания, который обеспечит подключение шрифтов Droid.

((=- Default to the notebook output style -=)) ((*- if not cell_style is defined -*)) ((* set cell_style = 'style_jupyter.tex.j2' *)) ((*- endif -*)) ((=- Inherit from the specified cell style. -=)) ((* extends cell_style *)) %=============================================================================== % Latex Article %=============================================================================== ((*- block docclass -*)) \documentclass[11pt] ((*- endblock docclass -*)) ((*- block packages -*)) ((( super() ))) \usepackage \usepackage \setdefaultlanguage \setotherlanguage \newfontfamily \newfontfamily \AtBeginDocument < \setmainfont\setsansfont \setmonofont > ((*- endblock packages -*)) 

После того, как в генерируемый TeX файл будут включены команды из бока packages , в PDF-файле будут отображаться кириллические буквы.

изображение страницы PDF-файла

Windows + MikTex

%%% пока не готово 

How to Export Jupyter Notebook by VSCode in PDF format? (Windows 10)

When I try to export my Jupyter Notebook in pdf format in VSCode like this: enter image description here enter image description here then I got this error:
enter image description here and jupyter output panel says: enter image description here so i tried to install MikTeX and update the required packages, but still I can’t export Jupyter Notebooks in PDF format by VSCode!
how can I fix this problem? Note That I know i can do it by convert it to HTML and then with ctrl+p try to save it as pdf! but I want to convert it to pdf in straight way!

  • python
  • visual-studio-code
  • jupyter-notebook
  • export-to-pdf

asked Sep 3, 2021 at 19:32
5,357 4 4 gold badges 16 16 silver badges 48 48 bronze badges

7 Answers 7

Since I’m using conda venvs, I did these steps:

  1. Activate conda venv using: conda activate in Anaconda prompt.
  2. Install nbconvert using conda install -c anaconda nbconvert

Now it’s all okay, and I can export Jupyter notebooks in HTML and PDF format both.

Update

Also, you should consider that nbconvert is compatible with Python 3.7-3.9 based on the official doc.

answered Feb 8, 2022 at 8:15
5,357 4 4 gold badges 16 16 silver badges 48 48 bronze badges

You can try following URL. Hope it will solve your issue

I just tried in Linux(Ubuntu 20.04) and it worked for me

You can follow this steps:

  1. sudo apt-get install texlive-xetex texlive-fonts-recommended texlive-latex-recommended
  2. Active env where you have jupyter installed
  3. Execute this command: jupyter nbconvert —to pdf your_file.ipynb

enter image description here

Output:

answered Sep 3, 2021 at 19:57
3,770 1 1 gold badge 5 5 silver badges 16 16 bronze badges

Thanks for your response. I saw that. But it didn’t work for me. Please write your attempt in specifying steps.

Sep 3, 2021 at 20:49
I just update the answer. You can try this
Sep 3, 2021 at 21:21

While this question has been answered twice neither one of the answers seemed to address the question on OP’s OS. I wanted to setup the same thing for a more streamlined workflow on Windows Jupyter development.

Unfortunately, I have been unabled to get the export as PDF button to work due to not knowing how to get VS Code to search the correct locations for the various dependencies; however, I have found a work around that allows one to export as PDF on Windows through WSL (Windows Subsystem for Linux).

WSL is a tool that I have grown to love using during all my development both professionally and within school, so I am sure you can find great use for it outside of PDF export if you do not already have it installed.

This method primarily uses the command line method for exporting using jupyter nbconvert —to pdf

This can also be used in Windows powershell; however, I have had little luck setting up the dependencies in powershell.

In WSL you can run this command and use the friendly neighbourhood Linux command line to install all the required dependencies.

Here is the documentation on how to setup nbconvert for Linux which I also found to work on WSL (https://nbconvert.readthedocs.io/en/latest/install.html)

If there are any other dependencies missing it is typically fairly easy to figure out how to install these through the command line.

Как сохранить jupyter notebook в pdf?

[I 23:49:31.834 NotebookApp] Writing 64127 bytes to .\notebook.tex
[I 23:49:31.834 NotebookApp] Building PDF
[I 23:49:31.844 NotebookApp] Running xelatex 3 times: [‘xelatex’, ‘.\\notebook.tex’, ‘-quiet’]
[I 23:49:44.891 NotebookApp] Running bibtex 1 time: [‘bibtex’, ‘.\\notebook’]
[W 23:49:45.240 NotebookApp] b had problems, most likely because there were no citationss

так же в ноутбуке нет русских комментариев, они просто не передались в pdf.
Пробовал pip install -U «notebook

  • Вопрос задан более трёх лет назад
  • 4194 просмотра

3 комментария

Простой 3 комментария

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *