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

查看:31
本文介绍了在 iPython Notebook 中查看 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	extwidth]{{{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 Notebook 中查看 pdf 图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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