Gift packages: buy a main package for someone, with a printable gift card

- /ajandek: the package, whom it is for and from whom, the recipient's
  address typed twice (or "I hand it over"), a message; paid on Stripe
  like any package, the invoice is the buyer's
- On payment the gift gets its own code (not a promo code: it cannot be
  withdrawn, and it adds the whole package); redeemed on /bevaltas
- The recipient's e-mail carries the message and the code, with the gift
  card attached as a PDF; the buyer's confirmation says it was a gift
- /ajandekaim: codes, state, the card to download, sending it by e-mail
  (again, or to another address) up to three times
- crates/gift-card draws the A4 card (example chart, questions avatar,
  QR code) as SVG and makes a PDF with krilla, fonts compiled in; the
  backend draws downloads on a blocking thread, the worker the e-mails
- Telegram notices say "(ajándék)"; unpaid gifts go after a week

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
This commit is contained in:
feco
2026-11-23 20:28:11 +00:00
co-authored by Claude Opus 5.5
parent 699ce2abbd
commit c90232f40c
46 changed files with 3647 additions and 88 deletions
+18
View File
@@ -0,0 +1,18 @@
[package]
name = "gift-card"
description = "The printable gift card (PDF) of a gifted package"
edition.workspace = true
version.workspace = true
license.workspace = true
publish.workspace = true
[dependencies]
base64.workspace = true
krilla = { version = "0.8", default-features = false, features = ["raster-images"] }
krilla-svg = "0.8"
qrcode = { version = "0.14", default-features = false }
ttf-parser = "0.25"
usvg = { version = "0.47", default-features = false, features = ["text"] }
[dev-dependencies]
resvg = { version = "0.47", default-features = false, features = ["text", "raster-images"] }
Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 42 KiB

