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
28 changes: 25 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,13 @@ python -m pip install -r requirements.txt

## Web configurator

Emoji in paragraph text, section headings, the table of contents, and document
titles render as inline color images using bundled Twemoji artwork. No emoji font
or network connection is required. Artwork credits and licensing are in
Emoji retain their original Unicode characters in the PDF text stream while
rendering as author-selected fixed-color artwork. Each color emoji has an inline
Type 3 text glyph with a ToUnicode mapping for the exact original sequence
(including skin tones, variation selectors, and joined emoji). Copying or
extracting the surrounding paragraph can therefore recover its Unicode emoji.
Twemoji is bundled by default; other styles require a PNG ZIP pack. Viewer
support for complex Unicode copy/paste varies. Twemoji credits are in
[the emoji asset notes](assets/twemoji/README.md).

Run the web app:
Expand Down Expand Up @@ -363,3 +367,21 @@ Enable **Customize positions on the first page** in Letterhead to arrange the ex
The editor uses the current page margins and reserves room above the body for visible fields. A positioned addressee appears once. Disabling the editor restores the fixed letterhead layout, while configuration export preserves your custom arrangement for later reuse. This integrates the editor from:

https://github.com/PDF-magic/compiler/pull/37


### Author-selected emoji appearance

Choose --emoji-style from twemoji, fluent, noto, openmoji, blobmoji, emojitwo,
or mutant-standard. Twemoji is the built-in default. For other styles, supply
--emoji-pack /path/to/artwork.zip, upload the ZIP in the web form, or install
the pack at assets/emoji-styles/STYLE/72x72.zip. Individual PNG files are
named by lowercase Unicode codepoints, joined with hyphens for sequences,
such as 1f600.png, 1f44d-1f3fd.png or
1f468-200d-1f469-200d-1f467-200d-1f466.png. Nested ZIP folders are allowed.

Missing supported emoji fail compilation rather than changing the style.
The author must source artwork and comply with the selected project's license.
Mutant Standard uses a noncommercial license and is not bundled. These images
fix the visual appearance; accompanying Type 3 ToUnicode glyphs preserve the
original emoji as inline selectable text. PDF/A output still needs independent
conformance validation.
34 changes: 33 additions & 1 deletion app.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
LetterSettings,
)
from first_page_layout import FirstPagePdfRenderer, parse_letterhead_layout
from emoji_renderer import EMOJI_STYLES, emoji_preview, validate_emoji_style
from pdf_compiler import ADMONITION_DEFAULT_COLORS, ADMONITION_TYPES, LINK_COLOR
from pdfa4_export import render_pdf as render_with_format
from legal_style_validator import validate_legal_style
Expand Down Expand Up @@ -162,6 +163,7 @@ def index():
else getattr(TypographySettings.for_style(style), name))
for name in PROFESSIONAL_TYPOGRAPHY
} for style in RENDER_STYLES},
emoji_styles=EMOJI_STYLES,
date_formats=DATE_FORMATS,
image_treatments=IMAGE_TREATMENTS,
page_number_styles=PAGE_NUMBER_STYLES,
Expand All @@ -177,11 +179,28 @@ def index():
' <script src="/static/letterhead-presets.js"></script>\n'
' <script src="/static/plain-link-options.js"></script>\n'
' <script src="/static/render-styles.js"></script>\n'
' <script src="/static/configuration.js"></script>\n</body>',
' <script src="/static/configuration.js"></script>\n'
' <script src="/static/emoji-styles.js"></script>\n</body>',
1,
)


@app.post("/emoji-preview")
def preview_emoji_style():
selected = request.form.get("emoji_style", "twemoji")
uploaded = request.files.get("emoji_pack")
try:
with TemporaryDirectory(prefix="pdf-emoji-preview-") as temp:
pack = None
if selected != "twemoji" and uploaded and uploaded.filename:
pack = Path(temp) / "style.zip"
uploaded.save(pack)
content = emoji_preview(selected, pack)
return send_file(BytesIO(content), mimetype="image/png")
except ValueError as exc:
return jsonify({"error": str(exc)}), 400


