【问题标题】:When I want to use the python reportlab to save a pdf ,I get the trouble when using path with nonASCII characters?当我想使用 python reportlab 保存 pdf 时,在使用非 ASCII 字符的路径时遇到麻烦?
【发布时间】:2015-03-26 23:52:26
【问题描述】:

我写了一些简单的函数来从reportlab生成pdf,但是当路径是非ASCII(例如中文)时,会出现问题UnicodeDecodeError: 'utf8' codec can't decode byte 0xd0 in position 3: invalid continuation byte。当路径全是 ASCII 时,一切都很好。

我的代码很简单,就像

from reportlab.lib.pagesizes import letter, A4, landscape  
from reportlab.platypus import SimpleDocTemplate, Image  
from reportlab.lib.units import inch  
from reportlab.pdfgen import canvas
from reportlab import rl_settings
import reportlab.lib.pagesizes

filename_pdf = path + path.split('/')[-2]+'.pdf'
c = canvas.Canvas(filename_pdf, pagesize=maxsize )
#some code
c.save()

【问题讨论】:

    标签: python pdf pdf-generation reportlab python-unicode


    【解决方案1】:
    filename_pdf = filename_pdf.decode('gbk','ignore')
    

    【讨论】:

    • 谢谢,我可以用你的方法解决我的问题。但我不明白为什么。能详细解释一下吗?
    • @mrbean 很高兴。 filename_pdf 最初是用 gbk 编码的。这是由操作系统和执行环境决定的。您需要对其进行解码以使其可识别以进行进一步处理。否则python会认为是ASCII,自然会抛出异常。
    猜你喜欢
    • 2016-04-15
    • 2017-04-09
    • 2021-03-24
    • 1970-01-01
    • 2013-11-11
    • 2015-08-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多