IPython/Jupyter Problems saving notebook as PDF - pdf

So, I've been trying to save a jupyter notebook as PDF but I just can't figure out how to do this. The first thing I try is from the file menu just download as PDF, but doing that results in:
nbconvert failed: PDF creating failed
the next thing I try is try to do the conversion from the Command Prompt like this
$ ipython nbconvert --to latex --post PDF MyNotebook.ipynb
but again, this results in an error message
ImportError: No module named 'PDF'
and if I try
$ ipython nbconvert --to latex MyNotebook.ipynb
this results in
IPython.nbconvert.utils.pandoc.PandocMissing: Pandoc wasn't found:
Please check that pandoc is installed
if I try to install pandoc (pip install pandoc), this gives me
ImportError: No module named 'ConfigParser'
and this is where I get stuck because I just don't know what else to do.
Anyone have idea how to fix whatever is wrong?

To make it work, I installed latex, typical latex extra, and pandoc.
With ubuntu:
sudo apt-get install texlive texlive-latex-extra pandoc
it takes some times: several 100 Mb to download. I read somewhere that you can use --no-install-recommends for texlive and extra to reduce to the dl.

If you are on a Mac and have Homebrew installed, open a terminal shell and install pandoc typing the command:
brew install pandoc
be patient, time to install and compile can take a while on slow internet connections or older systems.

To convert notebooks to PDF you first need to have nbconvert installed.
pip install nbconvert
# OR
conda install nbconvert
Next, if you aren't using Anaconda or haven't already, you must install pandoc either by following the instructions on their website or, on Linux, as follows:
sudo apt-get install pandoc
After that you need to have XeTex installed on your machine:
Linux : TeX Live
Mac : MacTex
Windows : MikTex
You can now navigate to the folder that holds your IPython Notebook and run the following command:
jupyter nbconvert --to pdf MyNotebook.ipynb
for further reference, please check out this link.

2015-4-22: It looks like an IPython update means that --to pdf should be used instead of --to latex --post PDF. There is a related Github issue.

For converting any Jupyter notebook to PDF, please follow the below instructions:
(Be inside Jupyter notebook):
On Mac OS:
command + P --> you will get a print dialog box --> change destination as PDF --> Click print
On Windows:
Ctrl + P --> you will get a print dialog box --> change destination as PDF --> Click print
If the above steps doesn't generate full PDF of the Jupyter notebook (probably because Chrome, some times, don't print all the outputs because Jupyter make a scroll for big outputs),
Try performing below steps for removing the auto scroll in the menu:-
Credits: #ÂngeloPolotto
In your Jupyter Notebook, click Cell on top of the jupyter notebook
Next click All output --> Toggle scrolling for removing auto scroll.

As the comments to the question say, you will need pandoc and latex (e.g. TeXShop). I installed pandoc with Homebrew, it took just a second. Having pandoc and TeXShop, I could generate latex but not pdf (on the command line).
ipython nbconvert --to latex mynotebook.ipynb
Exploring the latex (.tex) file with TeXShop, the failure was due to missing stylesheets and defs. After installing all of these (adjustbox.sty, adjcalc.sty, trimclip.sty, collectbox.sty, tc-pgf.def, ucs.sty, uni-global.def, utf8x.def, ucsencs.def), it did finally work.
However, the result looks a little too funky for my taste. It is too bad that printing the html from Safari loses the syntax coloring. Otherwise, it doesn't look so bad. (This is all on OS X).

I am using Anaconda-Jupyter Notebook on OS: Ubuntu 16.0 for Python programming.
Install Nbconvert, Pandoc, and Tex:
Open a terminal and implement the following commands in it.
Install Nbconvert: though it's part of the Jupyter ecosystem still install it once again
$conda install nbconvert
Or
$pip install nbconvert
But I will recommend using conda instead pip if you are using anaconda
Install Pandoc: since Nbconvert uses Pandoc for converting markdown to formats other than HTML. Type following command
$sudo apt-get install pandoc
Install TeX: For converting to PDF, nbconvert uses the TeX. Type following command
$sudo apt-get install texlive-xetex
After execution of these commands, close the opened notebooks refresh the home page Or restart the kernel of the opened notebook. Now try to download notebook as a pdf :)
Note: For more details, please refer the official documentation:
https://nbconvert.readthedocs.io/en/latest/install.html