@app.post("/validate")
def validate_markdown():
markdown, error, source_relative = submitted_markdown()
Expand Down Expand Up @@ -376,6 +395,17 @@ def metadata_value(name: str) -> str | None:
except ValueError as exc:
return jsonify({"error": str(exc)}), 400

emoji_style = request.form.get("emoji_style", "twemoji")
uploaded_emoji = request.files.get("emoji_pack")
emoji_pack = None
if emoji_style != "twemoji" and uploaded_emoji and uploaded_emoji.filename:
emoji_pack = root / "emoji-style.zip"
uploaded_emoji.save(emoji_pack)
try:
validate_emoji_style(emoji_style, emoji_pack)
except ValueError as exc:
return jsonify({"error": str(exc)}), 400

output = root / "output.pdf"
try:
renderer = FirstPagePdfRenderer(
Expand All @@ -394,6 +424,8 @@ def metadata_value(name: str) -> str | None:
keywords=metadata_value("keywords"),
smart_quotes=truthy("smart_quotes"),
quote_inline_number_footnotes=truthy("quote_inline_number_footnotes"),
emoji_style=emoji_style,
emoji_pack=emoji_pack,
underline_links=truthy("underline_links"),
hide_url_scheme=truthy("hide_url_scheme"),
link_color=link_color,
Expand Down
3 changes: 2 additions & 1 deletion configured_renderer.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@
)

from pdf_compiler import PdfRenderer, RefParagraph, TrackingDoc, advance_code_fence, alpha, compiler_creator, roman
from emoji_renderer import EmojiParagraph as Paragraph
from emoji_renderer import EmojiParagraph as Paragraph, render_with_emoji_style
from document_assets import resolve_document_image


Expand Down Expand Up @@ -996,6 +996,7 @@ def document(self, path: Path) -> SectionTrackingDoc:
author=self.author,
)

@render_with_emoji_style
def build(self) -> tuple[int, int, int]:
"""Render twice so a visible TOC can use the final section page locations."""
self.output.parent.mkdir(parents=True, exist_ok=True)
Expand Down
33 changes: 33 additions & 0 deletions docs/emoji-text-plan.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
# Author-selected color emoji with Unicode text

The author chooses a fixed PNG artwork style, while the PDF retains the
original Unicode emoji in the paragraph's searchable and copyable text stream.
The selected art draws in full color; a companion blank Type 3 glyph has a
ToUnicode CMap that maps one character code to the original Unicode sequence.
The glyph sits in the same ReportLab paragraph text run at the image position,
not in a separate end-of-page text layer. This also preserves presentation
selectors, skin-tone modifiers, flags, and zero-width joiners in the mapping.

Supported styles:
- Twemoji (bundled and default)
- Fluent Emoji
- Noto Emoji
- OpenMoji
- Blobmoji
- Emojitwo
- Mutant Standard

Alternative artwork is not bundled because of size, availability and licensing.
Supply a codepoint-named PNG ZIP through the web form or CLI, or install it at
assets/emoji-styles/STYLE/72x72.zip. The author must obtain the selected art
and comply with its license (Mutant Standard is noncommercial).

Both PDF rendering passes use a request-local style. The completed PDF is
postprocessed atomically to install Type 3 font objects and /ToUnicode mappings.
Other author-supplied images are unaffected. Missing recognized emoji in an
alternate pack fail instead of switching to a different style.

Limitations: Unicode emoji newer than both emoji catalogs may be unrecognized.
Uploaded packs are not stored in exported configuration files. Extraction and
copy/paste vary among PDF readers; PyMuPDF round-trip checks cover the original
sequences. PDF/A-4 and PDF/UA compliance still require independent validation.
190 changes: 163 additions & 27 deletions emoji_renderer.py
Original file line number Diff line number Diff line change
@@ -1,51 +1,152 @@
"""Render bundled Twemoji artwork inline without system fonts or network access."""
"""Render author-selected, fixed emoji artwork; never use viewer-native emoji fonts."""

from functools import lru_cache
from contextlib import contextmanager
from contextvars import ContextVar
from functools import lru_cache, wraps
from hashlib import sha256
from html import escape
from pathlib import Path
import re
from tempfile import TemporaryDirectory
from threading import Lock
from zipfile import ZipFile
from zipfile import BadZipFile, ZipFile

