Как ipynb перевести в pdf
Перейти к содержимому

Как ipynb перевести в pdf

  • автор:

Экспорт из 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

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

Convert (Jupyter Notebook) to

Convert (Jupyter Notebook) documents to format, edit and optimize documents online and free.

Convert IPYNB to PDF
Loading Uploader.
if you have uploaded a file, it will be displayed.
Confirm Cancel

Tags:

Jupyter Notebook (.ipynb)

An IPYNB file (Interactive Python Notebook) is a notebook document created by Jupyter Notebook, an interactive environment for students and scientists to analyze data using Python language. IPYNB files are usually converted to PDF, HTML, DOCX, RTF, and LaTeX formats.

Portable Document Fomat (.pdf)

PDF stands for Portable Document Format. It is a versatile file format created by Adobe in 1992 to present and exchange documents independent of software, hardware, and operating systems. It is now an open standard maintained by the International Organization for Standardization (ISO). PDFs can contain links, buttons, form fields, audio, video, and business logic and can be signed electronically. They can easily be viewed using the free Adobe Acrobat Reader software.

How to Convert IPYNB to PDF with Three Easy Ways

Sometimes, you may need to convert IPYNB to PDF for some reason. How to convert IPYNB to PDF? There are different ways to do that depending on your preferences and tools. In this post, MiniTool PDF Editor shows you three methods.

What Is an IPYNB File

IPYNB (stand for Interactive Python Notebook) files are notebook documents created by Jupyter Notebook, an interactive environment for students and scientists to analyze data using Python language. IPYNB files are usually converted to PDF, HTML, DOCX, and LaTeX formats for sharing, viewing, and printing.

Compared to IPYNB files, PDF files are more portable and compatible and you can easily share, view, and print PDF files on any device or platform. Besides, PDF files can preserve the formatting and features of your IPYNB files. In addition, PDF files can be encrypted and protected with passwords or permissions.

How to Convert IPYNB to PDF

There are several solutions that you can try according to your need.

Way 1. Use Online IPYNB to PDF Converters

One of the easiest ways to convert IPYNB to PDF is to use an online IPYNB to PDF converter, such as Vertopal, Sejda PDF, AllDocs, etc. Vertopal is a free online converter that supports over 200 file formats, including IPYNB and PDF. To use Vertopal, follow these steps:

Step 1. Go to the Vertopal official website. Then click Choose File to select the target IPYNB file from your computer, Google Drive, or Dropbox.

Step 2. Then click Convert and wait for the conversion to complete.

Step 3. Once done, download your PDF file on your local computer.

Way 2. Use a Print Option

Another way to convert IPYNB to PDF is to use a print option from Notepad or Jupyter Notebook app. This method may not preserve all the formatting and features of your IPYNB file, but it is a quick and simple solution. Here is how to do that:

Step 1. Open your IPYNB file with Notepad. Then click File > Print. Alternatively, you can press Ctrl + P to open the Print window.

Step 2. In the pop-up window, select Microsoft Print to PDF as the Printer and click the Print button.

Step 3. In the output window, click Save, name your PDF file, and choose a location to save.

save as PDF

Way 3. Use Google Collab

Google Colab is a free online service that allows you to create and run Jupyter notebooks in the cloud. You can use a command line tool called nbconvert to convert IPYNB to PDF. However, this requires that you have LaTeX installed on your system.

1. You can install LaTeX and nbconvert on Colab using the following commands:

!apt-get install texlive texlive-xetex texlive-latex-extra pandoc

!pip install pypandoc

2. Then you can run the following command to download your Colab IPYNB file as a PDF which will be saved on your Google Drive. Replace file_name.ipynb with the name of your IPYNB file.

!wget -nc https://raw.githubusercontent.com/brpy/colab-pdf/master/colab_pdf.py

from colab_pdf import colab_pdf

colab_pdf(‘file_name.ipynb’)

If the command is not working, you can also use Google Colab to download your IPYNB file as a PDF file.

Step 1. Go to Google Colab’s official website and upload your IPYNB file to open.

Step 2. Then click the File tab and select Print. You can directly press Ctrl + P to open the Print dialog box.

Step 3. Then choose Save as PDF as the destination printer. You can adjust the layout, margins, scale, and other settings of your PDF file.

Step 4. Once done, click Save, select a location, and name your PDF file.

A Method to Open and Edit PDF

After you get the PDF file, you can read and edit it using an easy-to-use PDF editing tool like MiniTool PDF Editor. It supports multiple functions and allows you to convert multiple file formats, merge PDFs, create PDFs, compress PDFs, draw PDF files, etc. with simple clicks. If you don’t have a PDF reader installed on your computer, you can download this tool to have a try.

MiniTool PDF Editor

Conclusion

We have learned three methods to convert IPYNB to PDF in this post. Do you have other nice ways to convert IPYNB to PDF? You can feel free to share them with us in the following comment zone.

  • facebook
  • twitter
  • linkedin
  • reddit

About The Author

Alin is a new member of MiniTool. Her articles are mainly about disk management, hard disk issues, and PDF editing. She is enthusiastic about acquiring computer knowledge and helping users to solve problems with computers. To provide more useful and professional solutions, she will keep learning and know more computer knowledge.

Jupyter – конвертация ноутбуков

Файлы ноутбуков Jupyter имеют расширение .ipynb . Записная книжка отображается в веб-браузере с помощью приложения Записная книжка. Его можно экспортировать в различные форматы файлов, используя параметр загрузки в меню файлов. Jupyter также имеет интерфейс командной строки в виде опции nbconvert . По умолчанию nbconvert экспортирует записную книжку в формат HTML. Вы можете использовать следующую команду для этой цели –

jupyter nbconvert mynotebook.ipynb

Это преобразует mynotebook.ipynb в mynotebook.html . Другой формат экспорта указывается в предложении `–to` .

Обратите внимание, что другие опции включают [‘asciidoc’, ‘custom’, ‘html’, ‘latex’, ‘markdown’, ‘notebook’, ‘pdf’, ‘python’, ‘rst’, ‘script’, ‘slides’]

HTML включает в себя «базовые» и «полные» шаблоны. Вы можете указать это в командной строке, как показано ниже –

jupyter nbconvert --to html --template basic mynotebook.ipynb

LaTex – формат подготовки документов, используемый специально для научного набора текста. Jupyter включает шаблоны «base», «article» и «report».

jupyter nbconvert --to latex –template report mynotebook.ipynb

Чтобы создать PDF через латекс, используйте следующую команду –

jupyter nbconvert mynotebook.ipynb --to pdf

Записную книжку можно экспортировать в слайд-шоу HTML. Преобразование использует Reveal.js в фоновом режиме. Чтобы обслуживать слайды HTTP-сервером, добавьте –postserve в командной строке. Чтобы создавать слайды, не требующие подключения к Интернету, просто поместите библиотеку Reveal.js в тот же каталог, где находится your_talk.slides.html .

jupyter nbconvert myslides.ipynb --to slides --post serve

Опция уценки конвертирует ноутбук в простой вывод уценки. Ячейки уценки не затрагиваются, а ячейки кода с отступом 4 пробела.

--to markdown

Вы можете использовать первую опцию, чтобы преобразовать блокнот в базовый вывод reStructuredText. Это полезно в качестве отправной точки для встраивания записных книжек в документы Sphinx.

--to rst

Это самый простой способ получить скрипт Python (или другой язык, в зависимости от ядра) из блокнота.

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

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