This Python script has GUI to select with explorer a Ipython Notebook you want to convert to pdf. The approach with wkhtmltopdf is the only approach I found works well and provides high quality pdfs. Other approaches described here are problematic, syntax highlighting does not work or graphs are messed up.
You'll need to install wkhtmltopdf:
http://wkhtmltopdf.org/downloads.html
and
Nbconvert
pip install nbconvert
# OR
conda install nbconvert
Python script
# Script adapted from CloudCray
# Original Source: https://gist.github.com/CloudCray/994dd361dece0463f64a
# 2016--06-29
# This will create both an HTML and a PDF file
import subprocess
import os
from Tkinter import Tk
from tkFileDialog import askopenfilename
WKHTMLTOPDF_PATH = "C:/Program Files/wkhtmltopdf/bin/wkhtmltopdf" # or wherever you keep it
def export_to_html(filename):
cmd = 'ipython nbconvert --to html "{0}"'
subprocess.call(cmd.format(filename), shell=True)
return filename.replace(".ipynb", ".html")
def convert_to_pdf(filename):
cmd = '"{0}" "{1}" "{2}"'.format(WKHTMLTOPDF_PATH, filename, filename.replace(".html", ".pdf"))
subprocess.call(cmd, shell=True)
return filename.replace(".html", ".pdf")
def export_to_pdf(filename):
fn = export_to_html(filename)
return convert_to_pdf(fn)
def main():
print("Export IPython notebook to PDF")
print(" Please select a notebook:")
Tk().withdraw() # Starts in folder from which it is started, keep the root window from appearing
x = askopenfilename() # show an "Open" dialog box and return the path to the selected file
x = str(x.split("/")[-1])
print(x)
if not x:
print("No notebook selected.")
return 0
else:
fn = export_to_pdf(x)
print("File exported as:\n\t{0}".format(fn))
return 1
main()

notebook-as-pdfInstall
python -m pip install notebook-as-pdf pyppeteer-install
Use it
You can also use it with nbconvert:
jupyter-nbconvert --to PDFviaHTML filename.ipynb
which will create a file called filename.pdf.
or pip install notebook-as-pdf
create pdf from notebook jupyter-nbconvert-toPDFviaHTML

This problem was experienced with both Ubuntu and Mac OSX. After a frantic set of searches and trials, both of them were solved. This requires both tex and pandoc; both jumbo external programs cannot installed by Python's pip.
Mac OSX: using MacPorts installation of pandoc
port install pandoc
This should take nearly an hour to complete (in the usual case). If the problem persists, you might have to install MacTeX distro. of TeXLive.
For Ubuntu: install vanilla TeXLive from the network installer -- not through apt-get. Then install pandoc using apt-get.
sudo apt-get install pandoc
A complete installation of TeXLive would require a upto to 4.4 GB on disk.
To save all this trouble, the recommeded way to use IPython/Jupyter Notebook would be to install Anaconda Python distribution.

I had all kinds of problems figuring this out as well. I don't know if it will provide exactly what you need, but I downloaded my notebook as an HTML file, then pulled it up in my Chrome browser, and then printed it as a PDF file, which I saved. It captured all my code, text and graphs. It was good enough for what I needed.

If you are using sagemath cloud version, you can simply go to the left corner,
select File --> Download as --> Pdf via LaTeX (.pdf)
Check the screenshot if you want.
Screenshot Convert ipynb to pdf
If it dosn't work for any reason, you can try another way.
select File --> Print Preview and then on the preview
right click --> Print and then select save as pdf.

As a brand new member, I was unable to simply add a comment on the post but I want to second that the solution offered by Phillip Schwartz worked for me. Hopefully people in a similar situation will try that path sooner with the emphasis. Not having page breaks was a frustrating problem for quite a while so I am grateful for the discussion above.
As Phillip Schwartz said:
"You'll need to install wkhtmltopdf: [http://wkhtmltopdf.org/downloads.html][1]
and Nbconvert "
You then add a cell of the type "rawNBConvert" and include:
<p style="page-break-after:always;"></p>
That seemed to do the trick for me, and the generated PDF had the page break at the corresponding locations.
You don't need to run the custom code though, as it seems the "normal" path of downloading the notebook as HTML, opening in browser, and printing to PDF works once those utilities are installed.

