Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
93 changes: 93 additions & 0 deletions assets/certificates/fonts/Lobster-OFL.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
Copyright 2010 The Lobster Project Authors (https://github.com/impallari/The-Lobster-Font), with Reserved Font Name "Lobster".

This Font Software is licensed under the SIL Open Font License, Version 1.1.
This license is copied below, and is also available with a FAQ at:
http://scripts.sil.org/OFL


-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------

PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font creation
efforts of academic and linguistic communities, and to provide a free and
open framework in which fonts may be shared and improved in partnership
with others.

The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply
to any document created using the fonts or their derivatives.

DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.

"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).

"Original Version" refers to the collection of Font Software components as
distributed by the Copyright Holder(s).

"Modified Version" refers to any derivative made by adding to, deleting,
or substituting -- in part or in whole -- any of the components of the
Original Version, by changing formats or by porting the Font Software to a
new environment.

"Author" refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.

PERMISSION & CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed, modify,
redistribute, and sell modified and unmodified copies of the Font
Software, subject to the following conditions:

1) Neither the Font Software nor any of its individual components,
in Original or Modified Versions, may be sold by itself.

2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.

3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the corresponding
Copyright Holder. This restriction only applies to the primary font name as
presented to the users.

4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.

5) The Font Software, modified or unmodified, in part or in whole,
must be distributed entirely under this license, and must not be
distributed under any other license. The requirement for fonts to
remain under this license does not apply to any document created
using the Font Software.

TERMINATION
This license becomes null and void if any of the above conditions are
not met.

DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.
Binary file added assets/certificates/fonts/Lobster-Regular.ttf
Binary file not shown.
Binary file added assets/certificates/fonts/PTSerif-Bold.ttf
Binary file not shown.
93 changes: 93 additions & 0 deletions assets/certificates/fonts/PTSerif-OFL.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
Copyright (c) 2010, ParaType Ltd. (http://www.paratype.com/public),
with Reserved Font Names "PT Sans", "PT Serif" and "ParaType".

This Font Software is licensed under the SIL Open Font License, Version 1.1
This license is copied below, and is also available with a FAQ at:
http://scripts.sil.org/OFL

-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------

PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font creation
efforts of academic and linguistic communities, and to provide a free and
open framework in which fonts may be shared and improved in partnership
with others.

The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply
to any document created using the fonts or their derivatives.

DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.

"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).

"Original Version" refers to the collection of Font Software components as
distributed by the Copyright Holder(s).

"Modified Version" refers to any derivative made by adding to, deleting,
or substituting -- in part or in whole -- any of the components of the
Original Version, by changing formats or by porting the Font Software to a
new environment.

"Author" refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.

PERMISSION & CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed, modify,
redistribute, and sell modified and unmodified copies of the Font
Software, subject to the following conditions:

1) Neither the Font Software nor any of its individual components,
in Original or Modified Versions, may be sold by itself.

2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.

3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the corresponding
Copyright Holder. This restriction only applies to the primary font name as
presented to the users.

4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.

5) The Font Software, modified or unmodified, in part or in whole,
must be distributed entirely under this license, and must not be
distributed under any other license. The requirement for fonts to
remain under this license does not apply to any document created
using the Font Software.

TERMINATION
This license becomes null and void if any of the above conditions are
not met.

DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.
Binary file added assets/certificates/fonts/PTSerif-Regular.ttf
Binary file not shown.
21 changes: 21 additions & 0 deletions assets/certificates/fonts/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# Certificate fonts