+44
View File
@@ -0,0 +1,44 @@
//! Writes a sample card as PDF and PNG: `cargo run -p gift-card --example preview -- <dir>`.
fn main() {
let dir = std::env::args().nth(1).unwrap_or_else(|| ".".into());
let contents: Vec<String> = [
"2 részletes képletelemzés",
"1 kapcsolati elemzés",
"2 éves előrejelzés",
"1 személyhely",
"3 kérdés",
"5 kártyajóslás",
]
.map(String::from)
.to_vec();
let message = std::env::var("MESSAGE").unwrap_or_else(|_| {
"Boldog születésnapot! Remélem, legalább annyira élvezni fogod, mint én. Nézd meg a kettőnk képletét is, \
kíváncsi vagyok, mit mond rólunk. Ölel: Ági"
.into()
});
let from = std::env::var("FROM").unwrap_or_else(|_| "Ági".into());
let to = std::env::var("TO").unwrap_or_else(|_| "Bea".into());
// A sample code can use letters real codes never have (I, O, 0).
let code = std::env::var("CODE").unwrap_or_else(|_| "ABCD-EFGH-JKMN".into());
let url = format!("https://sorsfonalak.hu/bevaltas?kod={code}");
let card = gift_card::Card {
package: "Páros",
contents: &contents,
code: &code,
redeem_url: &url,
recipient_name: Some(to.as_str()),
from_name: Some(from.as_str()),
message: (!message.is_empty()).then_some(message.as_str()),
};
let started = std::time::Instant::now();
let pdf = gift_card::pdf(&card).unwrap();
println!("pdf: {} bytes in {:?}", pdf.len(), started.elapsed());
std::fs::write(format!("{dir}/card.pdf"), pdf).unwrap();
let tree = gift_card::tree(&card).unwrap();
let scale: f32 = std::env::var("SCALE").ok().and_then(|s| s.parse().ok()).unwrap_or(2.0);
let size = tree.size().to_int_size().scale_by(scale).unwrap();
let mut pixmap = resvg::tiny_skia::Pixmap::new(size.width(), size.height()).unwrap();
resvg::render(&tree, resvg::tiny_skia::Transform::from_scale(scale, scale), &mut pixmap.as_mut());
pixmap.save_png(format!("{dir}/card.png")).unwrap();
}
Binary file not shown.
Binary file not shown.
Binary file not shown.
+187
View File
@@ -0,0 +1,187 @@
Fonts are (c) Bitstream (see below). DejaVu changes are in public domain.
Glyphs imported from Arev fonts are (c) Tavmjong Bah (see below)
Bitstream Vera Fonts Copyright
------------------------------
Copyright (c) 2003 by Bitstream, Inc. All Rights Reserved. Bitstream Vera is
a trademark of Bitstream, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of the fonts accompanying this license ("Fonts") and associated
documentation files (the "Font Software"), to reproduce and distribute the
Font Software, including without limitation the rights to use, copy, merge,
publish, distribute, and/or sell copies of the Font Software, and to permit
persons to whom the Font Software is furnished to do so, subject to the
following conditions:
The above copyright and trademark notices and this permission notice shall
be included in all copies of one or more of the Font Software typefaces.
The Font Software may be modified, altered, or added to, and in particular
the designs of glyphs or characters in the Fonts may be modified and
additional glyphs or characters may be added to the Fonts, only if the fonts
are renamed to names not containing either the words "Bitstream" or the word
"Vera".
This License becomes null and void to the extent applicable to Fonts or Font
Software that has been modified and is distributed under the "Bitstream
Vera" names.
The Font Software may be sold as part of a larger software package but no
copy of one or more of the Font Software typefaces may be sold by itself.
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 BITSTREAM OR THE GNOME
FOUNDATION 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.
Except as contained in this notice, the names of Gnome, the Gnome
Foundation, and Bitstream Inc., shall not be used in advertising or
otherwise to promote the sale, use or other dealings in this Font Software
without prior written authorization from the Gnome Foundation or Bitstream
Inc., respectively. For further information, contact: fonts at gnome dot
org.
Arev Fonts Copyright
------------------------------
Copyright (c) 2006 by Tavmjong Bah. All Rights Reserved.
Permission is hereby granted, free of charge, to any person obtaining
a copy of the fonts accompanying this license ("Fonts") and
associated documentation files (the "Font Software"), to reproduce
and distribute the modifications to the Bitstream Vera Font Software,
including without limitation the rights to use, copy, merge, publish,
distribute, and/or sell copies of the Font Software, and to permit
persons to whom the Font Software is furnished to do so, subject to
the following conditions:
The above copyright and trademark notices and this permission notice
shall be included in all copies of one or more of the Font Software
typefaces.
The Font Software may be modified, altered, or added to, and in
particular the designs of glyphs or characters in the Fonts may be
modified and additional glyphs or characters may be added to the
Fonts, only if the fonts are renamed to names not containing either
the words "Tavmjong Bah" or the word "Arev".
This License becomes null and void to the extent applicable to Fonts
or Font Software that has been modified and is distributed under the
"Tavmjong Bah Arev" names.
The Font Software may be sold as part of a larger software package but
no copy of one or more of the Font Software typefaces may be sold by
itself.
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
TAVMJONG BAH 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.
Except as contained in this notice, the name of Tavmjong Bah shall not
be used in advertising or otherwise to promote the sale, use or other
dealings in this Font Software without prior written authorization
from Tavmjong Bah. For further information, contact: tavmjong @ free
. fr.
TeX Gyre DJV Math
-----------------
Fonts are (c) Bitstream (see below). DejaVu changes are in public domain.
Math extensions done by B. Jackowski, P. Strzelczyk and P. Pianowski
(on behalf of TeX users groups) are in public domain.
Letters imported from Euler Fraktur from AMSfonts are (c) American
Mathematical Society (see below).
Bitstream Vera Fonts Copyright
Copyright (c) 2003 by Bitstream, Inc. All Rights Reserved. Bitstream Vera
is a trademark of Bitstream, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of the fonts accompanying this license (“Fonts”) and associated
documentation
files (the “Font Software”), to reproduce and distribute the Font Software,
including without limitation the rights to use, copy, merge, publish,
distribute,
and/or sell copies of the Font Software, and to permit persons to whom
the Font Software is furnished to do so, subject to the following
conditions:
The above copyright and trademark notices and this permission notice
shall be
included in all copies of one or more of the Font Software typefaces.
The Font Software may be modified, altered, or added to, and in particular
the designs of glyphs or characters in the Fonts may be modified and
additional
glyphs or characters may be added to the Fonts, only if the fonts are
renamed
to names not containing either the words “Bitstream” or the word “Vera”.
This License becomes null and void to the extent applicable to Fonts or
Font Software
that has been modified and is distributed under the “Bitstream Vera”
names.
The Font Software may be sold as part of a larger software package but
no copy
of one or more of the Font Software typefaces may be sold by itself.
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 BITSTREAM OR THE GNOME
FOUNDATION
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.
Except as contained in this notice, the names of GNOME, the GNOME
Foundation,
and Bitstream Inc., shall not be used in advertising or otherwise to promote
the sale, use or other dealings in this Font Software without prior written
authorization from the GNOME Foundation or Bitstream Inc., respectively.
For further information, contact: fonts at gnome dot org.
AMSFonts (v. 2.2) copyright
The PostScript Type 1 implementation of the AMSFonts produced by and
previously distributed by Blue Sky Research and Y&Y, Inc. are now freely
available for general use. This has been accomplished through the
cooperation
of a consortium of scientific publishers with Blue Sky Research and Y&Y.
Members of this consortium include:
Elsevier Science IBM Corporation Society for Industrial and Applied
Mathematics (SIAM) Springer-Verlag American Mathematical Society (AMS)
In order to assure the authenticity of these fonts, copyright will be
held by
the American Mathematical Society. This is not meant to restrict in any way
the legitimate use of the fonts, such as (but not limited to) electronic
distribution of documents containing these fonts, inclusion of these fonts
into other public domain or commercial font collections or computer
applications, use of the outline data to create derivative fonts and/or
faces, etc. However, the AMS does require that the AMS copyright notice be
removed from any derivative versions of the fonts which have been altered in
any way. In addition, to ensure the fidelity of TeX documents using Computer
Modern fonts, Professor Donald Knuth, creator of the Computer Modern faces,
has requested that any alterations which yield different font metrics be
given a different name.
$Id$
@@ -0,0 +1,93 @@
Copyright 2015 the Cormorant Project Authors (github.com/CatharsisFonts/Cormorant)
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:
https://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.
@@ -0,0 +1,93 @@
Copyright 2020 The Inter Project Authors (https://github.com/rsms/inter)
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:
https://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.
+8
View File
@@ -0,0 +1,8 @@
Fonts of the gift card, compiled into the binary.
- Cormorant Garamond SemiBold, Inter Regular and SemiBold: static instances from
Google Fonts (the same files as the share images), SIL Open Font License
(LICENSE-OFL-*.txt).
- Cormorant Garamond Medium Italic: a static instance of the Google Fonts
variable font; its family name inside is "Cormorant Garamond Light".
- DejaVu Sans 2.37: the zodiac and planet glyphs of the wheel (LICENSE-DejaVu.txt).
+638
View File
@@ -0,0 +1,638 @@
//! The printable gift card of a gifted package: one A4 page (PDF) with whom
//! it is for, the package, the giver's message, the code to redeem (with a QR
//! code), the example chart of the home page and the avatar of the questions.
//!
//! The page is drawn as an SVG and turned into a PDF with its text embedded
//! (selectable and searchable). Fonts and pictures are compiled in: the
//! services run in empty containers. Light and printer-friendly on purpose.
use std::fmt::Write as _;
use std::sync::{Arc, OnceLock};
use base64::Engine as _;
use krilla::action::{Action, LinkAction};
use krilla::annotation::{Annotation, LinkAnnotation, Target};
use krilla::geom::{Rect, Size};
use krilla::metadata::Metadata;
use krilla::page::PageSettings;
use krilla_svg::{SurfaceExt as _, SvgSettings};
use usvg::fontdb;
/// A4 in points.
const W: f32 = 595.28;
const H: f32 = 841.89;
const SERIF: &[u8] = include_bytes!("../fonts/CormorantGaramond-SemiBold.ttf");
const SERIF_ITALIC: &[u8] = include_bytes!("../fonts/CormorantGaramond-MediumItalic.ttf");
/// The family name inside that file (an instance cut from the variable font).
const SERIF_ITALIC_FAMILY: &str = "Cormorant Garamond Light";
const SANS: &[u8] = include_bytes!("../fonts/Inter-Regular.ttf");
const SANS_BOLD: &[u8] = include_bytes!("../fonts/Inter-SemiBold.ttf");
/// The zodiac and planet glyphs of the wheel.
const SYMBOLS: &[u8] = include_bytes!("../fonts/DejaVuSans.ttf");
const WHEEL: &str = include_str!("../assets/wheel.svg");
const AVATAR: &[u8] = include_bytes!("../assets/avatar.webp");
const INK: &str = "#1b2238";
const GOLD: &str = "#a07a2c";
const MUTED: &str = "#5f6578";
const LINE: &str = "#d9c9a3";
const PAPER: &str = "#fdfaf3";
/// Where the code box starts; the message fills the space above it.
const CODE_TOP: f32 = 636.0;
const CODE_HEIGHT: f32 = 114.0;
const CODE_LEFT: f32 = 56.0;
const QR_SIZE: f32 = 86.0;
const MESSAGE_LEFT: f32 = 164.0;
const MESSAGE_RIGHT: f32 = W - 70.0;
const AVATAR_SIZE: f32 = 70.0;
/// What goes on the card (the user's text is cleaned and escaped here).
pub struct Card<'a> {
/// The package's name ("Páros").
pub package: &'a str,
/// What the package gives, item by item ("2 részletes képletelemzés").
pub contents: &'a [String],
/// The code as shown (`ABCD-EFGH-JKLM`).
pub code: &'a str,
/// The link that opens the redeem page with the code filled in.
pub redeem_url: &'a str,
/// Whom it is for ("Bea részére").
pub recipient_name: Option<&'a str>,
/// Who gives it, as the buyer typed it.
pub from_name: Option<&'a str>,
/// The buyer's message (line breaks kept).
pub message: Option<&'a str>,
}
#[derive(Debug)]
pub struct Error(String);
impl std::fmt::Display for Error {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "gift card: {}", self.0)
}
}
impl std::error::Error for Error {}
/// The card as a PDF document.
pub fn pdf(card: &Card) -> Result<Vec<u8>, Error> {
let tree = tree(card)?;
let size = Size::from_wh(W, H).expect("A4 is a size");
let mut document = krilla::Document::new();
document.set_metadata(
Metadata::new()
.title(format!("Sorsfonalak ajándékutalvány – {}", card.package))
.language("hu".into())
.creator("Sorsfonalak".into()),
);
let mut page = document.start_page_with(PageSettings::new(size));
let mut surface = page.surface();
surface.draw_svg(&tree, size, SvgSettings::default()).ok_or_else(|| Error("the page could not be drawn".into()))?;
surface.finish();
// The QR code and the address can be clicked in a PDF reader.
let (qr, link) = link_areas(card);
for rect in [qr, link] {
let action = Action::Link(LinkAction::new(card.redeem_url.to_string()));
page.add_annotation(Annotation::new_link(LinkAnnotation::new(rect, Target::Action(action)), None));
}
page.finish();
document.finish().map_err(|e| Error(format!("{e:?}")))
}
/// The page as an SVG tree (the PDF is made from it; tests render it to a picture).
pub fn tree(card: &Card) -> Result<usvg::Tree, Error> {
let options = usvg::Options { fontdb: fonts(), font_family: "Inter".into(), ..Default::default() };
usvg::Tree::from_str(&svg(card), &options).map_err(|e| Error(e.to_string()))
}
fn fonts() -> Arc<fontdb::Database> {
static FONTS: OnceLock<Arc<fontdb::Database>> = OnceLock::new();
FONTS
.get_or_init(|| {
let mut db = fontdb::Database::new();
for data in [SERIF, SERIF_ITALIC, SANS, SANS_BOLD, SYMBOLS] {
db.load_font_data(data.to_vec());
}
Arc::new(db)
})
.clone()
}
// --- measuring and wrapping text ---------------------------------------------------------
#[derive(Clone, Copy)]
enum Face {
Serif,
SerifItalic,
Sans,
SansBold,
}
impl Face {
fn data(self) -> &'static [u8] {
match self {
Face::Serif => SERIF,
Face::SerifItalic => SERIF_ITALIC,
Face::Sans => SANS,
Face::SansBold => SANS_BOLD,
}
}
}
/// The width of a line of text (without kerning: a little wider than drawn).
fn width(face: Face, text: &str, size: f32, spacing: f32) -> f32 {
let face = ttf_parser::Face::parse(face.data(), 0).expect("the fonts are compiled in");
let em = f32::from(face.units_per_em());
text.chars()
.map(|c| {
let advance =
face.glyph_index(c).and_then(|g| face.glyph_hor_advance(g)).unwrap_or(face.units_per_em() / 2);
f32::from(advance) * size / em + spacing
})
.sum()
}
/// Breaks text into lines of at most `max` points (a word longer than a line is cut).
fn wrap(text: &str, max: f32, measure: &dyn Fn(&str) -> f32) -> Vec<String> {
let mut lines = Vec::new();
for paragraph in text.split('\n') {
let mut line = String::new();
for word in paragraph.split_whitespace() {
let joined = if line.is_empty() { word.to_string() } else { format!("{line} {word}") };
if measure(&joined) <= max {
line = joined;
continue;
}
if !line.is_empty() {
lines.push(std::mem::take(&mut line));
}
// The word alone, cut where it does not fit.
for c in word.chars() {
let longer = format!("{line}{c}");
if !line.is_empty() && measure(&longer) > max {
lines.push(std::mem::replace(&mut line, c.to_string()));
} else {
line = longer;
}
}
}
lines.push(line);
}
lines
}
/// Groups items into lines joined by `sep`, an item never split.
fn wrap_items(items: &[String], sep: &str, max: f32, measure: &dyn Fn(&str) -> f32) -> Vec<String> {
let mut lines: Vec<String> = Vec::new();
for item in items {
match lines.last_mut() {
Some(line) if measure(&format!("{line}{sep}{item}")) <= max => {
line.push_str(sep);
line.push_str(item);
}
_ => lines.push(item.clone()),
}
}
lines
}
/// User text made safe for the card: control characters out, at most one
/// empty line in a row, spaces trimmed.
fn clean(text: &str) -> String {
let text: String = text.replace("\r\n", "\n").chars().filter(|&c| c == '\n' || !c.is_control()).collect();
let mut out = String::new();
let mut empty = 0;
for line in text.trim().split('\n') {
let line = line.trim();
empty = if line.is_empty() { empty + 1 } else { 0 };
if empty <= 1 {
if !out.is_empty() {
out.push('\n');
}
out.push_str(line);
}
}
out
}
fn escape(text: &str) -> String {
let mut out = String::with_capacity(text.len());
for c in text.chars() {
match c {
'&' => out.push_str("&amp;"),
'<' => out.push_str("&lt;"),
'>' => out.push_str("&gt;"),
'"' => out.push_str("&quot;"),
'\'' => out.push_str("&apos;"),
c => out.push(c),
}
}
out
}
// --- the page ----------------------------------------------------------------------------
/// The message part: lines of italic text, their size and line height, and the signature.
struct Message {
lines: Vec<String>,
size: f32,
leading: f32,
signature: Option<String>,
}
impl Message {
const SIGNATURE_GAP: f32 = 24.0;
fn of(card: &Card, room: f32) -> Message {
let from = card.from_name.map(clean).map(|f| f.replace('\n', " ")).filter(|f| !f.is_empty());
let message = card.message.map(clean).filter(|m| !m.is_empty());
let (text, signature) = match (message, from) {
(Some(m), from) => (format!("„{m}”"), from.map(|f| format!("– {f}"))),
(None, Some(f)) => (format!("Szeretettel küldi: {f}"), None),
(None, None) => (
"Fedezd fel, mit mesélnek rólad a csillagok: a születési képleted, személyre szóló elemzések, \
és válaszok a kérdéseidre."
.to_string(),
None,
),
};
let room = room - if signature.is_some() { Self::SIGNATURE_GAP } else { 0.0 };
let max = MESSAGE_RIGHT - MESSAGE_LEFT;
let sizes = [(16.5, 22.0), (15.0, 20.0), (13.5, 18.0), (12.0, 16.0)];
for (size, leading) in sizes {
let lines = wrap(&text, max, &|s| width(Face::SerifItalic, s, size, 0.0));
if lines.len() as f32 * leading <= room {
return Message { lines, size, leading, signature };
}
}
// Still too long (many line breaks): the lines that fit, the last one cut.
let (size, leading) = sizes[sizes.len() - 1];
let mut lines = wrap(&text, max, &|s| width(Face::SerifItalic, s, size, 0.0));
let keep = ((room / leading).floor() as usize).max(1);
if lines.len() > keep {
lines.truncate(keep);
if let Some(last) = lines.last_mut() {
while !last.is_empty() && width(Face::SerifItalic, &format!("{last} …"), size, 0.0) > max {
last.pop();
}
last.push_str(" …");
}
}
Message { lines, size, leading, signature }
}
fn height(&self) -> f32 {
self.lines.len() as f32 * self.leading + if self.signature.is_some() { Self::SIGNATURE_GAP } else { 0.0 }
}
}
/// "sorsfonalak.hu/bevaltas" from the redeem link.
fn short_address(url: &str) -> &str {
let rest = url.split_once("://").map_or(url, |(_, r)| r);
rest.split(['?', '#']).next().unwrap_or(rest)
}
/// Where the QR code and the address are, for the link areas of the PDF.
fn link_areas(card: &Card) -> (Rect, Rect) {
let qr = Rect::from_xywh(qr_left(), CODE_TOP + (CODE_HEIGHT - QR_SIZE) / 2.0, QR_SIZE, QR_SIZE).expect("a rect");
let text_width = width(Face::Sans, &format!("Beváltás: {}", short_address(card.redeem_url)), 10.0, 0.0);
let link = Rect::from_xywh(CODE_LEFT + 26.0, CODE_TOP + 84.0, text_width, 15.0).expect("a rect");
(qr, link)
}
fn qr_left() -> f32 {
W - CODE_LEFT - 22.0 - QR_SIZE
}
/// A four-pointed star (the logo's), centred on (x, y).
fn star(x: f32, y: f32, r: f32, fill: &str) -> String {
let i = r * 0.28;
format!(
r#"<path fill="{fill}" d="M{x} {t}L{a} {b}L{rr} {y}L{a} {c}L{x} {bt}L{d} {c}L{l} {y}L{d} {b}Z"/>"#,
t = y - r,
a = x + i,
b = y - i,
rr = x + r,
c = y + i,
bt = y + r,
d = x - i,
l = x - r,
)
}
/// The QR code of the redeem link as a path of `size` points at (x, y).
fn qr(url: &str, x: f32, y: f32, size: f32) -> String {
let Ok(code) = qrcode::QrCode::with_error_correction_level(url, qrcode::EcLevel::M) else {
return String::new();
};
let n = code.width();
let colors = code.to_colors();
let mut d = String::new();
for row in 0..n {
let mut col = 0;
while col < n {
if colors[row * n + col] == qrcode::Color::Dark {
let start = col;
while col < n && colors[row * n + col] == qrcode::Color::Dark {
col += 1;
}
let _ = write!(d, "M{start} {row}h{}v1h-{}z", col - start, col - start);
} else {
col += 1;
}
}
}
let scale = size / n as f32;
format!(r#"<path fill="{INK}" transform="translate({x} {y}) scale({scale})" d="{d}"/>"#)
}
/// The page as an SVG document (points as units).
pub fn svg(card: &Card) -> String {
let cx = W / 2.0;
let mut s = String::new();
let _ = write!(s, r#"<svg xmlns="http://www.w3.org/2000/svg" width="{W}" height="{H}" viewBox="0 0 {W} {H}">"#);
// Paper and a double frame with stars in the corners.
let _ = write!(
s,
r#"<rect width="{W}" height="{H}" fill="white"/><rect x="18" y="18" width="{}" height="{}" fill="{PAPER}" stroke="{GOLD}" stroke-width="0.9"/><rect x="24" y="24" width="{}" height="{}" fill="none" stroke="{LINE}" stroke-width="0.5"/>"#,
W - 36.0,
H - 36.0,
W - 48.0,
H - 48.0
);
for (x, y) in [(24.0, 24.0), (W - 24.0, 24.0), (24.0, H - 24.0), (W - 24.0, H - 24.0)] {
s.push_str(&star(x, y, 6.0, GOLD));
}
// The logo: the mark and "sorsfonalak", centred.
let word_size = 30.0;
let mark = 34.0;
let gap = 10.0;
let total = mark + gap + width(Face::Serif, "sorsfonalak", word_size, 0.3);
let x0 = cx - total / 2.0;
let baseline = 80.0;
let mark_top = baseline - 9.5 - mark / 2.0;
let _ = write!(
s,
r#"<g transform="translate({x0} {mark_top}) scale({k})"><g fill="none" stroke="{GOLD}" stroke-width="4.5" stroke-linecap="round"><circle cx="32" cy="32" r="23"/><path d="M10 46 C 24 45, 29 23, 44 18"/><path d="M18 33.5 L36 33.5" stroke-width="4.2"/></g><path d="M49 6 L51.8 13.2 L59 16 L51.8 18.8 L49 26 L46.2 18.8 L39 16 L46.2 13.2 Z" fill="{INK}"/></g>"#,
k = mark / 64.0
);
let _ = write!(
s,
r#"<text x="{}" y="{baseline}" font-family="Cormorant Garamond" font-weight="600" font-size="{word_size}" letter-spacing="0.3" fill="{INK}">sors<tspan fill="{GOLD}">fonalak</tspan></text>"#,
x0 + mark + gap
);
// "AJÁNDÉKUTALVÁNY" between two short lines.
let eyebrow = "AJÁNDÉKUTALVÁNY";
let spacing = 3.2;
let ew = width(Face::SansBold, eyebrow, 9.0, spacing) - spacing;
let _ = write!(
s,
r#"<text x="{}" y="108" font-family="Inter" font-weight="600" font-size="9" letter-spacing="{spacing}" fill="{GOLD}">{eyebrow}</text>"#,
cx - ew / 2.0
);
for (a, b) in [(cx - ew / 2.0 - 56.0, cx - ew / 2.0 - 14.0), (cx + ew / 2.0 + 14.0, cx + ew / 2.0 + 56.0)] {
let _ = write!(s, r#"<line x1="{a}" y1="104.8" x2="{b}" y2="104.8" stroke="{LINE}" stroke-width="0.8"/>"#);
}
// The example chart with an orbit around it and a few stars.
let wheel = 216.0;
let wheel_top = 124.0;
let wy = wheel_top + wheel / 2.0;
let orbit = wheel / 2.0 + 13.0;
let _ = write!(s, r#"<circle cx="{cx}" cy="{wy}" r="{orbit}" fill="none" stroke="{LINE}" stroke-width="0.6"/>"#);
for (deg, r) in [(90.0_f32, 2.4), (-8.0, 1.8), (218.0, 2.0)] {
let (sin, cos) = deg.to_radians().sin_cos();
let _ = write!(s, r#"<circle cx="{}" cy="{}" r="{r}" fill="{GOLD}"/>"#, cx + orbit * cos, wy - orbit * sin);
}
for (x, y, r) in
[(124.0, 164.0, 5.0), (462.0, 148.0, 6.5), (470.0, 304.0, 4.0), (134.0, 322.0, 6.0), (420.0, 350.0, 3.0)]
{
s.push_str(&star(x, y, r, LINE));
}
let inner = WHEEL.split_once("viewBox=\"0 0 680 680\">").map_or("", |(_, rest)| rest);
let inner = inner.trim_end().trim_end_matches("</svg>");
let _ = write!(
s,
r#"<svg x="{}" y="{wheel_top}" width="{wheel}" height="{wheel}" viewBox="0 0 680 680">{inner}</svg>"#,
cx - wheel / 2.0
);
// Whom it is for, the package and what it gives.
if let Some(name) = card.recipient_name.map(clean).map(|n| n.replace('\n', " ")).filter(|n| !n.is_empty()) {
let line = format!("{name} részére");
let size = (440.0 / width(Face::SerifItalic, &line, 1.0, 0.0)).min(21.0);
let _ = write!(
s,
r#"<text x="{cx}" y="{}" text-anchor="middle" font-family="{SERIF_ITALIC_FAMILY}" font-style="italic" font-weight="500" font-size="{size}" fill="{GOLD}">{}</text>"#,
wheel_top + wheel + 38.0,
escape(&line)
);
}
let title_y = wheel_top + wheel + 76.0;
let _ = write!(
s,
r#"<text x="{cx}" y="{title_y}" text-anchor="middle" font-family="Cormorant Garamond" font-weight="600" font-size="36" fill="{INK}">„{}” csomag</text>"#,
escape(card.package)
);
let contents = wrap_items(card.contents, " · ", 440.0, &|t| width(Face::Sans, t, 10.0, 0.0));
let mut y = title_y + 26.0;
for line in &contents {
let _ = write!(
s,
r#"<text x="{cx}" y="{y}" text-anchor="middle" font-family="Inter" font-size="10" fill="{MUTED}" xml:space="preserve">{}</text>"#,
escape(line)
);
y += 15.0;
}
// A divider with a small diamond.
let divider = y + 10.0;
let _ = write!(
s,
r#"<line x1="{}" y1="{divider}" x2="{}" y2="{divider}" stroke="{LINE}" stroke-width="0.7"/><line x1="{}" y1="{divider}" x2="{}" y2="{divider}" stroke="{LINE}" stroke-width="0.7"/><path d="M{cx} {} l3.5 3.5 l-3.5 3.5 l-3.5 -3.5 z" fill="{GOLD}"/>"#,
cx - 150.0,
cx - 10.0,
cx + 10.0,
cx + 150.0,
divider - 3.5
);
// The message next to the avatar, centred in the room above the code box.
let room_top = divider + 22.0;
let room_bottom = CODE_TOP - 22.0;
let message = Message::of(card, room_bottom - room_top);
let block = message.height().max(AVATAR_SIZE);
let top = room_top + ((room_bottom - room_top - block) / 2.0).max(0.0);
let avatar_y = top + (block - AVATAR_SIZE) / 2.0;
let r = AVATAR_SIZE / 2.0;
let (ax, ay) = (70.0 + r, avatar_y + r);
let avatar = base64::engine::general_purpose::STANDARD.encode(AVATAR);
let _ = write!(
s,
r#"<clipPath id="avatar"><circle cx="{ax}" cy="{ay}" r="{r}"/></clipPath><image x="70" y="{avatar_y}" width="{AVATAR_SIZE}" height="{AVATAR_SIZE}" clip-path="url(#avatar)" href="data:image/webp;base64,{avatar}"/><circle cx="{ax}" cy="{ay}" r="{}" fill="none" stroke="{GOLD}" stroke-width="1.2"/><circle cx="{ax}" cy="{ay}" r="{}" fill="none" stroke="{LINE}" stroke-width="0.5"/>"#,
r + 2.5,
r + 6.0
);
let text_top = top + (block - message.height()) / 2.0;
let mut y = text_top + message.size * 0.95;
for line in &message.lines {
let _ = write!(
s,
r#"<text x="{MESSAGE_LEFT}" y="{y}" font-family="{SERIF_ITALIC_FAMILY}" font-style="italic" font-weight="500" font-size="{}" fill="{INK}" xml:space="preserve">{}</text>"#,
message.size,
escape(line)
);
y += message.leading;
}
if let Some(signature) = &message.signature {
let _ = write!(
s,
r#"<text x="{MESSAGE_RIGHT}" y="{}" text-anchor="end" font-family="Cormorant Garamond" font-weight="600" font-size="15" fill="{GOLD}">{}</text>"#,
y - message.leading + Message::SIGNATURE_GAP,
escape(signature)
);
}
// The code, the address and the QR code in a box.
let box_width = W - 2.0 * CODE_LEFT;
let tx = CODE_LEFT + 26.0;
let _ = write!(
s,
r#"<rect x="{CODE_LEFT}" y="{CODE_TOP}" width="{box_width}" height="{CODE_HEIGHT}" rx="10" fill="white" stroke="{GOLD}" stroke-width="1"/>"#
);
let _ = write!(
s,
r#"<text x="{tx}" y="{}" font-family="Inter" font-weight="600" font-size="8.5" letter-spacing="2.5" fill="{GOLD}">AJÁNDÉKKÓD</text>"#,
CODE_TOP + 30.0
);
let _ = write!(
s,
r#"<text x="{tx}" y="{}" font-family="Inter" font-weight="600" font-size="27" letter-spacing="1.5" fill="{INK}">{}</text>"#,
CODE_TOP + 66.0,
escape(card.code)
);
let _ = write!(
s,
r#"<text x="{tx}" y="{}" font-family="Inter" font-size="10" fill="{MUTED}">Beváltás: <tspan fill="{INK}" font-weight="600">{}</tspan></text>"#,
CODE_TOP + 95.0,
escape(short_address(card.redeem_url))
);
s.push_str(&qr(card.redeem_url, qr_left(), CODE_TOP + (CODE_HEIGHT - QR_SIZE) / 2.0, QR_SIZE));
// How to redeem it.
let how = "Lépj be vagy regisztrálj a sorsfonalak.hu oldalon, és írd be a kódot a „Kód beváltása” oldalon, \
vagy olvasd be a QR-kódot a telefonoddal. A kód egyszer váltható be, és nem jár le.";
let mut y = CODE_TOP + CODE_HEIGHT + 26.0;
for line in wrap(how, 430.0, &|t| width(Face::Sans, t, 9.0, 0.0)) {
let _ = write!(
s,
r#"<text x="{cx}" y="{y}" text-anchor="middle" font-family="Inter" font-size="9" fill="{MUTED}">{}</text>"#,
escape(&line)
);
y += 13.0;
}
s.push_str("</svg>");
s
}
#[cfg(test)]
mod tests {
use super::*;
fn contents() -> Vec<String> {
[
"2 részletes képletelemzés",
"1 kapcsolati elemzés",
"2 éves előrejelzés",
"1 személyhely",
"3 kérdés",
"5 kártyajóslás",
]
.map(String::from)
.to_vec()
}
fn card<'a>(contents: &'a [String], message: Option<&'a str>, from: Option<&'a str>) -> Card<'a> {
Card {
package: "Páros",
contents,
code: "ABCD-EFGH-JKMN",
redeem_url: "https://sorsfonalak.hu/bevaltas?kod=ABCD-EFGH-JKMN",
recipient_name: Some("Bea"),
from_name: from,
message,
}
}
#[test]
fn the_fonts_are_found_by_their_names() {
let db = fonts();
let families: Vec<String> = db.faces().flat_map(|f| f.families.iter().map(|(n, _)| n.clone())).collect();
for family in ["Cormorant Garamond", "Inter", "DejaVu Sans"] {
assert!(families.iter().any(|f| f == family), "{family} not in {families:?}");
}
let italic = db.query(&fontdb::Query {
families: &[fontdb::Family::Name(SERIF_ITALIC_FAMILY)],
weight: fontdb::Weight(500),
style: fontdb::Style::Italic,
..Default::default()
});
assert!(italic.is_some_and(|id| db.face(id).is_some_and(|f| f.style == fontdb::Style::Italic)));
}
#[test]
fn a_card_is_a_pdf_with_its_text() {
let contents = contents();
let pdf = pdf(&card(&contents, Some("Boldog születésnapot! Ölelés: Ági"), Some("Ági & <Péter>"))).unwrap();
assert!(pdf.starts_with(b"%PDF-"));
assert!(pdf.len() < 400_000, "{} bytes", pdf.len());
// The redeem link is clickable.
assert!(pdf.windows(26).any(|w| w == b"sorsfonalak.hu/bevaltas?ko"));
}
#[test]
fn long_messages_get_smaller_and_still_fit() {
let contents = contents();
let short = Message::of(&card(&contents, Some("Boldog születésnapot!"), Some("Ági")), 150.0);
assert_eq!((short.lines.len(), short.size), (1, 16.5));
let long = "Nagyon sok boldog születésnapot kívánok! ".repeat(7);
let m = Message::of(&card(&contents, Some(&long), Some("Ági")), 150.0);
assert!(m.size < 16.5 && m.height() <= 150.0, "{} lines of {}", m.lines.len(), m.size);
// Line after line: what does not fit is cut, with an ellipsis.
let lines = "a\n".repeat(40);
let m = Message::of(&card(&contents, Some(&lines), None), 150.0);
assert!(m.height() <= 150.0 && m.lines.last().unwrap().ends_with('…'));
// One endless word is broken.
let word = "a".repeat(300);
let m = Message::of(&card(&contents, Some(&word), None), 150.0);
assert!(m.lines.iter().all(|l| width(Face::SerifItalic, l, m.size, 0.0) <= MESSAGE_RIGHT - MESSAGE_LEFT));
}
#[test]
fn user_text_is_escaped_and_cleaned() {
let contents = contents();
let svg = svg(&card(&contents, Some("<b>szia</b>\u{7}\n\n\n\nvége"), Some("Ági & \"Péter\"")));
assert!(svg.contains("&lt;b&gt;szia&lt;/b&gt;") && !svg.contains('\u{7}'));
assert!(svg.contains("– Ági &amp; &quot;Péter&quot;"));
assert_eq!(clean(" a\n\n\n\nb "), "a\n\nb");
usvg::Tree::from_str(&svg, &usvg::Options::default()).unwrap();
}
#[test]
fn without_a_message_the_card_still_says_something() {
let contents = contents();
assert!(svg(&card(&contents, None, Some("Ági"))).contains("Szeretettel küldi: Ági"));
assert!(svg(&card(&contents, None, None)).contains(">Bea részére</text>"));
let nameless = Card { recipient_name: None, ..card(&contents, None, None) };
assert!(!svg(&nameless).contains("részére"));
assert!(svg(&card(&contents, None, None)).contains("Fedezd fel"));
assert_eq!(short_address("https://sorsfonalak.hu/bevaltas?kod=X"), "sorsfonalak.hu/bevaltas");
}
}