Giter VIP home page Giter VIP logo

notebook-as-pdf's Introduction

Jupyter Notebooks as PDF

Binder

This Jupyter notebook extension allows you to save your notebook as a PDF.

Three new features compared to the official "save as PDF" extension:

  1. produce a PDF with the smallest number of page breaks,
  2. the original notebook is attached to the PDF; and
  3. this extension does not require LaTex.

The created PDF will have as few pages as possible, in many cases only one. This is useful if you are exporting your notebook to a PDF for sharing with others who will view it on a screen.

Every <h1> tag in the notebook will be converted into a entry in the table of contents of the PDF.

To make it easier to reproduce the contents of the PDF at a later date the original notebook is attached to the PDF. Unfortunately not all PDF viewers know how to deal with attachments. PDF viewers known to support downloading of file attachments are: Acrobat Reader, pdf.js and evince. The pdftk CLI program can also extract attached files from a PDF. Preview for OSX does not know how to display/give you access to attachments of PDF files.

Install

To use this bundler you need to install it:

python -m pip install -U notebook-as-pdf
pyppeteer-install

The second command will download and setup Chromium. It is used to perform the HTML to PDF conversion.

On linux you probably also need to install some or all of the APT packages listed in binder/apt.txt.

Use it

Create a notebook and the click "File -> Download As". Click the new menu entry called "PDF via HTML". Your notebook will be converted to a PDF on the fly and then downloaded.

You can also use it with nbconvert:

jupyter-nbconvert --to pdfviahtml example.ipynb

which will create a file called example.pdf.

You will have to use Acrobat Reader to see the attachment to your PDF. Preview on OSX can not display PDF attachments.

notebook-as-pdf's People

Contributors

aleksandrtulenkov avatar betatim avatar bollwyvl avatar ian-r-rose avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

notebook-as-pdf's Issues

Question: how to enable notebook-as-pdf for multiple user in jupyterhub

Hi, i have installed the littlest jupyterhub and I would like to enable the notebook-as-pdf functionality for all users. However, if I install the package as admin, the 'Save and export notebook as > PDFviaHTML' options only appears in my own interface, not in the interface of the other users. How to fix this?

Nbconvert executes notebook twice using PDFviaHTML

I realized that when executing my notebook and converting it to PDF, it would execute the notebook twice.

I run the following command. It only happens when I convert to PDFviaHTML.
How do I know it runs twice? The jupyter notebook code saved a text file with the timestamp as the name.
Every time I use the following command it saves 2 files which confirms the behavior.

jupyter-nbconvert --ExecutePreprocessor.timeout=1200 --to PDFviaHTML --TemplateExporter.exclude_input=True --execute "Untitled.ipynb"

image

Landscape mode

I tried to convert my nb into a pdf but some lines were cut, is there a way of use landscape print?

Basic tests on osx, linux and windows

Thsi project should be able to run on windows, osx and linux. Testing all different platforms is hard, in particular because each individual doesn't have access to all of the platforms.

Setting up some basics tests that are cross-platform would be great.

Check out #4 (comment) for details on how to do this.

C++ dependency for pikepdf

I have a dependency issue which gives an 500 error in Jupyter, when launching a notebook:

Maybe there should be an uninstall instruction too in README.md for notebook-as-pdf?

Trying to figure out how to install C++ for me.

      File "D:\Anaconda3\lib\site-packages\notebook_as_pdf\__init__.py", line 17, in <module>
        import pikepdf
      File "D:\Anaconda3\lib\site-packages\pikepdf\__init__.py", line 23, in <module>
        raise ImportError(msg) from _e
    ImportError: pikepdf's extension library failed to import
    You may need to install Microsoft Visual C++ 2015-2019 Redistributable (x64) 14.24.28127 or newer.
[E 09:58:58.821 NotebookApp] {
      "Host": "localhost:8888",
      "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:75.0) Gecko/20100101 Firefox/75.0",
      "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
      "Accept-Language": "ru-RU,ru;q=0.8,en-US;q=0.5,en;q=0.3",
      "Accept-Encoding": "gzip, deflate",
      "Connection": "keep-alive",
      "Referer": "http://localhost:8888/tree",
      "Cookie": "username-localhost-8888=\"2|1:0|10:1587452334|23:username-localhost-8888|44:NDcwOWExYzVmZDkwNGNmYjhjMjhlNzVlYjJkYzFmZDA=|cae321ef80ae41f77680e7c093e875a1fe0fe404d8a71f478da4e19adc05adf6\"; _xsrf=2|74b6ff90|1909c13bb95219015f931aeab6200e4b|1586880665; username-localhost-8889=\"2|1:0|10:1587452291|23:username-localhost-8889|44:MTY2Y2E3OTMwYTRiNGNhNGIzYzAxNzU4NDEwYmFjMjY=|8195ac1e2f0f3c9a58234ab56b31c4149b95c3124ae8ca2cb4a168cf892c8cd1\"",
      "Upgrade-Insecure-Requests": "1"
    }
[E 09:58:58.823 NotebookApp] 500 GET /notebooks/corporate2.ipynb (127.0.0.1) 312.82ms referer=http://localhost:8888/tree

Make pikepdf dependency optional

pikepdf relies on qpdf which means a C++ compiler is needed to install it (I think). This can be tricky on Windows.

There are no Windows packages on conda-forge either.

Maybe it makes sense to make attaching the notebook to the PDF an optional feature to make it easier to install on Windows.

Fails when run as root

Thanks for this! As much as I like LaTeX on occasion, it's nice to have another option.

I have found that this exporter fails when run as root due to Chrome sandboxing policies. Might we add an option to turn off sandboxing?