The renderer bundles these Google Fonts files at commit
[`e7db6ca603fd4862010383ff17ffd6cc4ffac1c0`](https://github.com/google/fonts/tree/e7db6ca603fd4862010383ff17ffd6cc4ffac1c0):

| Local file | Upstream file | SHA-256 |
| --- | --- | --- |
| PTSerif-Regular.ttf | ofl/ptserif/PT_Serif-Web-Regular.ttf | a4951fade06ff8f09b7673aa81ffb65a8cd409e24d3289a6dc670bc4dda2557a |
| PTSerif-Bold.ttf | ofl/ptserif/PT_Serif-Web-Bold.ttf | 038ba7336bd7ea14f12ad155bed51a4345cac5153275d521dec3ba04021c526e |
| Lobster-Regular.ttf | ofl/lobster/Lobster-Regular.ttf | d6568e697fd50cedc0be04d8aae4127fe95add607e7bff954ca88604be80c205 |

PT Serif: ParaType. See [license and attribution](PTSerif-OFL.txt).
Lobster: The Lobster Project Authors. See [license and attribution](Lobster-OFL.txt).
The upstream font names and outlines are unchanged. Mont continues to use the
existing application assets in `assets/users/user_CV/`.

Frontend WOFF2 files are lossless container conversions of these TTF sources.
The backend uses the exact TTF files for both Pillow measurements and embedded PDF
faces. The renderer never downloads fonts during PDF generation. Lobster has one
400-weight face; it is used without synthetic bold. PT Serif uses 400/700 and Mont
uses the existing 400/600 faces.
12 changes: 12 additions & 0 deletions docs/modules/program-certificates.md
Original file line number Diff line number Diff line change
Expand Up @@ -86,3 +86,15 @@ PDF не изменяются, миграция БД не требуется. П
включая подгонку текста. Фон вписывается целиком без обрезки; вертикальные
изображения сохраняют разрешение до 2480 × 3508. Ранее сформированные PDF
не пересоздаются. Миграция базы не требуется.

## Шрифты элементов

`layout.<element>.font_family`: `mont`, `pt-serif` или `lobster`. Выбор хранится
отдельно для каждого элемента и входит в снимок выдачи. Старые шаблоны без поля
используют Mont. Старый клиент, опустивший поле, сохраняет предыдущий выбор
конкретного элемента; неизвестные семейства и произвольные URL отклоняются.
Pillow и PDF используют одни и те же локальные TTF, выбранный шрифт встраивается
в PDF. PT Serif использует 400/700, Mont 400/600, Lobster единственный 400 без
синтетического полужирного начертания. Шрифт изображения подписи не применяется.
Миграция и обновление ранее выданных PDF не требуются. Источники и лицензии:
`assets/certificates/fonts/README.md`.
91 changes: 64 additions & 27 deletions partner_programs/services/certificates.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,11 @@
from projects.models import Collaborator

logger = logging.getLogger(__name__)
CERTIFICATE_FONTS = {
"mont": ("Mont", "Mont-Regular.ttf", "Mont-SemiBold.ttf", 600),
"pt-serif": ("Certificate PT Serif", "PTSerif-Regular.ttf", "PTSerif-Bold.ttf", 700),
"lobster": ("Certificate Lobster", "Lobster-Regular.ttf", "Lobster-Regular.ttf", 400),
}
ELEMENTS = (
"title",
"subtitle",
Expand Down Expand Up @@ -67,7 +72,9 @@ def default_draft():
"subject": "Ваш сертификат за участие в программе {program}",
"message": "Здравствуйте, {name}!\nСпасибо за участие в программе «{program}».\nВаш сертификат готов.",
"layout": {
key: dict(zip(("x", "y", "width", "height", "font_size"), pos))
key: dict(
zip(("x", "y", "width", "height", "font_size"), pos), font_family="mont"
)
for key, pos in zip(ELEMENTS, positions)
},
}
Expand All @@ -87,6 +94,10 @@ def normalized_draft(draft):
**draft,
"orientation": draft.get("orientation", "landscape"),
"hidden_elements": [key for key in ELEMENTS if key in hidden_elements(draft)],
"layout": {
key: {**box, "font_family": box.get("font_family", "mont")}
for key, box in draft["layout"].items()
},
}


Expand Down Expand Up @@ -232,6 +243,9 @@ class Element(serializers.Serializer):
width = serializers.FloatField(min_value=2, max_value=100)
height = serializers.FloatField(min_value=1, max_value=100)
font_size = serializers.FloatField(min_value=8, max_value=72)
font_family = serializers.ChoiceField(
choices=list(CERTIFICATE_FONTS), required=False
)