from reportlab.platypus import Paragraph
from emoji_unicode import embed_unicode_emoji, emoji_from_image, emit_unicode_text


ASSETS = Path(__file__).parent / "assets" / "twemoji" / "72x72.zip"
STYLE_PACK_ROOT = Path(__file__).parent / "assets" / "emoji-styles"
EMOJI_STYLES = {
"twemoji": "Twemoji (bundled)",
"fluent": "Fluent Emoji",
"noto": "Noto Emoji",
"openmoji": "OpenMoji",
"blobmoji": "Blobmoji",
"emojitwo": "Emojitwo",
"mutant-standard": "Mutant Standard",
}
_active_style = ContextVar("pdf_compiler_emoji_style", default=("twemoji", str(ASSETS)))
_asset_lock = Lock()


@lru_cache(maxsize=1)
def _emoji_pattern():
with ZipFile(ASSETS) as bundle:
sequences = {
"".join(chr(int(part, 16)) for part in name[:-4].split("-")).replace("\ufe0f", ""): name
for name in bundle.namelist()
}
# Longest first keeps flags, skin tones, and joined families as one image.
patterns = []
for sequence in sorted(sequences, key=lambda value: (-len(value), value)):
patterns.append("".join(re.escape(char) + "\ufe0f?" for char in sequence))
return re.compile("|".join(patterns)), sequences
_PNG = b"\x89PNG\r\n\x1a\n"
_NAME = re.compile(r"(?:emoji_u)?([0-9a-f]{2,6}(?:-[0-9a-f]{2,6})*)\.png\Z")


def _archive(style, pack=None):
if style not in EMOJI_STYLES:
raise ValueError(f"Unknown emoji style: {style}")
if style == "twemoji":
if pack is not None:
raise ValueError("Twemoji uses bundled artwork; omit the external pack.")
path = ASSETS
else:
path = Path(pack) if pack is not None else STYLE_PACK_ROOT / style / "72x72.zip"
if not path.is_file():
raise ValueError(f"{EMOJI_STYLES[style]} is unavailable: supply its PNG ZIP pack.")
return str(path)


def _pack_index(archive):
try:
with ZipFile(archive) as bundle:
if len(bundle.infolist()) > 10000:
raise ValueError("Emoji ZIP contains too many entries.")
entries = {}
total = 0
for info in bundle.infolist():
name = Path(info.filename).name.lower()
matched = _NAME.fullmatch(name)
if not matched:
continue
total += info.file_size
if info.file_size > 1024 * 1024 or total > 128 * 1024 * 1024:
raise ValueError("Emoji ZIP exceeds image size limits.")
key = "".join(chr(int(part, 16)) for part in matched.group(1).split("-")
if int(part, 16) != 0xfe0f)
if key in entries:
raise ValueError(f"Duplicate emoji sequence: {name}")
entries[key] = info.filename
if not entries:
raise ValueError("Emoji ZIP must contain codepoint-named PNG files.")
return entries
except (BadZipFile, OSError) as exc:
raise ValueError("Emoji artwork must be a valid PNG ZIP file.") from exc


def validate_emoji_style(style, pack=None):
return _pack_index(_archive(style, pack))


@contextmanager
def emoji_style_scope(style="twemoji", pack=None):
archive = _archive(style, pack)
_pack_index(archive)
token = _active_style.set((style, archive))
try:
yield
finally:
_active_style.reset(token)


def render_with_emoji_style(method):
@wraps(method)
def wrapped(self, *args, **kwargs):
with emoji_style_scope(self.emoji_style, self.emoji_pack):
result = method(self, *args, **kwargs)
embed_unicode_emoji(self.output)
return result
return wrapped


@lru_cache(maxsize=32)
def _emoji_pattern(archive):
selected = _pack_index(archive)
reference = selected if archive == str(ASSETS) else _pack_index(str(ASSETS))
sequences = selected.keys() | reference.keys()
parts = [
"".join(re.escape(char) + "\ufe0f?" for char in sequence)
for sequence in sorted(sequences, key=lambda value: (-len(value), value))
]
return re.compile("|".join(parts)), selected