To convert .ipynb into pdf, your system should contain 2 components,
nbconvert:
Is part of jupyter allows to convert ipynb to pdf
pip install nbconvert
OR
conda install nbconvert
XeTeX:
Convert ipynb to .tex format and then converting to pdf.
sudo apt-get install texlive-xetex
Then you can use below command to convert to pdf,
ipython nbconvert --to pdf YOURNOTEBOOK.ipynb
In case, it doesn't work, install pandoc and try again.
sudo apt-get install pandoc

I had problems correctly displaying some symbols with regular download as pdf. So downloaded as tex jupyter nbconvert --to latex "my notebook.ipynb", made some tweaks with notepad (as an example, in my case I needed these lines for my language
\usepackage{tgpagella}
\usepackage[lithuanian,english]{babel}
) and then exported to pdf with latex --output-format=pdf "my notebook.tex".
But finally, however, to retain the same characters as you see in a browser I ended up using my Chrome browser printing: Ctrl+P Print to pdf. It adds unnecessary header and footer but everything else remains as it is. No more errors processing tqdm progress bar, no more code going out of the page and so on. Simple as that.

In any system, the basic steps to correctly setup nbconvert to convert ipython notebooks to pdf/latex are
Install nbconvert
Install pandoc
Install Texlive
Installing nbconvert
pip install nbconvert
or conda install nbconvert
Installing pandoc
sudo apt-get install pandoc for Ubuntu
or sudo yum install pandoc for CentOS
for others visit pandoc-installation
Installing texlive
You can install recommended packages or full install. For Ubuntu
sudo apt-get install texlive texlive-xetex texlive-generic-extra texlive-generic-recommended
`
For others and to full install texlive follow the instructions given at tug as per your system and choice.
I downloaded tar.gz file from tug-texlive-download and followed instructions given at TeX Live - Quick install. Installation instructions in summary:
Clean up
rm -rf /usr/local/texlive/2019
rm -rf ~/.texlive2019
Run installer
unpack the zip file
cd /your/unpacked/directory
perl install-tl
Enter command: i
Setting path
sudo vi /etc/bash.bashrc and insert
PATH=/usr/local/texlive/2019/bin/x86_64-linux:$PATH; export PATH
MANPATH=/usr/local/texlive/2019/texmf-dist/doc/man:$MANPATH; export MANPATH
INFOPATH=/usr/local/texlive/2019/texmf-dist/doc/info:$INFOPATH; export INFOPATH
Setting default papersize
tlmgr paper letter
The commands may differ as per your system but the basic steps remains the same.

I had this error in Windows 10. I followed these three steps and it solved my problem:
Install nbconvert
pip install nbconvert
Install pandoc
https://pandoc.org/installing.html
Install miktex
https://miktex.org/download
Also it is good to update libraries:
pip install jupyter --upgrade
pip install --upgrade --user nbconvert

What I found was that the nbconvert/utils/pandoc.py had a code bug that resulted in the error for my machine. The code checks if pandoc is in your environmental variables path. For my machine the answer is no. However pandoc.exe is!
Solution was to add '.exe' to the code on line 69
if __version is None:
if not which('pandoc.exe'):
raise PandocMissing()
The same goes for 'xelatex' is not installed.
Add to the file nbconvert/exporters/pdf.py on line 94
cmd = which(command_list[0]+'.exe')

For Ubuntu users, an answer can be found here. I also quote it:
The most probable cause, is that you have not installed the
appropriate dependencies. Your Ubuntu system has to have some packages
installed regarding conversion of LaTeX and XeTeX files, in order to
save your notebook as PDF. You can install them by:
sudo apt-get install texlive texlive-xetex texlive-generic-extra texlive-generic-recommended pandoc
Also, nbconvert is another dependency that is usually automatically
installed with jupyter. But you can install it just to be sure, while
having your virtual environment activated:
pip install -U nbconvert

You may go for below simple trick (works totally well with all modern browsers; on all recent operating systems - Windows, Mac, Linux) :
Right click anywhere on your ipynb notebook.
Select Print... . This will take you to the "Print-Preview Wizard" that will show you a PDF form of your python notebook.
Provide the destination folder name. Click save.
Voila!!
This simple hack shall ofcourse save much of your time of installing nbviewer or miktex, pandoc or LaTex, etc. converter packages. Moreover, actually this hack works in same way, like you try to save an html webpage into PDF format.

Related

When I open the nvim init.vim file, this error comes for Neoclide coc.vim

I get this error when I try to open the init.vim file for neovim, for neoclide coc.vim. Any solutions? in WSL(Ubuntu)
[coc.nvim] Error on execute :pyx command, ultisnips feature of coc-snippets requires pyx support on vim. use :CocOpenLog for details
Enter command pip install pynvim in your command line. It helped me. And before this you should have python on your PC.
you choose correct version of python in init.vim
let g:python3_host_prog="/usr/bin/version python"
example
let g:python3_host_prog="/usr/bin/python3.10"
I tried with installing pynvim and also have the latest pip (21.3.1). My vim version is 9.0 and compiled it from scratch.
But while searching the features included with vim, I realised that I had not included python. After following this answer, I enabled python while compiling vim. My issue has been resolved.
I had to upgrade pip first, then run pip install pynvim.
Most likely you default python install broke for some reason on you machine (was the same for me).
Try running the python command from the terminal.
If you get command not recognized than you know this is the problem.
Reinstalling python or
set the python the python path that vim uses to an installed python version that works
let g:python3_host_prog="/usr/bin/version python"
Assuming you have python3 installed.

Is there a way to use Python 3.5 instead of 3.6?

I need to install a library that is only compatible with Python 3.5. Is there a way to change the Python version in Colaboratory from 3.6 to 3.5?
The only way to vary the Python 3 version is to connect to a local runtime.
You cannot directly change the environment for the notebook.
After hours of exploration, I found a solution:
Initialize a Ngork server in the Colaboratory notebook.
connect to the Ngork server from a local terminal using SSH (or use any editor which supports SSH connections)
Install the required Python version using the terminal.
Install virtualenv.
Create a virtual environment by specifying the Python version installed.
Activate the environment.
Work in that environment from the terminal directly.
Check out Free!! GPUs on your local machine which provides to get detailed description on how to follow the steps.
There is a way to use any version of python you want 3.5 or 3.8 in this example, without having to run a kernel locally or going through an ngrok proxy.
Download the colab notebook. Open a text editor to change the kernel specification to:
"kernelspec": {
"name": "py38",
"display_name": "Python 3.8"
}
This is the same trick as the one used with Javascript, Java, and Golang.
Then upload the edited notebook to Google Drive. Open the notebook in Google Colab. It cannot find the py38 kernel, so it use normal python3 kernel.
You need to install a python 3.8, the google-colab package and the ipykernel under the name you defined above: "py38":
!wget -O mini.sh https://repo.anaconda.com/miniconda/Miniconda3-py38_4.8.2-Linux-x86_64.sh
!chmod +x mini.sh
!bash ./mini.sh -b -f -p /usr/local
!conda install -q -y jupyter
!conda install -q -y google-colab -c conda-forge
!python -m ipykernel install --name "py38" --user
Reload the page, and voilà, you can test the version is correct:
import sys
print("User Current Version:-", sys.version)
A working example can be found there.

tensorboard: command not found

I installed TensorFlow on my MacBook Pro 10.12.5 from source code by steps described here.
https://www.tensorflow.org/install/install_sources
TensorFlow itself works well but I cannot run TensorBoard.
It seems tensorboard is not installed properly.
When I try running tensorboard --logdir=... it says -bash: tensorboard: command not found. And locate tensorboard returns empty.
Do I need any additional step to install tensorboard?
You could call tensorboard as a python module like this:
python3 -m tensorboard.main --logdir=~/my/training/dir
or add this to your .profile
alias tensorboard='python3 -m tensorboard.main'
If no other methods work then try this one. It may help you.
1. check the location of Tensorflow
pip show tensorflow
It will show output something like this.
...
Name: tensorflow
Version: 1.4.0
Location: /home/abc/xy/.local/lib/python2.7/site-packages
...
2. Go to that location you get from the above output.
cd /home/abc/xy/.local/lib/python2.7/site-packages
There you can see a directory named tensorboard.
cd tensorboard
3. There must be a file named 'main.py'.
4. Execute the following command to launch the tensorboard.
python main.py --logdir=/path/to/log_file/
If you installed Tensorflow with Virtualenv, then first Check whether you have activated the tensorflow envirnoment or not
If you have activated the tensorflow session then your command prompt will look like this :
If not, Write the below command and try running tensorboard again.
source ~/tensorflow/bin/activate
Run this command:
python3 -m tensorboard.main --logdir=logdir
To run directory you can use,
Change =logdir to ="dir/TensorFlow"
(Directory path)
What version of Tensorflow are you running? Older versions don't include Tensorboard.
If you do have a newer version, I see you are using OSX, which apparently caused some problems for other people: https://github.com/tensorflow/tensorflow/issues/2115 Check this page to fix it!
As a MacPorts user, I'm used to running things from out of the path
/opt/local/bin. When you install a python package via MacPorts, that's
where the executables go --- even if they're just symbolic links to
files to a main python repository in
/opt/local/Library/Frameworks/Python.framework/Versions/2.7/bin/
pip installs things into the latter directory, but apparently does NOT
add the symbolic link to /opt/local/bin
This has never been an issue (or even come up) for me before, because
I've only used pip to install (non-executable) packages which load
from within python. In conclusion, there is a
/opt/local/Library/Frameworks/Python.framework/Versions/2.7/bin/tensorboard
This is a pip / MacPorts-SOP mismatch / user error*, and nothing to do
with tensorboard in particular. Please close this issue. Thanks for
your help.
*my 'locate' database was in the process of updating but hadn't completed
Quickest solution -
echo "alias tensorboard='python3 -m tensorboard.main'" >> ~/.bash_profile
After adding this to your .bash_profile you can use
tensorboard --logdir=/path
If you are using pycharm in windows environment this may help:
python -m tensorboard.main --logdir=logs

Image Magic not generating thumbnail for first page of PDF Files

I have downloaded the Image Magic from the following Link:
http://www.imagemagick.org/download/linux/CentOS/i386/ImageMagick-6.9.1-3.i386.rpm
Extracted the rpm file using rpm2cpio ImageMagick-6.9.1-3.i386.rpm | cpio -idmv
Running below command to create the thumbnail for the first page of PDF
convert source.pdf[0] output.jpg
But I am getting error:
convert: No match.
Anyone has any idea why it is not working? What I am doing wrong?
Instead of installing ImageMagick, you have extracted it instead. What you would want to do is install it.
You could run yum install ImageMagick to install it, which will take care of all the necessary dependencies as well. Or, if you wanted to install using the rpm, you should run rpm -i ImageMagick-6.9.1-3.i386.rpm. I would suggest going through the yum route instead, however.
Note: The above answer is based upon the assumption that you are using CentOS or RedHat or a similar distribution. If you are using Ubuntu or a similar distribution, you would need to use apt-get install imagemagick.

Getting xkcd plots using matplotlib

The current version of matplotlib (1.3.1) supports xkcd-style plotting, but when I follow the basic instructions for generating such a plot (in iPython 1.1.0),
%pylab
plt.xkcd()
plt.plot(sin(linspace(0, 10)))
plt.title('Whoo Hoo!!!')
I get
instead of
What am I doing wrong?
To get it working, you need
matplotlib 1.3.1 (it won't work with matplotlib 1.3.0 or earlier)
sudo pip install matplotlib --upgrade
font Humor Sans
download from here or here, install (on OS X you open it and click Install)
remove the matplotlib font cache (as suggested by DanHickstein in matplotlib/issues/2269)
rm ~/.matplotlib/fontList.cache
Now, execute the code and it should work.
You do not need to change backend to TkAgg, as some people suggest. For me it works perfectly fine on 'module://IPython.kernel.zmq.pylab.backend_inline' (you can check it by plt.get_backend()).
(I had the same problem and I've solved it, at least on OS X 10.8.5, with matplotlib 1.3.1 and IPython 2.0.0; removing font cache was necessary to get the font running.)
Using ubuntu 16.04 and python 3, with matplotlib 2.0.0 installed the following fixes the problem for me.
Install Comic sans: sudo apt install fonts-humor-sans
Remove matplotlib cache: rm ~/.cache/matplotlib -r
Make sure you have fonts-humor-sans installed.
In Ubuntu/Debian, you can install them with (from the command-line):
$ sudo apt install python3-xkcd fonts-humor-sans
Then the best option (instead of deleting the matplotlib cache) is to rebuild the font manager (from within the Python interpreter, script or Jupyter notebook):
import matplotlib
matplotlib.font_manager._rebuild()
From the blog post you linked:
Also, if you want to have the font match above, be sure to download and install the Humor Sans font on your system. For matplotlib to recognize it, you may have to remove the font cache...
As far as which version of the font to download, I would try the most current.