class Draft(serializers.Serializer):
orientation = serializers.ChoiceField(
Expand Down Expand Up @@ -275,11 +289,18 @@ class Draft(serializers.Serializer):
raise ValidationError({"hidden_elements": "Элементы не должны повторяться."})
if set(data["layout"]) != set(ELEMENTS):
raise ValidationError("Состав элементов шаблона изменен. Обновите страницу.")
for element in data["layout"].values():
for key, element in data["layout"].items():
import math

if not all(math.isfinite(value) for value in element.values()):
if not all(
math.isfinite(element[field])
for field in ("x", "y", "width", "height", "font_size")
):
raise ValidationError("Размеры и положение должны быть конечными числами.")
element.setdefault(
"font_family",
(previous or {}).get("layout", {}).get(key, {}).get("font_family", "mont"),
)
if (
element["x"] + element["width"] > 100.01
or element["y"] + element["height"] > 100.01
Expand All @@ -301,21 +322,29 @@ class Draft(serializers.Serializer):
return normalized_draft(dict(data))


@lru_cache(maxsize=4)
def certificate_font(bold):
filename = "Mont-SemiBold.ttf" if bold else "Mont-Regular.ttf"
return ImageFont.truetype(
str(Path(settings.BASE_DIR) / "assets/users/user_CV" / filename), 1000
)
def certificate_font_key(box):
key = box.get("font_family", "mont")
return key if key in CERTIFICATE_FONTS else "mont"


def certificate_font_path(key, bold):
filename = CERTIFICATE_FONTS[key][2 if bold else 1]
directory = "assets/users/user_CV" if key == "mont" else "assets/certificates/fonts"
return Path(settings.BASE_DIR) / directory / filename


@lru_cache(maxsize=6)
def certificate_font(bold, family="mont"):
return ImageFont.truetype(str(certificate_font_path(family, bold)), 1000)


def page_dimensions(orientation="landscape"):
return (210, 297) if orientation == "portrait" else (297, 210)


def fit_certificate_text(value, box, bold=False, orientation="landscape"):
"""Подгоняем реальные строки Mont по обеим сторонам бокса, без обрезки ФИО."""
font = certificate_font(bold)
"""Подгоняем реальные строки выбранного шрифта без обрезки ФИО."""
font = certificate_font(bold, certificate_font_key(box))
page_width, page_height = (
(793.7, 1122) if orientation == "portrait" else (1122, 793.7)
)
Expand Down Expand Up @@ -361,21 +390,17 @@ def render_pdf(snapshot, assets, name, program_name, number, issued_at):
from weasyprint import HTML
from weasyprint.text.fonts import FontConfiguration

fonts = Path(settings.BASE_DIR) / "assets/users/user_CV"
orientation = snapshot.get("orientation", "landscape")
page_width, page_height = page_dimensions(orientation)

def fetch(url):
if url == "certificate-font:regular":
return {
"string": (fonts / "Mont-Regular.ttf").read_bytes(),
"mime_type": "font/ttf",
}
if url == "certificate-font:bold":
return {
"string": (fonts / "Mont-SemiBold.ttf").read_bytes(),
"mime_type": "font/ttf",
}
for key in CERTIFICATE_FONTS:
for bold, weight in ((False, "regular"), (True, "bold")):
if url == f"certificate-font:{key}:{weight}":
return {
"string": certificate_font_path(key, bold).read_bytes(),
"mime_type": "font/ttf",
}
if url.startswith("data:image/png;base64,"):
return {
"string": base64.b64decode(url.split(",", 1)[1], validate=True),
Expand Down Expand Up @@ -411,23 +436,35 @@ def src(asset):
)
else:
value = values[key]
family = certificate_font_key(box)
family_name, _, _, bold_weight = CERTIFICATE_FONTS[family]
weight = bold_weight if key in ("name", "title") else 400
size, lines = fit_certificate_text(
value, box, key in ("name", "title"), orientation
)
content = "<br>".join(escape(line) for line in lines)
elements.append(
f'<div class="element {key}" style="{style}font-size:{size}px"><span>{content}</span></div>'
f'<div class="element {key}" style="{style}font-size:{size}px;'
f'font-family:{family_name};font-weight:{weight}"><span>{content}</span></div>'
)
html = (
"""<html><head><meta charset="utf-8"><style>
@font-face{font-family:Mont;src:url('certificate-font:regular')}
@font-face{font-family:Mont;src:url('certificate-font:bold');font-weight:600}
'<html><head><meta charset="utf-8"><style>'
+ "".join(
f"@font-face{{font-family:'{name}';src:url('certificate-font:{key}:regular');font-weight:400}}"
+ (
f"@font-face{{font-family:'{name}';src:url('certificate-font:{key}:bold');font-weight:{bold_weight}}}"
if bold_weight != 400
else ""
)
for key, (name, _, _, bold_weight) in CERTIFICATE_FONTS.items()
)
+ """
@page{size:PAGE_WIDTHmm PAGE_HEIGHTmm;margin:0}*{box-sizing:border-box}body{margin:0;font-family:Mont;color:#353535}
.sheet{position:relative;width:PAGE_WIDTHmm;height:PAGE_HEIGHTmm;overflow:hidden;background:white}
.background{position:absolute;width:100%;height:100%;object-fit:contain}
.element{position:absolute;text-align:center;line-height:1.3;overflow:hidden;padding:1px}
.element span{position:absolute;left:1px;right:1px;top:50%;transform:translateY(-50%);white-space:nowrap}
.name,.title{font-weight:600}.signature{object-fit:contain}
.signature{object-fit:contain}
</style></head><body><div class="sheet">""".replace(
"PAGE_WIDTH", str(page_width)
).replace(
Expand Down
Loading
Loading