0

这是我第一次使用 ReportLab,我尝试制作简单的 pdf,但是当我尝试运行脚本时出现以下错误。

class ReportLabTest (webapp.RequestHandler):

    def get(self):
        c = canvas.Canvas("hello.pdf")
        c.translate(inch,inch)
        c.setFont("Helvetica", 80)
        c.setStrokeColorRGB(0.2,0.5,0.3)
        c.setFillColorRGB(1,0,1)
        c.rect(inch,inch,6*inch,9*inch, fill=1)
        c.rotate(90)
        c.setFillColorRGB(0,0,0.77)
        c.drawString(3*inch, -3*inch, "Hello World")
        c.showPage()
        c.save()
        self.write_response(c)
        self.response.headers['Content-Type'] = 'application/pdf'
        self.response.headers['Content-Disposition'] = 'filename=testpdf.pdf'

        return 

我得到的错误是:

Traceback (most recent call last):
  File "/home/ducos/google_appengine/google/appengine/ext/webapp/_webapp25.py", line 710, in \__call__
        handler.get(*groups)

  File "/home/ducos/workspace/MedeticWS/www/tests.py", line 572, in get
        c.save()

  File "/home/ducos/workspace/MedeticWS/reportlab/pdfgen/canvas.py", line 1123, in save
        self._doc.SaveToFile(self._filename, self)

  File "/home/ducos/workspace/MedeticWS/reportlab/pdfbase/pdfdoc.py", line 234, in SaveToFile
        f = open(filename, "wb")

  File "/home/ducos/google_appengine/google/appengine/tools/dev_appserver_import_hook.py", line 589, in __init__
        raise IOError('invalid mode: %s' % mode)

IOError: invalid mode: wb

谢谢你的帮助。

4

2 回答 2

2

根据先前的答案,您无法写入文件系统。但是,您可以提供类似设备的文件作为参数而不是文件名。从画布的来源You may pass a file-like object to filename as an alternative to a string.

So you can create a StringIO object pass it to Canvas, and then rather than calling save() which may close the device (I am not sure on this - see below). do showpage() if you haven't already and the perform getvalue() on the StringIO object to for your response.write(). e.g.

from StringIO import StringIO
x = StringIO()
c = canvas.Canvas(x)
... dostuff
c.save()
output = x.getvalue()
self.write_response(output)

Just checked, if a file like handle is provided then it doesn't call close so a save() would be fine.

于 2012-08-25T00:45:06.823 回答
1

无法写入 AppEngine 中的文件。因此,该save()方法在尝试打开文件进行写入时失败。

您可以使用该getpdfdata()方法并将其保存到数据存储区或 Blob 存储区。

于 2012-08-24T16:54:25.287 回答