如何使用ReportLab将PNG添加到PDF中

6
我正在使用report lab,但我无法找到在platypus中添加PNG图像的方法。以下是从这里http://www.tylerlesmann.com/2009/jan/28/writing-pdfs-python-adding-images/获取的一些示例代码,但在追加PNG时出现错误。你能帮我让它正常工作吗?
#!/usr/bin/env python

import os
import urllib2
from reportlab.lib.pagesizes import letter
from reportlab.platypus import SimpleDocTemplate, Image

filename = './python-logo.png'

def get_python_image():
    """ Get a python logo image for this example """
    if not os.path.exists(filename):
        response = urllib2.urlopen(
            'http://www.python.org/community/logos/python-logo.png')
        f = open(filename, 'w')
        f.write(response.read())
        f.close()

get_python_image()

doc = SimpleDocTemplate("image.pdf", pagesize=letter)
parts = []
parts.append(Image(filename))
doc.build(parts)



---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
/media/Felipe/B1wt/<ipython-input-21-1c3c466b9184> in <module>()
     22 parts = []
     23 parts.append(Image(filename))
---> 24 doc.build(parts)
     25 

/usr/lib/python2.7/site-packages/reportlab/platypus/doctemplate.pyc in build(self, flowables, onFirstPage, onLaterPages, canvasmaker)
   1115         if onLaterPages is _doNothing and hasattr(self,'onLaterPages'):
   1116             self.pageTemplates[1].beforeDrawPage = self.onLaterPages
-> 1117         BaseDocTemplate.build(self,flowables, canvasmaker=canvasmaker)
   1118 
   1119 def progressCB(typ, value):

/usr/lib/python2.7/site-packages/reportlab/platypus/doctemplate.pyc in build(self, flowables, filename, canvasmaker)
    878                 try:
    879                     first = flowables[0]
--> 880                     self.handle_flowable(flowables)
    881                     handled += 1
    882                 except:

/usr/lib/python2.7/site-packages/reportlab/platypus/doctemplate.pyc in handle_flowable(self, flowables)
    761             canv = self.canv
    762             #try to fit it then draw it

--> 763             if frame.add(f, canv, trySplit=self.allowSplitting):
    764                 if not isinstance(f,FrameActionFlowable):
    765                     self._curPageFlowableCount += 1

/usr/lib/python2.7/site-packages/reportlab/platypus/frames.pyc in _add(self, flowable, canv, trySplit)
    157             h = y - p - s
    158             if h>0:
--> 159                 w, h = flowable.wrap(aW, h)
    160             else:
    161                 return 0

/usr/lib/python2.7/site-packages/reportlab/platypus/flowables.pyc in wrap(self, availWidth, availHeight)
    406     def wrap(self, availWidth, availHeight):
    407         #the caller may decide it does not fit.

--> 408         return self.drawWidth, self.drawHeight
    409 
    410     def draw(self):

/usr/lib/python2.7/site-packages/reportlab/platypus/flowables.pyc in __getattr__(self, a)
    400             return self._img
    401         elif a in ('drawWidth','drawHeight','imageWidth','imageHeight'):
--> 402             self._setup_inner()
    403             return self.__dict__[a]
    404         raise AttributeError("<Image @ 0x%x>.%s" % (id(self),a))

/usr/lib/python2.7/site-packages/reportlab/platypus/flowables.pyc in _setup_inner(self)
    366         height = self._height
    367         kind = self._kind
--> 368         img = self._img
    369         if img: self.imageWidth, self.imageHeight = img.getSize()
    370         if self._lazy>=2: del self._img

/usr/lib/python2.7/site-packages/reportlab/platypus/flowables.pyc in __getattr__(self, a)
    396         if a=='_img':
    397             from reportlab.lib.utils import ImageReader  #this may raise an error
--> 398             self._img = ImageReader(self._file)
    399             del self._file
    400             return self._img

/usr/lib/python2.7/site-packages/reportlab/lib/utils.pyc in __init__(self, fileName, ident)
    539         self._transparent = None
    540         self._data = None
--> 541         if _isPILImage(fileName):
    542             self._image = fileName
    543             self.fp = getattr(fileName,'fp',None)

/usr/lib/python2.7/site-packages/reportlab/lib/utils.pyc in _isPILImage(im)
    519 def _isPILImage(im):
    520     try:
--> 521         return isinstance(im,Image.Image)
    522     except ImportError:
    523         return 0

AttributeError: 'NoneType' object has no attribute 'Image'

你的代码在我使用 reportlab-2.5 和 Python 2.7 上运行良好。 - mhawke
你使用的reportlab版本是哪个? - Osmond Bishop
reportlab.platypus.Image('foo.png', width=64, height=64).drawOn(canvas, x, y) 是在 reportlab PDF 上绘制 PNG 的另一种方式。为了记录。 - Bob Stein
问题在于reportlab不支持PNG格式,必须是JPEG图像文件。 - Conor
1个回答

8
您需要安装 PIL (Python Imaging Library),例如:
pip install PIL

我猜测如果导入PIL失败,Image会被设置为None。如果reportlab源代码容易浏览的话,我会进行确认。
编辑:我们来看一下:
try:
    import Image
    if PIL_WARNINGS: warnOnce('Python Imaging Library not available as package; upgrade   your installation!')
except ImportError, errMsg:
    _checkImportError(errMsg)
    Image = None

现在执行 pip install Pillow - Bob Stein

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接