Django-pdf响应编码错误-reportlab

问题描述 投票:1回答:1

我正在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

示例两个文件从相同的字节IO生成:

A。本地文件B。共享的FileResponse或HttpResponse文件:enter image description here

[奇怪的是,我点击招摇中的“下载”链接后使用“打开方式”选项,并且选择了其他程序,例如“ wps pdf”我将在生成的pdf中获得其他字符。]

使用wps pdf]从swagger

链接直接打开pdf:enter image description here

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

python django character-encoding pdf-generation reportlab
1个回答
0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.