@ma3xak

Как подружить Pisa с кириллицей?

Привет всем не могу понять как подуржить Pisa с кирилицей, для печати pdf, пытаюсь подключить шрифт но не работает
Как быть ?

# encoding: utf-8
from io import BytesIO
from django.http import HttpResponse
from django.template.loader import get_template

from xhtml2pdf import pisa 

def render_pdf(url_template, contexto = {}):
	template = get_template(url_template)
	html = template.render(contexto)
	result = BytesIO()
	pdf = pisa.pisaDocument(html.encode('UTF-8'), result, encodind = 'UTF-8')
	if not pdf.err:
		return HttpResponse(result.getvalue(), content_type = "application/pdf")
	return None


from __future__ import unicode_literals

from django.shortcuts import render
from django.views.generic import View
# Create your views here.
from django.http import HttpResponse
from mi_pdf.utileria  import render_pdf 

class PDFPrueba(View):
	'''
	Пишем вывод пдф
	'''
	def get(self, request, *args, **kwargs): 
		pdf = render_pdf("profiles/dogovor/dogovor.html")
		return HttpResponse(pdf ,content_type = "application/pdf")

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
	<style>
		@font-face { font-family: Arial; src: url("profiles/dogovor/arial.ttf"); }
		body{
			font-family: Arial;
		}
	</style>

Как быть не могу понять. в пдф получаю квадратики
  • Вопрос задан
  • 2440 просмотров
Решения вопроса 1
sergey-gornostaev
@sergey-gornostaev Куратор тега Django
Седой и строгий
Рендер не может сам загружать ссылки, поэтому не может получить шрифт profiles/dogovor/arial.ttf. У функции pisaDocument есть параметр link_callback, в который можно передать функцию преобразующую http-адреса в локальные пути. Например такую:
def fetch_pdf_resources(uri, rel):
    if uri.find(settings.MEDIA_URL) != -1:
        path = os.path.join(settings.MEDIA_ROOT, uri.replace(settings.MEDIA_URL, ''))
    elif uri.find(settings.STATIC_URL) != -1:
        path = os.path.join(settings.STATIC_ROOT, uri.replace(settings.STATIC_URL, ''))
    else:
        path = None
    return path


pdf = pisa.pisaDocument(BytesIO(template.encode('UTF-8')), result,
                                                           encoding='utf-8',
                                                           link_callback=fetch_pdf_resources)

И естественно, url для шрифта надо поменять на абсолютный, а сам шрифт по этому url должен быть доступен.
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы