【问题标题】:Django - pdf response has wrong encoding - reportlabDjango - pdf 响应的编码错误 - reportlab
【发布时间】:2025-11-30 10:15:02
【问题描述】:

我正在 Django 后端开发 PDF 生成器。我使用 reportlab。它似乎工作,但编码不正确。当我使用变音符号时,它会得到错误的字符/符号。

问题非常类似于: Django - pdf response has wrong encoding - xhtml2pdf

但我使用 reportlab,它允许添加字体。 我在reportlab中注册了支持波兰变音符号的字体:“Aleo”。

pdfmetrics.registerFont(TTFont('Aleo', './resources/fonts/Aleo/Aleo-Light.ttf'))
pdfmetrics.registerFont(TTFont('AleoBd', './resources/fonts/Aleo/Aleo-Bold.ttf'))
pdfmetrics.registerFont(TTFont('AleoIt', './resources/fonts/Aleo/Aleo-Italic.ttf'))
pdfmetrics.registerFont(TTFont('AleoBI', './resources/fonts/Aleo/Aleo-BoldItalic.ttf'))
registerFontFamily('Aleo', normal='Aleo', bold='AleoBd', italic='AleoIt', boldItalic='AleoBI')

在 djagno 中输出 pdf 的示例:

file_response = Album.pdf_generator(request.user, request.data.get('album_id'))

# Make copy to save local pdf file and send via django
binary_copy = deepcopy(file_response)
with open('test.pdf', 'wb') as f:
    f.write(binary_copy.read())

content_type = {'pdf': 'application/pdf'}

response = HttpResponse(file_response, content_type=content_type)
response['Content-Disposition'] = 'attachment; filename=moja_nazwa.pdf'
# response = FileResponse(file_response, as_attachment=True, filename='hello.pdf')
return response

从相同的 bytesIO 生成的两个文件示例:

A.本地文件 B. 共享 FileResponse 或 HttpResponse 文件:

奇怪的是,如果我在 swagger 中单击“下载”链接后使用“打开方式”选项,然后选择其他程序,例如"wps pdf" 我将在生成的 pdf 中获取其他字符..

使用 wps pdf 直接从 swagger 的链接打开 pdf:

【问题讨论】:

    标签: python django character-encoding pdf-generation reportlab


    【解决方案1】:

    分析问题,我终于找到了创建pdf编码错误的原因。问题不在于reportlab,而在于Swagger,他在共享文件时将其内容视为文本数据而不是二进制数据。

    【讨论】:

      最近更新 更多