cf. ian-r-rose@9d92490

puppeteer.chromium_downloader connection fail

Hi there,

I installed the package but the chromium downloader fails or gets stuck (I am using a Windows server behind a proxy).

Any thoughts on workarounds that I can try? I have Chromium installed already.

Thanks!
Ana

Failure in gitlab CI

I am really excited for this extension, since it would allow a much leaner docker image in my CI runners.

The runner configuration is pretty simple:

image: python:latest

build:
  stage: build
  script:
    - pip install --no-cache-dir -r requirements.txt
    - jupyter nbconvert --to PDFviaHTML --execute example.ipynb

and of course, notebook-as-pdf is part of requirements.txt.

So I took it for a spin, but it was not a happy camper:

$ jupyter nbconvert --to PDFviaHTML --execute example.ipynb
 [NbConvertApp] Converting notebook example.ipynb to PDFviaHTML
 [NbConvertApp] Executing notebook with kernel: python3
 [NbConvertApp] Executing notebook with kernel: python3
 [W:pyppeteer.chromium_downloader] start chromium download.
 Download may take a few minutes.
 100%|██████████| 108773488/108773488 [00:01<00:00, 105172481.75it/s]
 [W:pyppeteer.chromium_downloader] 
 chromium download done.
 [W:pyppeteer.chromium_downloader] chromium extracted to: /root/.local/share/pyppeteer/local-chromium/588429
 Traceback (most recent call last):
<snip>
 Traceback (most recent call last):
   File "/usr/local/lib/python3.8/site-packages/pyppeteer/launcher.py", line 151, in _close_process
     self._loop.run_until_complete(self.killChrome())
   File "/usr/local/lib/python3.8/asyncio/base_events.py", line 591, in run_until_complete
     self._check_closed()
   File "/usr/local/lib/python3.8/asyncio/base_events.py", line 508, in _check_closed
     raise RuntimeError('Event loop is closed')
 RuntimeError: Event loop is closed
 sys:1: RuntimeWarning: coroutine 'Launcher.killChrome' was never awaited
 RuntimeWarning: Enable tracemalloc to get the object allocation traceback

I'm wondering if my requirements.txt needs something else (why is chromium installed on demand?) but instead of blindly trying things out, I thought I should report it first.

Click to toggle the full log.
Running with gitlab-runner 13.0.1 (21cb397c)
   on default-runner-7f9b6f57bc-t25l7 JXQu29S9
Preparing the "docker" executor
00:06
 Using Docker executor with image python:latest ...
 WARNING: Container based cache volumes creation is disabled. Will not create volume for "/cache"
 Pulling docker image python:latest ...
 Using docker image sha256:7f5b6ccd03e9da5e02a20ea4377ae61f6ae1b935b05c1bd52fdafe4b958b5e50 for python:latest ...
Preparing environment
00:02
 Running on runner-jxqu29s9-project-94480-concurrent-0 via default-runner-7f9b6f57bc-t25l7...
Getting source from Git repository
00:02
 Fetching changes with git depth set to 50...
 Initialized empty Git repository in /builds/adavid/mylittlelark/.git/
 Created fresh repository.
 From https://gitlab.cern.ch/adavid/mylittlelark
  * [new ref]         refs/pipelines/1751602 -> refs/pipelines/1751602
  * [new branch]      master                 -> origin/master
 Checking out 48add964 as master...
 Skipping Git submodules setup
