在iPython笔记本中查看pdf图像 [英] View pdf image in an iPython Notebook

查看:95
本文介绍了在iPython笔记本中查看pdf图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码使我可以在iPython笔记本中查看png图像.有没有办法查看pdf图片?我不需要一定要使用IPython.display.我正在寻找一种将文件中的pdf图像打印到iPython笔记本输出单元格的方法.

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 Image

fig = Image(filename=('./temp/my_plot.png'))
fig

谢谢.

推荐答案

您(和其他人)面临的问题是PDF无法直接在浏览器中显示. 获得类似内容的唯一可能方法是使用图像转换器从PDF中创建PNG或JPG并显示该图像.
这可以通过imagemagick和自定义显示功能来完成.

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.

一个简单的解决方案是使用魔杖( http://docs.wand-py.org ) python-imagemagick绑定.我尝试使用Ubuntu 13.04:

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

以文本形式:

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

对于多页pdf,您可以获取例如第二页通过:

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

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

更新2

由于最近的浏览器支持使用其嵌入式pdf查看器显示pdf,因此可以将基于iframe的可能的替代解决方案实现为

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 = pdf
    self.size = size

  def _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)

该类实现html和Latex表示形式,因此pdf也可以在nbconversion转换为Latex的过程中幸免.可以像

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))

使用Firefox 33时,

With Firefox 33 this results in

这篇关于在iPython笔记本中查看pdf图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