GAE格式的Unicode字体,带有web2py / pyfpdf

时间:2013-08-04 16:40:57

标签: google-app-engine pdf web2py

我正在编写一个应用程序,其结果是pdf文件,其中包含一些带有unicode字符的文本。在GAE devserver上它运行良好,但在部署后它无法导入字体文件(在add_font()(pyfpdf)之后崩溃)。

代码是:

# -*- coding: utf-8 -*-
def fun1(): 

from gluon.contrib.pyfpdf import FPDF, HTMLMixin
class MyFPDF(FPDF, HTMLMixin):
    pass

pdf =MyFPDF()
pdf.add_font('DejaVu', '', 'DejaVuSansCondensed.ttf', uni=True)
pdf.add_page()
pdf.set_font('DejaVu','',16)
pdf.write(10,'test-ąśł')

response.headers['Content-Type']='application/pdf'
return pdf.output(dest='S')

字体文件(首次在web2py服务器上运行后生成DejaVuSansCondensed.pkl文件...)是/ gluon / contrib / fpdf / font。我没有添加任何东西到routers.py(我使用基于模式的系统)也app.yaml没有改变。我明白了:

In FILE: /base/data/home/apps/s~myapp/web2py-04.369240954601780983/applications/app3/controllers/default.py

Traceback (most recent call last):
  File "/base/data/home/apps/s~myapp/web2py-04.369240954601780983/gluon/restricted.py", line 212, in restricted
    exec ccode in environment
  File "/base/data/home/apps/s~myapp/web2py-04.369240954601780983/applications/app3/controllers/default.py", line 674, in <module>
  File "/base/data/home/apps/s~myapp/web2py-04.369240954601780983/gluon/globals.py", line 194, in <lambda>
    self._caller = lambda f: f()
  File "/base/data/home/apps/s~myapp/web2py-04.369240954601780983/applications/app3/controllers/default.py", line 493, in fun1
    pdf.add_font('DejaVu', '', 'DejaVuSansCondensed.ttf', uni=True)
  File "/base/data/home/apps/s~myapp/web2py-04.369240954601780983/gluon/contrib/fpdf/fpdf.py", line 432, in add_font
    font_dict = pickle.load(fh)
  File "/base/data/home/runtimes/python27p/python27_dist/lib/python2.7/pickle.py", line 1378, in load
    return Unpickler(file).load()
  File "/base/data/home/runtimes/python27/python27_dist/lib/python2.7/pickle.py", line 858, in load
    dispatch[key](self)
  File "/base/data/home/runtimes/python27/python27_dist/lib/python2.7/pickle.py", line 966, in load_string
    raise ValueError, "insecure string pickle"
ValueError: insecure string pickle

正如我在当地(web2py / rocket和gae)所说,它运作良好。部署后,只有这样的工作:

pdf =MyFPDF()
pdf.add_page()
pdf.set_font('Arial','',16)
pdf.write(10,'testąśł')

但没有“不寻常”的角色......

最好的解决方案是添加我的字体文件(如DejaVu),但基本上我需要任何字体的unicode字符...也许是一些“半解决方案”使用“通用GAE unicode”字体...如果它存在这样的事情......

1 个答案:

答案 0 :(得分:0)

感谢Tim的建议!

我发现some solution ......这不是最好的,但它有效......

问题在于使用GAE上的pickle。最好的解决方案(可能)是重载/重写add_font()函数,GAE以这种方式写入数据存储区而不是文件系统。仍然会出现Additionaly ValueError: insecure string pickle错误,我根据this尝试了b64编码。但我仍然得到错误。所以我的解决方案是使用注释掉/删除的部分重载add_font()函数:

if os.path.exists(unifilename):
    fh = open(unifilename)
    try:
        font_dict = pickle.load(fh)
    finally:
    fh.close()
else:

try:
    fh = open(unifilename, "w")
    pickle.dump(font_dict, fh)
    fh.close()
except IOError, e:
    if not e.errno == errno.EACCES:
        raise  # Not a permission error.

因此,这个函数每次都计算得更多,而不仅仅是从泡菜中读取数据......但它适用于GAE。