当我尝试以下操作时:
from reportlab.lib.pagesizes import letter
from reportlab.pdfgen.canvas import Canvas
import urllib
import StringIO
import PIL.Image
image_file = urllib.urlopen('https://www.google.com/images/srpr/logo11w.png')
image_string = StringIO.StringIO(image_file.read())
logo = PIL.Image.open(image_string)
canvas = Canvas('output.pdf', pagesize=letter)
canvas.drawImage(logo, 10, 10)
canvas.showPage()
canvas.save()
我收到此错误:
Traceback (most recent call last):
File "imagefromurl.py", line 12, in <module>
canvas.drawImage(logo, 10, 10)
File "/usr/lib/python2.7/dist-packages/reportlab/pdfgen/canvas.py", line 857, in drawImage
imgObj = pdfdoc.PDFImageXObject(name, image, mask=mask)
File "/usr/lib/python2.7/dist-packages/reportlab/pdfbase/pdfdoc.py", line 2090, in __init__
ext = string.lower(os.path.splitext(source)[1])
File "/usr/lib/python2.7/posixpath.py", line 96, in splitext
return genericpath._splitext(p, sep, altsep, extsep)
File "/usr/lib/python2.7/genericpath.py", line 91, in _splitext
sepIndex = p.rfind(sep)
File "/usr/lib/python2.7/dist-packages/PIL/Image.py", line 515, in __getattr__
raise AttributeError(name)
Reportlab是2.5版本。
答案 0 :(得分:18)
我正在努力做到这一点。这样做(还添加了必要的掩码以避免透明变黑):
from reportlab.lib.pagesizes import letter
from reportlab.pdfgen.canvas import Canvas
from reportlab.lib.utils import ImageReader
logo = ImageReader('https://www.google.com/images/srpr/logo11w.png')
canvas = Canvas('output.pdf', pagesize=letter)
canvas.drawImage(logo, 10, 10, mask='auto')
canvas.showPage()
canvas.save()
虽然艰难的方法可以让我发现无法获取图像网址并处理它(例如替换本地图像),但事实并非如此。