Restoring cache
00:01
Downloading artifacts
00:02
Running before_script and script
01:23
 $ pip install --no-cache-dir -r requirements.txt
 Collecting jupyter
   Downloading jupyter-1.0.0-py2.py3-none-any.whl (2.7 kB)
 Collecting pympler
   Downloading Pympler-0.8.tar.gz (175 kB)
 Collecting lark-parser
   Downloading lark-parser-0.8.9.tar.gz (294 kB)
 Collecting tqdm
   Downloading tqdm-4.46.1-py2.py3-none-any.whl (63 kB)
 Collecting tables
   Downloading tables-3.6.1-cp38-cp38-manylinux1_x86_64.whl (4.3 MB)
 Collecting notebook-as-pdf
   Downloading notebook_as_pdf-0.2.0-py3-none-any.whl (5.2 kB)
 Collecting ipywidgets
   Downloading ipywidgets-7.5.1-py2.py3-none-any.whl (121 kB)
 Collecting nbconvert
   Downloading nbconvert-5.6.1-py2.py3-none-any.whl (455 kB)
 Collecting jupyter-console
   Downloading jupyter_console-6.1.0-py2.py3-none-any.whl (21 kB)
 Collecting ipykernel
   Downloading ipykernel-5.3.0-py3-none-any.whl (119 kB)
 Collecting notebook
   Downloading notebook-6.0.3-py3-none-any.whl (9.7 MB)
 Collecting qtconsole
   Downloading qtconsole-4.7.5-py2.py3-none-any.whl (118 kB)
 Collecting numexpr>=2.6.2
   Downloading numexpr-2.7.1-cp38-cp38-manylinux1_x86_64.whl (164 kB)
 Collecting numpy>=1.9.3
   Downloading numpy-1.19.0-cp38-cp38-manylinux2010_x86_64.whl (14.6 MB)
 Collecting pyppeteer
   Downloading pyppeteer-0.2.2-py3-none-any.whl (145 kB)
 Collecting PyPDF2
   Downloading PyPDF2-1.26.0.tar.gz (77 kB)
 Collecting widgetsnbextension~=3.5.0
   Downloading widgetsnbextension-3.5.1-py2.py3-none-any.whl (2.2 MB)
 Collecting ipython>=4.0.0; python_version >= "3.3"
   Downloading ipython-7.16.1-py3-none-any.whl (785 kB)
 Collecting traitlets>=4.3.1
   Downloading traitlets-4.3.3-py2.py3-none-any.whl (75 kB)
 Collecting nbformat>=4.2.0
   Downloading nbformat-5.0.7-py3-none-any.whl (170 kB)
 Collecting defusedxml
   Downloading defusedxml-0.6.0-py2.py3-none-any.whl (23 kB)
 Collecting pygments
   Downloading Pygments-2.6.1-py3-none-any.whl (914 kB)
 Collecting jupyter-core
   Downloading jupyter_core-4.6.3-py2.py3-none-any.whl (83 kB)
 Collecting entrypoints>=0.2.2
   Downloading entrypoints-0.3-py2.py3-none-any.whl (11 kB)
 Collecting pandocfilters>=1.4.1
   Downloading pandocfilters-1.4.2.tar.gz (14 kB)
 Collecting mistune<2,>=0.8.1
   Downloading mistune-0.8.4-py2.py3-none-any.whl (16 kB)
 Collecting jinja2>=2.4
   Downloading Jinja2-2.11.2-py2.py3-none-any.whl (125 kB)
 Collecting testpath
   Downloading testpath-0.4.4-py2.py3-none-any.whl (163 kB)
 Collecting bleach
   Downloading bleach-3.1.5-py2.py3-none-any.whl (151 kB)
 Collecting jupyter-client
   Downloading jupyter_client-6.1.3-py3-none-any.whl (106 kB)
 Collecting prompt-toolkit!=3.0.0,!=3.0.1,<3.1.0,>=2.0.0
   Downloading prompt_toolkit-3.0.5-py3-none-any.whl (351 kB)
 Collecting tornado>=4.2
   Downloading tornado-6.0.4.tar.gz (496 kB)
 Collecting pyzmq>=17
   Downloading pyzmq-19.0.1-cp38-cp38-manylinux1_x86_64.whl (1.1 MB)
 Collecting prometheus-client
   Downloading prometheus_client-0.8.0-py2.py3-none-any.whl (53 kB)
 Collecting Send2Trash
   Downloading Send2Trash-1.5.0-py3-none-any.whl (12 kB)
 Collecting terminado>=0.8.1
   Downloading terminado-0.8.3-py2.py3-none-any.whl (33 kB)
 Collecting ipython-genutils
   Downloading ipython_genutils-0.2.0-py2.py3-none-any.whl (26 kB)
 Collecting qtpy
   Downloading QtPy-1.9.0-py2.py3-none-any.whl (54 kB)
 Collecting appdirs<2.0.0,>=1.4.3
   Downloading appdirs-1.4.4-py2.py3-none-any.whl (9.6 kB)
 Collecting urllib3<2.0.0,>=1.25.8
   Downloading urllib3-1.25.9-py2.py3-none-any.whl (126 kB)
 Collecting websockets<9.0,>=8.1
   Downloading websockets-8.1-cp38-cp38-manylinux2010_x86_64.whl (78 kB)
 Collecting pyee<8.0.0,>=7.0.1
   Downloading pyee-7.0.2-py2.py3-none-any.whl (12 kB)
 Collecting jedi>=0.10
   Downloading jedi-0.17.1-py2.py3-none-any.whl (1.4 MB)
 Collecting pexpect; sys_platform != "win32"
   Downloading pexpect-4.8.0-py2.py3-none-any.whl (59 kB)
 Requirement already satisfied: setuptools>=18.5 in /usr/local/lib/python3.8/site-packages (from ipython>=4.0.0; python_version >= "3.3"->ipywidgets->jupyter->-r requirements.txt (line 1)) (47.1.1)
 Collecting pickleshare
   Downloading pickleshare-0.7.5-py2.py3-none-any.whl (6.9 kB)
 Collecting backcall
   Downloading backcall-0.2.0-py2.py3-none-any.whl (11 kB)
 Collecting decorator
   Downloading decorator-4.4.2-py2.py3-none-any.whl (9.2 kB)
 Collecting six
   Downloading six-1.15.0-py2.py3-none-any.whl (10 kB)
 Collecting jsonschema!=2.5.0,>=2.4
   Downloading jsonschema-3.2.0-py2.py3-none-any.whl (56 kB)
 Collecting MarkupSafe>=0.23
   Downloading MarkupSafe-1.1.1-cp38-cp38-manylinux1_x86_64.whl (32 kB)
 Collecting packaging
   Downloading packaging-20.4-py2.py3-none-any.whl (37 kB)
 Collecting webencodings
   Downloading webencodings-0.5.1-py2.py3-none-any.whl (11 kB)
 Collecting python-dateutil>=2.1
   Downloading python_dateutil-2.8.1-py2.py3-none-any.whl (227 kB)
 Collecting wcwidth
   Downloading wcwidth-0.2.5-py2.py3-none-any.whl (30 kB)
 Collecting ptyprocess; os_name != "nt"
   Downloading ptyprocess-0.6.0-py2.py3-none-any.whl (39 kB)
 Collecting parso<0.8.0,>=0.7.0
   Downloading parso-0.7.0-py2.py3-none-any.whl (100 kB)
 Collecting pyrsistent>=0.14.0
   Downloading pyrsistent-0.16.0.tar.gz (108 kB)
 Collecting attrs>=17.4.0
   Downloading attrs-19.3.0-py2.py3-none-any.whl (39 kB)
 Collecting pyparsing>=2.0.2
   Downloading pyparsing-2.4.7-py2.py3-none-any.whl (67 kB)
 Building wheels for collected packages: pympler, lark-parser, PyPDF2, pandocfilters, tornado, pyrsistent
   Building wheel for pympler (setup.py): started
   Building wheel for pympler (setup.py): finished with status 'done'
   Created wheel for pympler: filename=Pympler-0.8-py3-none-any.whl size=164713 sha256=3e8ab23edf19d99c51f5b7a9a1bf74ebbb9f947a6d9ebade2ff8c0a7ad75083f
   Stored in directory: /tmp/pip-ephem-wheel-cache-pivp50fy/wheels/2c/09/38/7c8c5dc224099d3a7194d154a99093d429bb4bda18c241c4b5
   Building wheel for lark-parser (setup.py): started
   Building wheel for lark-parser (setup.py): finished with status 'done'
   Created wheel for lark-parser: filename=lark_parser-0.8.9-py2.py3-none-any.whl size=75357 sha256=990a32661454b7b77d1df1858328ea40daa9bac5ce84bebc0be6cb43a5246b33
   Stored in directory: /tmp/pip-ephem-wheel-cache-pivp50fy/wheels/5c/55/8c/91a8363366ada1c946e50d5c030e63129a2d8f3120e1975997
   Building wheel for PyPDF2 (setup.py): started
   Building wheel for PyPDF2 (setup.py): finished with status 'done'
   Created wheel for PyPDF2: filename=PyPDF2-1.26.0-py3-none-any.whl size=61084 sha256=b1f7402d283104baebace712c6dd94abb940019a8acd38feaf5903eb11954f19
   Stored in directory: /tmp/pip-ephem-wheel-cache-pivp50fy/wheels/b1/1a/8f/a4c34be976825a2f7948d0fa40907598d69834f8ab5889de11
   Building wheel for pandocfilters (setup.py): started
   Building wheel for pandocfilters (setup.py): finished with status 'done'
   Created wheel for pandocfilters: filename=pandocfilters-1.4.2-py3-none-any.whl size=7856 sha256=75791b53889332212a9cbf41d5ba54a30932ae76bec3902bc753298f58305841
   Stored in directory: /tmp/pip-ephem-wheel-cache-pivp50fy/wheels/f6/08/65/e4636b703d0e870cd62692dafd6b47db27287fe80cea433722
   Building wheel for tornado (setup.py): started
   Building wheel for tornado (setup.py): finished with status 'done'
   Created wheel for tornado: filename=tornado-6.0.4-cp38-cp38-linux_x86_64.whl size=427821 sha256=978cecc354d37b4422e9f08fe5949afad94728628d849b74d1c6870ac25c0171
   Stored in directory: /tmp/pip-ephem-wheel-cache-pivp50fy/wheels/88/79/e5/598ba17e85eccf2626eab62e4ee8452895636cd542650d450d
   Building wheel for pyrsistent (setup.py): started
   Building wheel for pyrsistent (setup.py): finished with status 'done'
   Created wheel for pyrsistent: filename=pyrsistent-0.16.0-cp38-cp38-linux_x86_64.whl size=126675 sha256=87e75b33c767b74b59c2ae526d335a2be64aab5cf3b983c519171a6aaceff172
   Stored in directory: /tmp/pip-ephem-wheel-cache-pivp50fy/wheels/17/be/0f/727fb20889ada6aaaaba861f5f0eb21663533915429ad43f28
 Successfully built pympler lark-parser PyPDF2 pandocfilters tornado pyrsistent
 Installing collected packages: six, python-dateutil, tornado, ipython-genutils, decorator, traitlets, jupyter-core, pyzmq, jupyter-client, MarkupSafe, jinja2, defusedxml, pygments, entrypoints, pandocfilters, mistune, testpath, pyrsistent, attrs, jsonschema, nbformat, pyparsing, packaging, webencodings, bleach, nbconvert, parso, jedi, ptyprocess, pexpect, pickleshare, backcall, wcwidth, prompt-toolkit, ipython, ipykernel, prometheus-client, Send2Trash, terminado, notebook, widgetsnbextension, ipywidgets, jupyter-console, qtpy, qtconsole, jupyter, pympler, lark-parser, tqdm, numpy, numexpr, tables, appdirs, urllib3, websockets, pyee, pyppeteer, PyPDF2, notebook-as-pdf
 Successfully installed MarkupSafe-1.1.1 PyPDF2-1.26.0 Send2Trash-1.5.0 appdirs-1.4.4 attrs-19.3.0 backcall-0.2.0 bleach-3.1.5 decorator-4.4.2 defusedxml-0.6.0 entrypoints-0.3 ipykernel-5.3.0 ipython-7.16.1 ipython-genutils-0.2.0 ipywidgets-7.5.1 jedi-0.17.1 jinja2-2.11.2 jsonschema-3.2.0 jupyter-1.0.0 jupyter-client-6.1.3 jupyter-console-6.1.0 jupyter-core-4.6.3 lark-parser-0.8.9 mistune-0.8.4 nbconvert-5.6.1 nbformat-5.0.7 notebook-6.0.3 notebook-as-pdf-0.2.0 numexpr-2.7.1 numpy-1.19.0 packaging-20.4 pandocfilters-1.4.2 parso-0.7.0 pexpect-4.8.0 pickleshare-0.7.5 prometheus-client-0.8.0 prompt-toolkit-3.0.5 ptyprocess-0.6.0 pyee-7.0.2 pygments-2.6.1 pympler-0.8 pyparsing-2.4.7 pyppeteer-0.2.2 pyrsistent-0.16.0 python-dateutil-2.8.1 pyzmq-19.0.1 qtconsole-4.7.5 qtpy-1.9.0 six-1.15.0 tables-3.6.1 terminado-0.8.3 testpath-0.4.4 tornado-6.0.4 tqdm-4.46.1 traitlets-4.3.3 urllib3-1.25.9 wcwidth-0.2.5 webencodings-0.5.1 websockets-8.1 widgetsnbextension-3.5.1
 $ jupyter nbconvert --to html --execute example.ipynb
 [NbConvertApp] Converting notebook example.ipynb to html
 [NbConvertApp] Executing notebook with kernel: python3
 [NbConvertApp] Writing 342781 bytes to example.html
 $ jupyter nbconvert --to PDFviaHTML --execute example.ipynb
 [NbConvertApp] Converting notebook example.ipynb to PDFviaHTML
 [NbConvertApp] Executing notebook with kernel: python3
 [NbConvertApp] Executing notebook with kernel: python3
 [W:pyppeteer.chromium_downloader] start chromium download.
 Download may take a few minutes.
 100%|██████████| 108773488/108773488 [00:01<00:00, 105172481.75it/s]
 [W:pyppeteer.chromium_downloader] 
 chromium download done.
 [W:pyppeteer.chromium_downloader] chromium extracted to: /root/.local/share/pyppeteer/local-chromium/588429
 Traceback (most recent call last):
   File "/usr/local/bin/jupyter-nbconvert", line 8, in <module>
     sys.exit(main())
   File "/usr/local/lib/python3.8/site-packages/jupyter_core/application.py", line 270, in launch_instance
     return super(JupyterApp, cls).launch_instance(argv=argv, **kwargs)
   File "/usr/local/lib/python3.8/site-packages/traitlets/config/application.py", line 664, in launch_instance
     app.start()
   File "/usr/local/lib/python3.8/site-packages/nbconvert/nbconvertapp.py", line 340, in start
     self.convert_notebooks()
   File "/usr/local/lib/python3.8/site-packages/nbconvert/nbconvertapp.py", line 510, in convert_notebooks
     self.convert_single_notebook(notebook_filename)
   File "/usr/local/lib/python3.8/site-packages/nbconvert/nbconvertapp.py", line 481, in convert_single_notebook
     output, resources = self.export_single_notebook(notebook_filename, resources, input_buffer=input_buffer)
   File "/usr/local/lib/python3.8/site-packages/nbconvert/nbconvertapp.py", line 410, in export_single_notebook
     output, resources = self.exporter.from_filename(notebook_filename, resources=resources)
   File "/usr/local/lib/python3.8/site-packages/nbconvert/exporters/exporter.py", line 179, in from_filename
     return self.from_file(f, resources=resources, **kw)
   File "/usr/local/lib/python3.8/site-packages/nbconvert/exporters/exporter.py", line 197, in from_file
     return self.from_notebook_node(nbformat.read(file_stream, as_version=4), resources=resources, **kw)
   File "/usr/local/lib/python3.8/site-packages/notebook_as_pdf/__init__.py", line 148, in from_notebook_node
     self.pool.submit(
   File "/usr/local/lib/python3.8/concurrent/futures/_base.py", line 439, in result
     return self.__get_result()
   File "/usr/local/lib/python3.8/concurrent/futures/_base.py", line 388, in __get_result
     raise self._exception
   File "/usr/local/lib/python3.8/concurrent/futures/thread.py", line 57, in run
     result = self.fn(*self.args, **self.kwargs)
   File "/usr/local/lib/python3.8/asyncio/runners.py", line 43, in run
     return loop.run_until_complete(main)
   File "/usr/local/lib/python3.8/asyncio/base_events.py", line 616, in run_until_complete
     return future.result()
   File "/usr/local/lib/python3.8/site-packages/notebook_as_pdf/__init__.py", line 107, in notebook_to_pdf
     await html_to_pdf(f.name, pdf_path)
   File "/usr/local/lib/python3.8/site-packages/notebook_as_pdf/__init__.py", line 24, in html_to_pdf
     browser = await launch(handleSIGINT=False, handleSIGTERM=False, handleSIGHUP=False)
   File "/usr/local/lib/python3.8/site-packages/pyppeteer/launcher.py", line 305, in launch
     return await Launcher(options, **kwargs).launch()
   File "/usr/local/lib/python3.8/site-packages/pyppeteer/launcher.py", line 166, in launch
     self.browserWSEndpoint = get_ws_endpoint(self.url)
   File "/usr/local/lib/python3.8/site-packages/pyppeteer/launcher.py", line 225, in get_ws_endpoint
     raise BrowserError('Browser closed unexpectedly:\n')
 pyppeteer.errors.BrowserError: Browser closed unexpectedly:
 Error in atexit._run_exitfuncs:
 Traceback (most recent call last):
   File "/usr/local/lib/python3.8/site-packages/pyppeteer/launcher.py", line 151, in _close_process
     self._loop.run_until_complete(self.killChrome())
   File "/usr/local/lib/python3.8/asyncio/base_events.py", line 591, in run_until_complete
     self._check_closed()
   File "/usr/local/lib/python3.8/asyncio/base_events.py", line 508, in _check_closed
     raise RuntimeError('Event loop is closed')
 RuntimeError: Event loop is closed
 sys:1: RuntimeWarning: coroutine 'Launcher.killChrome' was never awaited
 RuntimeWarning: Enable tracemalloc to get the object allocation traceback
Running after_script
00:02
Uploading artifacts for failed job
00:03
 ERROR: Job failed: exit code 1

KeyError: 'template_paths' on M1 Mac, Big Sur 11.2

I recently upgraded my old macbook where pdf export worked absolutely fine. Installed the same way on my new m1 mac mini, now the option of exporting does not appear in jupyterlab and when trying to export via terminal I get the following error:

Traceback (most recent call last):
  File "/Users/User/opt/anaconda3/lib/python3.8/site-packages/traitlets/traitlets.py", line 535, in get
    value = obj._trait_values[self.name]
KeyError: 'template_paths'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Users/User/opt/anaconda3/bin/jupyter-nbconvert", line 11, in <module>
    sys.exit(main())
  File "/Users/User/opt/anaconda3/lib/python3.8/site-packages/jupyter_core/application.py", line 270, in launch_instance
    return super(JupyterApp, cls).launch_instance(argv=argv, **kwargs)
  File "/Users/User/opt/anaconda3/lib/python3.8/site-packages/traitlets/config/application.py", line 845, in launch_instance
    app.start()
  File "/Users/User/opt/anaconda3/lib/python3.8/site-packages/nbconvert/nbconvertapp.py", line 350, in start
    self.convert_notebooks()
  File "/Users/User/opt/anaconda3/lib/python3.8/site-packages/nbconvert/nbconvertapp.py", line 518, in convert_notebooks
    cls = get_exporter(self.export_format)
  File "/Users/User/opt/anaconda3/lib/python3.8/site-packages/nbconvert/exporters/base.py", line 102, in get_exporter
    if getattr(exporter(config=config), 'enabled', True):
  File "/Users/User/opt/anaconda3/lib/python3.8/site-packages/notebook_as_pdf/__init__.py", line 204, in __init__
    super().__init__(config=with_default_config, **kw)
  File "/Users/User/opt/anaconda3/lib/python3.8/site-packages/nbconvert/exporters/templateexporter.py", line 325, in __init__
    super().__init__(config=config, **kw)
  File "/Users/User/opt/anaconda3/lib/python3.8/site-packages/nbconvert/exporters/exporter.py", line 114, in __init__
    self._init_preprocessors()
  File "/Users/User/opt/anaconda3/lib/python3.8/site-packages/nbconvert/exporters/templateexporter.py", line 491, in _init_preprocessors
    conf = self._get_conf()
  File "/Users/User/opt/anaconda3/lib/python3.8/site-packages/nbconvert/exporters/templateexporter.py", line 507, in _get_conf
    for path in map(Path, self.template_paths):
  File "/Users/User/opt/anaconda3/lib/python3.8/site-packages/traitlets/traitlets.py", line 575, in __get__
    return self.get(obj, cls)
  File "/Users/User/opt/anaconda3/lib/python3.8/site-packages/traitlets/traitlets.py", line 538, in get
    default = obj.trait_defaults(self.name)
  File "/Users/User/opt/anaconda3/lib/python3.8/site-packages/traitlets/traitlets.py", line 1578, in trait_defaults
    return self._get_trait_default_generator(names[0])(self)
  File "/Users/User/opt/anaconda3/lib/python3.8/site-packages/traitlets/traitlets.py", line 975, in __call__
    return self.func(*args, **kwargs)
  File "/Users/User/opt/anaconda3/lib/python3.8/site-packages/nbconvert/exporters/templateexporter.py", line 518, in _template_paths
    template_names = self.get_template_names()
  File "/Users/User/opt/anaconda3/lib/python3.8/site-packages/nbconvert/exporters/templateexporter.py", line 608, in get_template_names
    raise ValueError('Unsupported mimetype %r for template %r, mimetypes supported are: \n\t%s' %\
ValueError: Unsupported mimetype 'application/pdf' for template 'lab', mimetypes supported are: 
	text/html

Thankful for any help,
Cheers

Text outside code cells is selected backwards

When selecting text that is outside of the code cells, it is selected as if all the letters were put backwards. (So it becomes impossible to copy.)
Inside the code cells it is selected correctly.

inverted text

correct text

Installation dependencies?

This is more a question than an issue on itself 😄

The installation procedure for notebook-as-pdf is quite straightforward:

python -m pip install notebook-as-pdf
pyppeteer-install

I had a quick look at the files inside the binder repo that are used to build the demo with mybinder:

  • notebook-as-pdf is installed through requirements.txt
  • and the postBuild script runs pyppeteer-install

However, the apt.txt file contains a list of Ubuntu/Debian libraries. Are they related to the installation of notebook-as-pdf on itself?

Option to save pdf not exist

Option to save pdf not exist - just small scrool bar? Or something like this (artefact)
pyPDF2 3.0.1
notebook_as_pdf-0.5.0-py3-none-any.whl
Jupyter Version: 7.0.6
FF 120.0.1

no menu

Custom page height?

Hi!

Thanks for the package, I've so far found it very useful for several projects!

Alas I currently have the problem that I need to deliver some notebooks as PDFs but client requires there to be A4-size page breaks.
I quickly found this line, which I assume controls when a page break is inserted (i.e. for the 200 inch Adobe limit).

I've cloned the repo, changed height to 11.7 * 72 (for A4 standard) and reinstalled the package from my local copy. Unfortunately I still only get single page PDFs.
Is this the right place to be changing the page height limit? Or should I look somewhere else?

Many thanks for your time!
Kieran

(P.S. my deadline is Sunday 11th of April, so any help before then would be greatly appreciated. Thanks!!)

Page width as config option

For some applications the default width (994px) is wider than optimal. It would be useful to have a command line option to allow the user to choose an effective browser page width.

json version issue?

Hi, thanks very much for this, it is just what I need for a project I'm developing to use markdown generated from code. It makes very nice notebook output, allowing text and figure captions. What it lacks is a nice way to generate a PDF.
However, my first attempt to use if fails with the message from, I guess chromium:
nbconvert failed: GET /json/version HTTP/1.1

the version of json, in the latest jupyter, is 2.0.

Embedding local images via markdown doesn't work

Hi, very helpful extension. Thanks for your work!

There is just one problem that I have noticed.
If I embed an image via HTML (Image(filename = "my_file.png")) then it will perfectly work but if I embed it as a markdown (![title](my_file.png)), then it will not be converted in the pdf file.

nbconvert failed: module 'asyncio' has no attribute 'run'

hi, I am current use python 3.6, and I have installed notebook-as-pdf, when I create pdf and download it from menu, meet the error nbconvert failed: module 'asyncio' has no attribute 'run', the error detailed info is below:
[I 2020-09-25 10:56:00.901 SingleUserNotebookApp log:158] 101 GET /research/user/18621009317/api/kernels/e05d5cb2-25ee-4ac5-9b5e-5d13e2b7f561/channels?session_id=aed108f1902345d78d12bd5f616ba207 ([email protected]) 577.30ms
[E 2020-09-25 10:57:17.935 SingleUserNotebookApp handlers:133] nbconvert failed: module 'asyncio' has no attribute 'run'
Traceback (most recent call last):
File "/root/anaconda3/lib/python3.6/site-packages/notebook/nbconvert/handlers.py", line 130, in get
resources=resource_dict
File "/root/anaconda3/lib/python3.6/site-packages/notebook_as_pdf/init.py", line 166, in from_notebook_node
asyncio.run,
AttributeError: module 'asyncio' has no attribute 'run'
[W 2020-09-25 10:57:17.936 SingleUserNotebookApp web:1667] 500 GET /research/user/18621009317/nbconvert/PDFviaHTML/1.0%E7%BB%84%E5%90%88%E5%91%A8%E6%9C%9F%E9%80%89%E8%82%A1.ipynb?download=true (58.247.201.152): nbconvert failed: module 'asyncio' has no attribute 'run'

how can I change something to make it compatible with python 3.6, currently, I don't want to update to python 3.7, as there are a lot of stuffs to update. thanks!

Image results are not shown in the PDF if `%matplotlib` magic commands are used

Hello there, loving your Project so far.
I just tried using it to export some explanations on how to use matplotlib and realized the following:

Problem:

When using magic comments like %matplotlib notebook or %matplotlib widget to produce interactive plot windows, the results are not displayed in the final PDF.
This is not a huge issue as you can comment out these commands and run the notebook again to get it into a state where the export works, but I feel this is an unnecessary step that could be avoided.

Example code:

Here is a example cell so you can test it yourselfe:

%matplotlib widget

from matplotlib import pyplot as plt
from math import sin

x = list(range(100))
y = [sin(x) for x in x]

plt.plot(x,y)

some analysis:

Looking at the actual json data, it seems like the image is just there in the same form in both cases. So from my perspective the same functionality could be used to display both image types

Json representation without magic:

"outputs": [
    {
        "output_type": "execute_result",
        "data": {
            "text/plain": [
                "[<matplotlib.lines.Line2D at 0x229ac10ba30>]"
            ]
        },
        "metadata": {},
        "execution_count": 1
    },
    {
        "output_type": "display_data",
        "data": {
            "image/png": "loads of base64...", //here is the actuall image 
            "text/plain": [
                "<Figure size 432x288 with 1 Axes>"
            ]
        },
        "metadata": {
            "needs_background": "light"
        }
    }
],

Json representation with magic:

"outputs": [
    {
        "output_type": "execute_result",
        "data": {
            "text/plain": [
                "[<matplotlib.lines.Line2D at 0x229aef84dc0>]"
            ]
        },
        "metadata": {},
        "execution_count": 2
    },
    {
        "output_type": "display_data",
        "data": {
            "application/vnd.jupyter.widget-view+json": {
                "version_major": 2,
                "version_minor": 0,
                "model_id": "c9dfc6ced3c74d28882947a564d6eb03"
            },
            "image/png": "loads of base64...", //more or less the same as above
            "text/plain": [
                "Canvas(toolbar=Toolbar(toolitems=[('Home', 'Reset original view', 'home', 'home'), ('Back', 'Back to previous …"
            ]
        },
        "metadata": {}
    }
],

nbconvert v6.0.3 issue

I have updated nbconvert and that created issues with this package.

  File "c:\python3\lib\site-packages\nbconvert\nbconvertapp.py", line 350, in start
    self.convert_notebooks()
  File "c:\python3\lib\site-packages\nbconvert\nbconvertapp.py", line 524, in convert_notebooks
    self.convert_single_notebook(notebook_filename)
  File "c:\python3\lib\site-packages\nbconvert\nbconvertapp.py", line 489, in convert_single_notebook
    output, resources = self.export_single_notebook(notebook_filename, resources, input_buffer=input_buffer)
  File "c:\python3\lib\site-packages\nbconvert\nbconvertapp.py", line 418, in export_single_notebook
    output, resources = self.exporter.from_filename(notebook_filename, resources=resources)
  File "c:\python3\lib\site-packages\nbconvert\exporters\exporter.py", line 181, in from_filename
    return self.from_file(f, resources=resources, **kw)
  File "c:\python3\lib\site-packages\nbconvert\exporters\exporter.py", line 199, in from_file
    return self.from_notebook_node(nbformat.read(file_stream, as_version=4), resources=resources, **kw)
  File "c:\python3\lib\site-packages\notebook_as_pdf\__init__.py", line 227, in from_notebook_node
    heading_positions = self.pool.submit(
  File "c:\python3\lib\concurrent\futures\_base.py", line 432, in result
    return self.__get_result()
  File "c:\python3\lib\concurrent\futures\_base.py", line 388, in __get_result
    raise self._exception
  File "c:\python3\lib\concurrent\futures\thread.py", line 57, in run
    result = self.fn(*self.args, **self.kwargs)
  File "c:\python3\lib\site-packages\nest_asyncio.py", line 29, in run
    loop = asyncio.get_event_loop()
  File "c:\python3\lib\asyncio\events.py", line 639, in get_event_loop
    raise RuntimeError('There is no current event loop in thread %r.'
RuntimeError: There is no current event loop in thread 'ThreadPoolExecutor-0_0'.
sys:1: RuntimeWarning: coroutine 'notebook_to_pdf' was never awaited

Multiple Pages?

Hello everyone,

notebook-as-pdf... I have been waiting for years for this functionality! Great work!

Would it be feasible to add a feature that allows for exporting multiple pages?

Best,
Tristan

nbconvert failed: module 'asyncio' has no attribute 'run'

I am on Python 3.6.9 and trying to download a Jupyter Notebook with markdown cells (containing HTML code) to PDF. I could not find a conda package version of notebook-as-pdf and so I used pip install. However, when tying to download (File > Download as > PDF via HTML (.pdf) I receive the following error: nbconvert failed: module 'asyncio' has no attribute 'run'

Also receive the following error when attempting to download via Python or Anaconda command prompt with: jupyter-nbconvert --to pdfviahtml C:\Users\myProfile\Documents\Jupyter_Notebook\Announcement\Announcement.ipynb

(arcgispro-py3) C:\Users\myProfile>jupyter-nbconvert --to pdfviahtml C:\Users\myProfile\Documents\Jupyter_Notebook\Announcement\Announcement.ipynb
Traceback (most recent call last):
File "C:\Users\myProfile\MyPrograms\ESRI_ArcGIS_Pro\bin\Python\envs\arcgispro-py3\Scripts\jupyter-nbconvert-script.py", line 10, in
sys.exit(main())
File "C:\Users\myProfile\MyPrograms\ESRI_ArcGIS_Pro\bin\Python\envs\arcgispro-py3\lib\site-packages\jupyter_core\application.py", line 270, in launch_instance
return super(JupyterApp, cls).launch_instance(argv=argv, **kwargs)
File "C:\Users\myProfile\MyPrograms\ESRI_ArcGIS_Pro\bin\Python\envs\arcgispro-py3\lib\site-packages\traitlets\config\application.py", line 658, in launch_instance
app.start()
File "C:\Users\myProfile\MyPrograms\ESRI_ArcGIS_Pro\bin\Python\envs\arcgispro-py3\lib\site-packages\nbconvert\nbconvertapp.py", line 340, in start
self.convert_notebooks()
File "C:\Users\myProfile\MyPrograms\ESRI_ArcGIS_Pro\bin\Python\envs\arcgispro-py3\lib\site-packages\nbconvert\nbconvertapp.py", line 499, in convert_notebooks
cls = get_exporter(self.export_format)
File "C:\Users\myProfile\MyPrograms\ESRI_ArcGIS_Pro\bin\Python\envs\arcgispro-py3\lib\site-packages\nbconvert\exporters\base.py", line 113, in get_exporter
% (name, ', '.join(get_export_names())))
ValueError: Unknown exporter "pdfviahtml", did you mean one of: PDFviaHTML, asciidoc, custom, html, latex, markdown, notebook, pdf, python, rst, script, slides?

Custom CSS styles as config option

Sometimes the caller wants to customise the look&feel of the notebook a bit when converting it. For example making some bits of text easier to read or hiding the In [ ]/Out [ ] tags.

To help with this we could add a parameter that allows people to pass a custom CSS string via the configuration system.

PDF is just one long page?

When I open with Acrobat reader the PDF file produced from an IPython notebook I get a single, long document that Acrobat is trying to fit in a single page. How can I get multiple pages so I can actually print the PDF?

Add lower level headings to the export

Hello! Thanks for a fantastic extension, it really works quite well and is very seamless.

As you mention in your blog post, lower level headings might be coming soon to this extension:

In a future version lower level headings might be included in the table of contents. This would give you a more detailed view of the notebook structure but also more clutter in the table of contents. Maybe a better solution is to allow people to insert "bookmarks" into the notebook. Each of these bookmarks would then be a table of contents entry.

I thought I'd open an issue requesting this feature as it would be super useful for me. I use jupyter notebooks for teaching and having a nice non-paginated PDF export of a notebook would be really handy!

Todo for v0.3.0

Things to do for v0.3.0

  • make --no-sandbox the default #9
  • fix the version in setup.py to be 0.3.0 #9
  • mention additional dependencies that need to be installed #10 and #9 both had that issue
  • (stretch goal) investigate creating an outline from the <h1> tags in the notebook

nbconvert failed: Navigation Timeout Exceeded: 30000 ms exceeded.

I am currently running the File > "Download as" > "PDf via puppeteer (.html) and getting the following error:

500 : Internal Server Error
nbconvert failed: Navigation Timeout Exceeded: 30000 ms exceeded.

How can I edit the length of this timeout while still using this "Download as PDF" approach?

Python 3.6 not supported

when i run it , i get an error

nbconvert failed: module 'asyncio' has no attribute 'run'

Python 3.6 doesn't have this function

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.