如何将非ascii字符添加到文件名中?
问题描述:
我试图下载包含俄文单词到文件名的pdf文件时遇到问题。我使用了pdfkit工具。如何将非ascii字符添加到文件名中?
def get_pdf_document(request, code):
host = request.scheme + "://" + request.META["HTTP_HOST"]
uri = reverse('documents:view_signed_document',
kwargs={'code': code}) + "?is_pdf=true"
obj = get_object_or_404(DownloadCode, code=code)
options = {
'page-size': 'A4',
'encoding': "UTF-8",
'no-outline': None,
'margin-bottom': '17',
'margin-left': '10',
'margin-right': '10',
'margin-top': '10',
'footer-html': host + reverse('api:pdf-footer', kwargs={'code': code}),
}
if obj.doc_type == ACTS_TYPE or obj.doc_type == LISTS_TYPE:
options['orientation'] = 'Landscape'
result = pdfkit.from_url(host + uri, False, options=options)
response = HttpResponse(result, content_type='application/pdf')
response[
'Content-Disposition'] = 'attachment; filename=\"{}-{}.pdf\"'.format(GET_DOC_TYPE[obj.doc_type], code)
response['Content-Length'] = response.tell()
return response
,我有这些常数变量:
PDF_INVOICE = u"СЧЕТ-ФАКТУРА"
PDF_ACT = u"АКТ"
PDF_LIST = u"НАКЛАДНАЯ"
PDF_PAYMENT = u"СЧЕТ НА ОПЛАТУ"
PDF_RECON = u"АКТ СВЕРКИ"
PDF_COMMON = u"НЕФОРМАЛИЗОВАННЫЙ"
GET_DOC_TYPE = {
INVOICE_TYPE: PDF_INVOICE,
ACTS_TYPE: PDF_ACT,
LISTS_TYPE: PDF_LIST,
PAYMENTS_TYPE: PDF_PAYMENT,
RECONS_TYPE: PDF_RECON,
COMMONS_TYPE: PDF_COMMON,
}
和我的错误消息:
'ascii' codec can't encode characters in position 0-2: ordinal not in range(128)
,我不知道如何解决这个问题。请帮助
答
编码常数变量utf-8
格式
PDF_INVOICE = (u"СЧЕТ-ФАКТУРА").encode('utf-8')
感谢ü,它的真正的工作,但我还添加# - * - 编码:UTF-8 - * - 在文件的顶部,为什么它不起作用 –
尝试'# - * - coding:utf-8 - * - '而不是'# - coding:utf-8 --' –