View pdf image in an iPython Notebook

2024/11/20 17:31:02

The following code allows me to view a png image in an iPython notebook. Is there a way to view pdf image? I don't need to use IPython.display necessarily. I am looking for a way to print a pdf image in a file to the iPython notebook output cell.

## This is for an `png` image
from IPython.display import Imagefig = Image(filename=('./temp/my_plot.png'))
fig

Thank you.

Answer

The problem you (and others) face is that PDFs cannot be displayed directly in the browser. The only possible way to get something similar is to use an image-converter to create a PNG or JPG out of the PDF and display this one.
This could be done via imagemagick and a custom display function.

Update 1

A simple solution is to use wand (http://docs.wand-py.org) a python-imagemagick binding. I tried with Ubuntu 13.04:

wand session in ipython

In text form:

from wand.image import Image as WImage
img = WImage(filename='hat.pdf')
img

For a multi-page pdf, you can get e.g. the second page via:

img = WImage(filename='hat.pdf[1]')

Update 2

As recent browsers support to display pdfs with their embedded pdf viewer a possible alternative solution based on an iframe can be implemented as

class PDF(object):def __init__(self, pdf, size=(200,200)):self.pdf = pdfself.size = sizedef _repr_html_(self):return '<iframe src={0} width={1[0]} height={1[1]}></iframe>'.format(self.pdf, self.size)def _repr_latex_(self):return r'\includegraphics[width=1.0\textwidth]{{{0}}}'.format(self.pdf)

This class implements html and latex representations, hence the pdf will also survive a nbconversion to latex. It can be used like

PDF('hat.pdf',size=(300,250))

With Firefox 33 this results in enter image description here

https://en.xdnf.cn/q/26295.html

Related Q&A

Is the use of del bad?

I commonly use del in my code to delete objects:>>> array = [4, 6, 7, hello, 8] >>> del(array[array.index(hello)]) >>> array [4, 6, 7, 8] >>> But I have heard many …

Find how many lines in string

I am creating a python movie player/maker, and I want to find the number of lines in a multiple line string. I was wondering if there was any built in function or function I could code to do this:x = &…

AttributeError: Cant get attribute new_block on module pandas.core.internals.blocks

I was using pyspark on AWS EMR (4 r5.xlarge as 4 workers, each has one executor and 4 cores), and I got AttributeError: Cant get attribute new_block on <module pandas.core.internals.blocks. Below is…

Disable python import sorting in VSCode

I am trying to disable vscode from formatting my python imports when I save my file. I have some code that must run in between various imports so order is important, but every time I save it just shove…

Log-log lmplot with seaborn

Can Seaborns lmplot plot on log-log scale? This is lmplot with linear axes: import numpy as np import pandas as pd import seaborn as sns x = 10**arange(1, 10) y = 10** arange(1,10)*2 df1 = pd.DataFra…

Django on IronPython

I am interested in getting an install of Django running on IronPython, has anyone had any success getting this running with some level of success? If so can you please tell of your experiences, perfo…

How to create a DataFrame while preserving order of the columns?

How can I create a DataFrame from multiple numpy arrays, Pandas Series, or Pandas DataFrames while preserving the order of the columns?For example, I have these two numpy arrays and I want to combine …

Dynamically limiting queryset of related field

Using Django REST Framework, I want to limit which values can be used in a related field in a creation. For example consider this example (based on the filtering example on https://web.archive.org/web/…

How to clear GPU memory after PyTorch model training without restarting kernel

I am training PyTorch deep learning models on a Jupyter-Lab notebook, using CUDA on a Tesla K80 GPU to train. While doing training iterations, the 12 GB of GPU memory are used. I finish training by sav…

cryptography is required for sha256_password or caching_sha2_password

Good day. Hope your all are well. Can someone help me with fix this? Im new to the MySQL environment. Im trying to connect to MySQL Database remotely. I used the following python code and got this err…