def pdf(request):
Sales_by_employee = Sales.objects.all().order_by('Employee_code')
open("database/temp.html", "w").write(render_to_string("database/Sales_by_employee.html",
{'Sales_by_employee': Sales_by_employee}))
pdf = html2pdf("database/temp.html")
return HttpResponse(pdf, content_type='application/pdf')
import os
from io import BytesIO
from django.http import HttpResponse
from django.template.loader import get_template
from xhtml2pdf import pisa
from django.conf import settings
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
def html2pdf(template_source, context_dict={}):
template = get_template(template_source)
html = template.render(context_dict)
result = BytesIO()
pdf = pisa.pisaDocument(BytesIO(html.encode('UTF-8')), result, link_callback=fetch_pdf_resources, encoding='utf-8')
if not pdf.err:
return HttpResponse(result.getvalue(), content_type="application/pdf")
return None
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
{% load static %}
<html dir="ltr" lang="ru-RU">
<head>
<!-- <meta charset="utf-8"> -->
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>Отчёт</title>
<link href="{% static 'database/arial.ttf' %}" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<style type="text/css">
@font-face {
font-family: Arial;
src: url(./static/database/arial.ttf);
}
body {
font-family: Arial, sans-serif;
}
table {
background: white;
border: 3px black solid; /* стиль внешней рамки */
}
td {
background: white;
border: 3px black solid; /* стиль рамки ячеек */
padding: 0.2em;
}
th {
background: white;
border: 3px black solid; /* стиль рамки заголовков */
padding: 0.2em;
}
</style>
</head>
from io import BytesIO
from django.http import HttpResponse
from django.template.loader import get_template
from xhtml2pdf import pisa
def fetch_pdf_resources(uri, rel):
if uri.find(settings.STATIC_URL) != 0:
# path = os.path.join(settings.STATIC_ROOT, uri.replace(settings.STATIC_URL, ''))
path = 'C:/Web/Apteka_05/apteka/database/templates/database/font.ttf'
else:
path = None
print(path)
return path
def html2pdf(template_source, context_dict={}):
template = get_template(template_source)
html = template.render(context_dict)
result = BytesIO()
pdf = pisa.pisaDocument(BytesIO(html.encode("UTF-8")), result, encoding='utf-8',
link_callback=fetch_pdf_resources)
if not pdf.err:
return HttpResponse(result.getvalue(), content_type='application/pdf')
else:
return HttpResponse("Error Rendering PDF", status=400)