@lru_cache(maxsize=1)
def _asset_directory():
return TemporaryDirectory(prefix="pdf-compiler-emoji-")


@lru_cache(maxsize=None)
def _image_path(filename):
@lru_cache(maxsize=1024)
def _image_path(archive, filename, original):
with _asset_lock:
path = Path(_asset_directory().name) / filename
prefix = sha256(archive.encode()).hexdigest()[:16]
directory = Path(_asset_directory().name) / prefix
directory.mkdir(exist_ok=True)
codepoints = "-".join(f"{ord(char):x}" for char in original)
path = directory / f"{codepoints}__{Path(filename).name}"
if not path.exists():
with ZipFile(ASSETS) as bundle:
path.write_bytes(bundle.read(filename))
with ZipFile(archive) as bundle:
data = bundle.read(filename)
if not data.startswith(_PNG):
raise ValueError(f"Invalid PNG emoji artwork: {filename}")
path.write_bytes(data)
return escape(str(path), quote=True)


def emoji_preview(style, pack=None):
archive = _archive(style, pack)
entries = _pack_index(archive)
sample = next((entries.get(item) for item in ("😀", "🌐", "👍🏽", "❤️")
if entries.get(item)), None)
if sample is None:
raise ValueError("This emoji pack lacks a common preview glyph.")
with ZipFile(archive) as bundle:
data = bundle.read(sample)
if not data.startswith(_PNG):
raise ValueError("Emoji preview must be a PNG.")
return data


def _dash_markup(text):
# Standard PDF Times lacks these Unicode hyphens and the figure dash.
text = text.replace("\u2010", "-").replace("\u2012", "\u2013")
return re.sub(
r"\S*\u2011\S*",
Expand All @@ -55,16 +156,23 @@ def _dash_markup(text):


def emoji_markup(text, font_size):
pattern, sequences = _emoji_pattern()
style, archive = _active_style.get()
pattern, selected = _emoji_pattern(archive)

def replace(match):
filename = sequences[match.group().replace("\ufe0f", "")]
normalized = match.group().replace("\ufe0f", "")
filename = selected.get(normalized)
if filename is None:
raise ValueError(
f"{EMOJI_STYLES[style]} does not include emoji {match.group()!r}. "
"Choose a compatible artwork pack."
)
return (
f'<img src="{_image_path(filename)}" width="{font_size}" '
f'<img src="{_image_path(archive, filename, match.group())}" width="{font_size}" '
f'height="{font_size}" valign="middle"/>'
)

# Never modify link destinations, anchors, or other markup attributes.
# Do not change markup attributes, link destinations, or anchors.
return "".join(
part if index % 2 else pattern.sub(replace, _dash_markup(part))
for index, part in enumerate(re.split(r"(<[^>]+>)", text))
Expand All @@ -76,3 +184,31 @@ def __init__(self, text, style=None, bulletText=None, frags=None, **kwargs):
if text and frags is None:
text = emoji_markup(text, style.fontSize if style is not None else 10)
super().__init__(text, style, bulletText=bulletText, frags=frags, **kwargs)

def beginText(self, *args, **kwargs):
tx = super().beginText(*args, **kwargs)
self._emoji_tx = tx
return tx

def drawPara(self, *args, **kwargs):
# ReportLab draws inline images separately from its paragraph text.
# Insert the exact Unicode sequence into that same text run at the
# image's position, while retaining the full-color PNG for display.
canvas = self.canv
original_draw_image = canvas.drawImage

def draw_image(image, x, y, *image_args, **image_kwargs):
result = original_draw_image(image, x, y, *image_args, **image_kwargs)
sequence = emoji_from_image(image, Path(_asset_directory().name))
if sequence is not None:
emit_unicode_text(
canvas, self._emoji_tx, sequence,
self.style.fontSize, self.style.fontName,
)
return result

canvas.drawImage = draw_image
try:
return super().drawPara(*args, **kwargs)
finally:
canvas.drawImage = original_draw_image
Loading
Loading