From aedd9d52a70a90dcdded011f12d8e11848ef552a Mon Sep 17 00:00:00 2001 From: John Wooten Date: Wed, 9 Sep 2026 16:29:45 -0400 Subject: [PATCH 1/5] =?UTF-8?q?=F0=9F=93=9D=20Scaffold=20inline=20emoji=20?= =?UTF-8?q?text=20and=20set=20selection?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Codex --- docs/emoji-text-plan.md | 141 ++++++++++++++++++++++++++++++++++++++++ examples/emoji-text.md | 34 ++++++++++ 2 files changed, 175 insertions(+) create mode 100644 docs/emoji-text-plan.md create mode 100644 examples/emoji-text.md diff --git a/docs/emoji-text-plan.md b/docs/emoji-text-plan.md new file mode 100644 index 0000000..dc8abb6 --- /dev/null +++ b/docs/emoji-text-plan.md @@ -0,0 +1,141 @@ +# Inline emoji text implementation + +Status: scaffold only. The renderer still uses bundled Twemoji images. + +## Requested behavior + +Preserve emoji as inline Unicode text by default instead of replacing it with +images. The user wants the reader's device to render the characters using its +own emoji appearance. Selectable text using a fixed embedded font is a possible +fallback, but has not been accepted as equivalent to that request. + +## Establish the PDF constraint first + +PDF text requires a font and character mapping. Passing raw emoji through the +current Times font produces missing glyphs; removing image substitution alone +does not implement this feature. ReportLab supports embedded TrueType fonts, +but embedding a font fixes its appearance rather than adopting the reader's +native emoji style. See the [ReportLab font documentation](https://docs.reportlab.com/reportlab/userguide/ch3_fonts/). + +1. Prototype Unicode PDF text with a nonembedded emoji font reference and an + explicit Unicode mapping outside the production renderer. Verify the actual + result in macOS Preview and a PDF.js viewer, including extraction and copying. + Do not assume either viewer supplies browser-style emoji fallback or supports + the same sequences. +2. Record whether native appearance is feasible and portable. If it is not, + explain the limitation before treating an embedded font as the solution. + An HTML output could supply native browser emoji rendering, but adding that + output is a separate product decision. +3. If implementing an embedded-font alternative, select a redistributable font + with suitable glyph coverage and shaping support. Document its license and + whether output is monochrome or color. Do not bundle Apple's system fonts. + +## Implementation map + +### Requested emoji selector + +Add a selector with all seven options below and small visual previews showing +how each set renders emoji. This is a requested feature specification only; +do not implement the selector as part of this scaffold. + +| Option | Visual style | +| --- | --- | +| Fluent Emoji | Rich, polished, dimensional style | +| Noto Emoji | Rounded Google/Android style | +| OpenMoji | Bold outlines and color | +| Twemoji | Familiar flat style | +| Blobmoji | Classic Google blob style | +| Emojitwo | Older EmojiOne cartoon style | +| Mutant Standard | Distinctive alternative designs | + +These descriptions summarize the user's supplied comparison, not verified +current coverage, maintenance, or license claims. Before implementation, verify +each project's current release, asset and font licenses, attribution requirements, +and available output formats from its primary sources. Sets may provide artwork +rather than fonts; do not label image-based PDF output as selectable emoji text. +The selector request does not resolve the native-versus-embedded-font constraint. + +Selector behavior: + +- Show previews from the actual selected release of each set, rather than using + the browser's native emoji characters to stand in for those designs. Prefer + several emoji from the current document and use a sample when it has none. +- Keep all seven options visible. Mark an option unavailable and disable its + selection if it cannot render every emoji sequence used in the document. + Explain which sequences are unsupported beside the option. +- Determine coverage from the actual assets or font/shaping backend that will + generate the PDF. A set's Unicode version or its name alone is insufficient. +- Check full sequences, including variation selectors, joined emoji, flags, + skin tones, and keycaps. Individual component coverage does not establish + support for a combined sequence. An unsupported sequence must not silently + split into separate symbols or fall back to another set. +- Recompute availability when the source or any rendered text field changes, + including titles, headings, addressees, and headers. Inspect visible text, not + URLs or markup attributes; respect uploaded-file precedence over pasted text. +- If the selected set becomes incompatible, show the missing sequences and block + compilation until a compatible choice is made or the content is corrected. + Do not silently switch sets or omit characters. If none support the complete + document, explain that no set is currently available for that content. +- Preserve the selection per render request and validate coverage on the server + as well as in the UI. Unknown or failed coverage checks must not appear as + confirmed support. +- Make previews and disabled reasons accessible with text labels and keyboard + navigation. Clearly describe whether each backend produces text or images. + +### Renderer integration + +- `emoji_renderer.py`: separate the current image substitution from the proposed + text backend. Keep `_dash_markup` behavior and leave markup attributes, + destinations, and anchors untouched. Preserve variation selectors, skin tones, + regional indicators, keycaps, and zero-width joiners in text sequences. +- `EmojiParagraph`: apply the selected backend consistently when constructing + paragraphs; preserve the existing `frags` path used during paragraph splitting. + Do not use mutable process-wide settings for individual render requests. +- `pdf_compiler.py`: propagate any rendering option through the base renderer, + paragraph construction, list items, and CLI arguments. +- `configured_renderer.py`, `typography_renderer.py`, and `first_page_layout.py`: + cover all directly constructed paragraphs, headings, TOC entries, visible + titles, addressees, and running headers. Keep ordinary body typography intact. +- `app.py` and `templates/index.html`: implement the seven-set selector and its + coverage checks. Make text the default only when it renders correctly. Any retained + image mode must be explicit, not a silent fallback that contradicts the request. +- `README.md`: replace the existing claim that emoji always render as images + once behavior changes; describe the actual viewer and font limitations. + +Do not silently drop unsupported emoji, replace them with images in text mode, +or claim that an embedded font produces reader-native appearance. + +## Validation to run during implementation + +Use `examples/emoji-text.md` as the shared visual and text-extraction fixture. +The scaffold does not change production behavior or replace the current tests. + +1. Extend `tests/test_emoji_renderer.py` to assert original Unicode sequences + survive the text path and do not create image fragments. Retain coverage of + links, dash normalization, wrapping, and any explicitly supported image mode. +2. Generate PDFs through both the CLI and web renderer. Check emoji-only input + introduces no image XObjects, has a usable Unicode mapping, and extracts the + original sequences. Text appearing in paragraph fragments is insufficient. +3. Verify selection and copying from real PDF viewers, including headings and + TOC entries. Compare extracted characters by code point, including invisible + sequence characters. +4. Inspect visual output at normal and high zoom in Preview and PDF.js. Verify + no missing glyphs, clipping, unintended spacing, or broken joined sequences. + Test wrapping, multi-page documents, and the light/dark viewer presentation. +5. Run the existing emoji, typography, heading/TOC, and web-render tests using the + repository's available Python environment. Report separately what was tested + structurally, what was seen in viewers, and what remains viewer-dependent. +6. Verify the selector shows all seven sets with real previews. Exercise complete + coverage, missing joined sequences, no compatible sets, upload precedence, + header-only emoji, and edits that invalidate the selected set. Confirm server + validation rejects an incompatible set even when UI checks are bypassed. + +## Completion criteria + +- Default emoji are PDF text, selectable and copyable as the original Unicode. +- No emoji images are introduced in text mode. +- The example renders correctly across the tested viewers and all applicable + document surfaces. +- Reader-native appearance is either demonstrated or explicitly identified as + unsupported; fixed embedded-font appearance is not presented as native. +- Font licensing, deployment requirements, and supported behavior are documented. diff --git a/examples/emoji-text.md b/examples/emoji-text.md new file mode 100644 index 0000000..40e79da --- /dev/null +++ b/examples/emoji-text.md @@ -0,0 +1,34 @@ +# Emoji text rendering fixture 🌐 + +[[TOC]] + +## Individual characters πŸ€” ⏰ 🌐 + +πŸ€” Before the sentence. An inline clock ⏰ stays in the text. A final globe 🌐. + +## Emoji sequences + +Skin tone: πŸ‘πŸ½. Flag: πŸ‡ΊπŸ‡Έ. Family: πŸ‘¨β€πŸ‘©β€πŸ‘§β€πŸ‘¦. Heart: ❀️. +Keycap: 1️⃣. Rainbow flag: πŸ³οΈβ€πŸŒˆ. Text presentation: β™₯︎. Emoji presentation: β™₯️. + +## Formatting and links + +**Bold emoji πŸ€”** and *italic emoji 🌐* remain selectable characters. + +[Emoji link ⏰](https://example.com/emoji) + +- List item with a globe 🌐. +- Nested sequences: + - Family πŸ‘¨β€πŸ‘©β€πŸ‘§β€πŸ‘¦ and skin tone πŸ‘πŸ½. + +## Wrapping and punctuation + +Repeat this paragraph when checking multi-page layout: Emoji πŸ€” should stay +inline with surrounding words, and joined sequences πŸ‘¨β€πŸ‘©β€πŸ‘§β€πŸ‘¦ should remain intact +when text wraps. Preserve punctuation around (🌐), [⏰], and β€œβ€οΈβ€. + +Keep existing dash handling: on‐chain, on‑chain, 1β€’2, en–dash, and emβ€”dash. + +*** + +The horizontal rule above should remain independent of emoji rendering. From 133dca83ca4c3ed6782b0e050b43acfb12f8bd01 Mon Sep 17 00:00:00 2001 From: John Wooten <60260750+JFWooten4@users.noreply.github.com> Date: Fri, 13 Nov 2026 03:06:55 -0500 Subject: [PATCH 2/5] =?UTF-8?q?=F0=9F=96=8C=EF=B8=8F=20Add=20author-select?= =?UTF-8?q?ed=20emoji=20artwork=20rendering?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Support seven named fixed emoji styles with bundled Twemoji as default. Scope the chosen asset pack per PDF render, expose CLI style and pack arguments, and reject missing artwork rather than silently substituting reader-native emoji. Co-authored-by: ChatGPT 6 --- configured_renderer.py | 3 +- emoji_renderer.py | 158 ++++++++++++++++++++++++++++++++++------- pdf_compiler.py | 14 +++- 3 files changed, 146 insertions(+), 29 deletions(-) diff --git a/configured_renderer.py b/configured_renderer.py index d2c2805..5e293a5 100644 --- a/configured_renderer.py +++ b/configured_renderer.py @@ -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 @@ -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) diff --git a/emoji_renderer.py b/emoji_renderer.py index 9241d4c..4dfef7c 100644 --- a/emoji_renderer.py +++ b/emoji_renderer.py @@ -1,32 +1,110 @@ -"""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 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): + return method(self, *args, **kwargs) + 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) @@ -34,18 +112,37 @@ 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): 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) + path = directory / 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*", @@ -55,16 +152,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'' ) - # 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)) diff --git a/pdf_compiler.py b/pdf_compiler.py index 4cf2845..ee7359b 100644 --- a/pdf_compiler.py +++ b/pdf_compiler.py @@ -36,7 +36,7 @@ ) -from emoji_renderer import EmojiParagraph as Paragraph +from emoji_renderer import EmojiParagraph as Paragraph, EMOJI_STYLES, render_with_emoji_style, validate_emoji_style from page_breaks import PAGE_BREAK_SENTINEL, normalize_page_breaks from document_assets import resolve_document_image @@ -445,6 +445,8 @@ def __init__( start_heading: str | None = None, smart_quotes: bool = False, quote_inline_number_footnotes: bool = False, + emoji_style: str = "twemoji", + emoji_pack: Path | None = None, underline_links: bool = True, link_color: str = LINK_COLOR, ): @@ -457,6 +459,9 @@ def __init__( self.author = author or "" self.smart_quotes = smart_quotes self.quote_inline_number_footnotes = quote_inline_number_footnotes + validate_emoji_style(emoji_style, emoji_pack) + self.emoji_style = emoji_style + self.emoji_pack = emoji_pack self.underline_links = underline_links if not re.fullmatch(r"#[0-9a-fA-F]{6}", link_color): raise ValueError("Link color must be a six-digit hex color, such as #2E732E.") @@ -1460,6 +1465,7 @@ def document(self, path: Path) -> TrackingDoc: author=self.author, ) + @render_with_emoji_style def build(self) -> tuple[int, int, int]: self.output.parent.mkdir(parents=True, exist_ok=True) tmp = self.output.with_suffix(".tmp.pdf") @@ -1526,6 +1532,10 @@ def main() -> int: action="store_true", help="Convert straight quotes to typographic quotes in rendered text", ) + parser.add_argument("--emoji-style", choices=tuple(EMOJI_STYLES), default="twemoji", + help="Author-selected fixed emoji artwork style") + parser.add_argument("--emoji-pack", type=Path, + help="PNG ZIP asset pack for a non-Twemoji style") parser.add_argument( "--quote-inline-number-footnotes", action="store_true", @@ -1557,6 +1567,8 @@ def main() -> int: start_heading=args.start_heading, smart_quotes=args.smart_quotes, quote_inline_number_footnotes=args.quote_inline_number_footnotes, + emoji_style=args.emoji_style, + emoji_pack=args.emoji_pack, **presentation, ) from pdfa4_export import render_pdf From 0c0f37e44da1617cae4e6c618f16939ce9e9d434 Mon Sep 17 00:00:00 2001 From: John Wooten <60260750+JFWooten4@users.noreply.github.com> Date: Fri, 13 Nov 2026 03:08:19 -0500 Subject: [PATCH 3/5] =?UTF-8?q?=F0=9F=96=8C=EF=B8=8F=20Expose=20author=20e?= =?UTF-8?q?moji=20artwork=20selection=20in=20the=20web=20configurator?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add the seven-style selector, optional artwork ZIP upload, true PNG previews, web validation and coverage tests. Document default Twemoji behavior, optional artwork sources, and licensing and PDF/A limitations. Co-authored-by: ChatGPT 6 --- README.md | 25 ++++- app.py | 34 ++++++- docs/emoji-text-plan.md | 172 +++++++---------------------------- static/emoji-styles.js | 37 ++++++++ templates/index.html | 16 ++++ tests/test_emoji_renderer.py | 31 +++++++ 6 files changed, 169 insertions(+), 146 deletions(-) create mode 100644 static/emoji-styles.js diff --git a/README.md b/README.md index abfb6a9..00272a8 100644 --- a/README.md +++ b/README.md @@ -10,10 +10,10 @@ 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 -[the emoji asset notes](assets/twemoji/README.md). +Emoji render as fixed inline color images chosen by the document author, not +viewer-native emoji fonts. Twemoji is bundled by default; other named styles +require a supplied PNG ZIP pack. Image emoji are not individually selectable +Unicode text. Twemoji credits are in [the emoji asset notes](assets/twemoji/README.md). Run the web app: @@ -363,3 +363,20 @@ 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 but do not turn emoji into selectable Unicode PDF +text. PDF/A output still needs independent conformance validation. diff --git a/app.py b/app.py index 9efeb15..289ddc5 100644 --- a/app.py +++ b/app.py @@ -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 @@ -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, @@ -177,11 +179,28 @@ def index(): ' \n' ' \n' ' \n' - ' \n', + ' \n' + ' \n', 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() @@ -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( @@ -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, diff --git a/docs/emoji-text-plan.md b/docs/emoji-text-plan.md index dc8abb6..78ef88c 100644 --- a/docs/emoji-text-plan.md +++ b/docs/emoji-text-plan.md @@ -1,141 +1,31 @@ -# Inline emoji text implementation - -Status: scaffold only. The renderer still uses bundled Twemoji images. - -## Requested behavior - -Preserve emoji as inline Unicode text by default instead of replacing it with -images. The user wants the reader's device to render the characters using its -own emoji appearance. Selectable text using a fixed embedded font is a possible -fallback, but has not been accepted as equivalent to that request. - -## Establish the PDF constraint first - -PDF text requires a font and character mapping. Passing raw emoji through the -current Times font produces missing glyphs; removing image substitution alone -does not implement this feature. ReportLab supports embedded TrueType fonts, -but embedding a font fixes its appearance rather than adopting the reader's -native emoji style. See the [ReportLab font documentation](https://docs.reportlab.com/reportlab/userguide/ch3_fonts/). - -1. Prototype Unicode PDF text with a nonembedded emoji font reference and an - explicit Unicode mapping outside the production renderer. Verify the actual - result in macOS Preview and a PDF.js viewer, including extraction and copying. - Do not assume either viewer supplies browser-style emoji fallback or supports - the same sequences. -2. Record whether native appearance is feasible and portable. If it is not, - explain the limitation before treating an embedded font as the solution. - An HTML output could supply native browser emoji rendering, but adding that - output is a separate product decision. -3. If implementing an embedded-font alternative, select a redistributable font - with suitable glyph coverage and shaping support. Document its license and - whether output is monochrome or color. Do not bundle Apple's system fonts. - -## Implementation map - -### Requested emoji selector - -Add a selector with all seven options below and small visual previews showing -how each set renders emoji. This is a requested feature specification only; -do not implement the selector as part of this scaffold. - -| Option | Visual style | -| --- | --- | -| Fluent Emoji | Rich, polished, dimensional style | -| Noto Emoji | Rounded Google/Android style | -| OpenMoji | Bold outlines and color | -| Twemoji | Familiar flat style | -| Blobmoji | Classic Google blob style | -| Emojitwo | Older EmojiOne cartoon style | -| Mutant Standard | Distinctive alternative designs | - -These descriptions summarize the user's supplied comparison, not verified -current coverage, maintenance, or license claims. Before implementation, verify -each project's current release, asset and font licenses, attribution requirements, -and available output formats from its primary sources. Sets may provide artwork -rather than fonts; do not label image-based PDF output as selectable emoji text. -The selector request does not resolve the native-versus-embedded-font constraint. - -Selector behavior: - -- Show previews from the actual selected release of each set, rather than using - the browser's native emoji characters to stand in for those designs. Prefer - several emoji from the current document and use a sample when it has none. -- Keep all seven options visible. Mark an option unavailable and disable its - selection if it cannot render every emoji sequence used in the document. - Explain which sequences are unsupported beside the option. -- Determine coverage from the actual assets or font/shaping backend that will - generate the PDF. A set's Unicode version or its name alone is insufficient. -- Check full sequences, including variation selectors, joined emoji, flags, - skin tones, and keycaps. Individual component coverage does not establish - support for a combined sequence. An unsupported sequence must not silently - split into separate symbols or fall back to another set. -- Recompute availability when the source or any rendered text field changes, - including titles, headings, addressees, and headers. Inspect visible text, not - URLs or markup attributes; respect uploaded-file precedence over pasted text. -- If the selected set becomes incompatible, show the missing sequences and block - compilation until a compatible choice is made or the content is corrected. - Do not silently switch sets or omit characters. If none support the complete - document, explain that no set is currently available for that content. -- Preserve the selection per render request and validate coverage on the server - as well as in the UI. Unknown or failed coverage checks must not appear as - confirmed support. -- Make previews and disabled reasons accessible with text labels and keyboard - navigation. Clearly describe whether each backend produces text or images. - -### Renderer integration - -- `emoji_renderer.py`: separate the current image substitution from the proposed - text backend. Keep `_dash_markup` behavior and leave markup attributes, - destinations, and anchors untouched. Preserve variation selectors, skin tones, - regional indicators, keycaps, and zero-width joiners in text sequences. -- `EmojiParagraph`: apply the selected backend consistently when constructing - paragraphs; preserve the existing `frags` path used during paragraph splitting. - Do not use mutable process-wide settings for individual render requests. -- `pdf_compiler.py`: propagate any rendering option through the base renderer, - paragraph construction, list items, and CLI arguments. -- `configured_renderer.py`, `typography_renderer.py`, and `first_page_layout.py`: - cover all directly constructed paragraphs, headings, TOC entries, visible - titles, addressees, and running headers. Keep ordinary body typography intact. -- `app.py` and `templates/index.html`: implement the seven-set selector and its - coverage checks. Make text the default only when it renders correctly. Any retained - image mode must be explicit, not a silent fallback that contradicts the request. -- `README.md`: replace the existing claim that emoji always render as images - once behavior changes; describe the actual viewer and font limitations. - -Do not silently drop unsupported emoji, replace them with images in text mode, -or claim that an embedded font produces reader-native appearance. - -## Validation to run during implementation - -Use `examples/emoji-text.md` as the shared visual and text-extraction fixture. -The scaffold does not change production behavior or replace the current tests. - -1. Extend `tests/test_emoji_renderer.py` to assert original Unicode sequences - survive the text path and do not create image fragments. Retain coverage of - links, dash normalization, wrapping, and any explicitly supported image mode. -2. Generate PDFs through both the CLI and web renderer. Check emoji-only input - introduces no image XObjects, has a usable Unicode mapping, and extracts the - original sequences. Text appearing in paragraph fragments is insufficient. -3. Verify selection and copying from real PDF viewers, including headings and - TOC entries. Compare extracted characters by code point, including invisible - sequence characters. -4. Inspect visual output at normal and high zoom in Preview and PDF.js. Verify - no missing glyphs, clipping, unintended spacing, or broken joined sequences. - Test wrapping, multi-page documents, and the light/dark viewer presentation. -5. Run the existing emoji, typography, heading/TOC, and web-render tests using the - repository's available Python environment. Report separately what was tested - structurally, what was seen in viewers, and what remains viewer-dependent. -6. Verify the selector shows all seven sets with real previews. Exercise complete - coverage, missing joined sequences, no compatible sets, upload precedence, - header-only emoji, and edits that invalidate the selected set. Confirm server - validation rejects an incompatible set even when UI checks are bypassed. - -## Completion criteria - -- Default emoji are PDF text, selectable and copyable as the original Unicode. -- No emoji images are introduced in text mode. -- The example renders correctly across the tested viewers and all applicable - document surfaces. -- Reader-native appearance is either demonstrated or explicitly identified as - unsupported; fixed embedded-font appearance is not presented as native. -- Font licensing, deployment requirements, and supported behavior are documented. +# Author-selected emoji artwork + +Status: author selection implemented; former reader-native Unicode emoji plan +superseded. The document author chooses the emoji's artwork. Emoji are fixed +PNG images, not viewer-native fonts or selectable Unicode text. + +Supported style names: +- Twemoji (bundled and default) +- Fluent Emoji +- Noto Emoji +- OpenMoji +- Blobmoji +- Emojitwo +- Mutant Standard + +Alternative artwork is not bundled because of size, availability and differing +licenses. Supply a style's 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 actual selected art and comply with the artist's license (including +Mutant Standard's noncommercial restriction). + +Both passes of a PDF export use a request-local selected style. Missing glyphs +found by the bundled emoji catalog or the selected pack fail rather than +falling back to another style. The web UI previews a real PNG from the supplied +pack. ZIP entries need hexadecimal Unicode names like 1f600.png or +1f468-200d-1f469-200d-1f467-200d-1f466.png. + +Limitations: Unicode emoji newer than both catalogs might be unrecognized. +Uploaded style packs are not included in exported web configuration files. +PDF/A still requires independent validation; selectable Unicode emoji would +require a separate text-layer implementation. diff --git a/static/emoji-styles.js b/static/emoji-styles.js new file mode 100644 index 0000000..6146ce8 --- /dev/null +++ b/static/emoji-styles.js @@ -0,0 +1,37 @@ +(() => { + const style = document.getElementById("emoji-style"); + const pack = document.getElementById("emoji-pack"); + const preview = document.getElementById("emoji-preview"); + const status = document.getElementById("emoji-preview-status"); + if (!style || !pack || !preview || !status) return; + let revision = 0, previous = null; + async function refresh() { + const current = ++revision; + const body = new FormData(); + body.set("emoji_style", style.value); + if (style.value !== "twemoji" && pack.files.length) body.set("emoji_pack", pack.files[0]); + status.textContent = "Checking selected emoji artwork…"; + try { + const response = await fetch("/emoji-preview", { method: "POST", body }); + if (current !== revision) return; + if (!response.ok) { + const result = await response.json(); + throw new Error(result.error || "Preview unavailable."); + } + const blob = await response.blob(); + if (previous) URL.revokeObjectURL(previous); + previous = URL.createObjectURL(blob); + preview.src = previous; + preview.style.display = "block"; + status.textContent = "Preview from the actual selected artwork."; + } catch (error) { + if (current !== revision) return; + preview.removeAttribute("src"); + preview.style.display = "none"; + status.textContent = error.message; + } + } + style.addEventListener("change", refresh); + pack.addEventListener("change", refresh); + refresh(); +})(); diff --git a/templates/index.html b/templates/index.html index ccabbc2..0780b3e 100644 --- a/templates/index.html +++ b/templates/index.html @@ -305,6 +305,22 @@

PDF Compiler

Choose a folder with one Markdown file and referenced raster images, including subfolders. + + +
+ Actual selected emoji artwork preview + +
diff --git a/tests/test_emoji_renderer.py b/tests/test_emoji_renderer.py index 7480df2..c360b72 100644 --- a/tests/test_emoji_renderer.py +++ b/tests/test_emoji_renderer.py @@ -63,6 +63,37 @@ def test_builds_pdf_with_emoji_in_headings_toc_and_wrapped_body(self): self.assertGreater(pages, 2) self.assertIn(b"/Subtype /Image", output.read_bytes()) + def test_selected_pack_does_not_fall_back(self): + from zipfile import ZipFile + from emoji_renderer import emoji_style_scope, validate_emoji_style + with TemporaryDirectory() as temp: + path = Path(temp) / "noto.zip" + bundled = Path(__file__).resolve().parents[1] / "assets" / "twemoji" / "72x72.zip" + with ZipFile(bundled) as source, ZipFile(path, "w") as target: + name = next(name for name in source.namelist() if name.endswith("1f600.png")) + target.writestr("1f600.png", source.read(name)) + validate_emoji_style("noto", path) + with emoji_style_scope("noto", path): + self.assertEqual(emoji_markup("πŸ˜€", 14).count(" Date: Fri, 13 Nov 2026 03:31:02 -0500 Subject: [PATCH 4/5] =?UTF-8?q?=F0=9F=90=9E=20Preserve=20Unicode=20emoji?= =?UTF-8?q?=20when=20copying=20color=20PDF=20text?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Render author-selected color emoji artwork alongside inline Type 3 text glyphs with exact ToUnicode mappings. Preserve emoji sequences in extracted paragraphs and cover round-trip extraction in regression tests. Co-authored-by: ChatGPT 6 --- README.md | 17 +++-- docs/emoji-text-plan.md | 40 +++++------ emoji_renderer.py | 40 +++++++++-- emoji_unicode.py | 127 +++++++++++++++++++++++++++++++++++ tests/test_emoji_renderer.py | 27 ++++++++ 5 files changed, 222 insertions(+), 29 deletions(-) create mode 100644 emoji_unicode.py diff --git a/README.md b/README.md index 00272a8..6badf7f 100644 --- a/README.md +++ b/README.md @@ -10,10 +10,14 @@ python -m pip install -r requirements.txt ## Web configurator -Emoji render as fixed inline color images chosen by the document author, not -viewer-native emoji fonts. Twemoji is bundled by default; other named styles -require a supplied PNG ZIP pack. Image emoji are not individually selectable -Unicode text. Twemoji credits are in [the emoji asset notes](assets/twemoji/README.md). +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: @@ -378,5 +382,6 @@ such as 1f600.png, 1f44d-1f3fd.png or 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 but do not turn emoji into selectable Unicode PDF -text. PDF/A output still needs independent conformance validation. +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. diff --git a/docs/emoji-text-plan.md b/docs/emoji-text-plan.md index 78ef88c..017925c 100644 --- a/docs/emoji-text-plan.md +++ b/docs/emoji-text-plan.md @@ -1,10 +1,14 @@ -# Author-selected emoji artwork +# Author-selected color emoji with Unicode text -Status: author selection implemented; former reader-native Unicode emoji plan -superseded. The document author chooses the emoji's artwork. Emoji are fixed -PNG images, not viewer-native fonts or selectable 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 style names: +Supported styles: - Twemoji (bundled and default) - Fluent Emoji - Noto Emoji @@ -13,19 +17,17 @@ Supported style names: - Emojitwo - Mutant Standard -Alternative artwork is not bundled because of size, availability and differing -licenses. Supply a style's 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 actual selected art and comply with the artist's license (including -Mutant Standard's noncommercial restriction). +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 passes of a PDF export use a request-local selected style. Missing glyphs -found by the bundled emoji catalog or the selected pack fail rather than -falling back to another style. The web UI previews a real PNG from the supplied -pack. ZIP entries need hexadecimal Unicode names like 1f600.png or -1f468-200d-1f469-200d-1f467-200d-1f466.png. +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 catalogs might be unrecognized. -Uploaded style packs are not included in exported web configuration files. -PDF/A still requires independent validation; selectable Unicode emoji would -require a separate text-layer implementation. +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. diff --git a/emoji_renderer.py b/emoji_renderer.py index 4dfef7c..e00d2e8 100644 --- a/emoji_renderer.py +++ b/emoji_renderer.py @@ -12,6 +12,7 @@ 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" @@ -91,7 +92,9 @@ def render_with_emoji_style(method): @wraps(method) def wrapped(self, *args, **kwargs): with emoji_style_scope(self.emoji_style, self.emoji_pack): - return method(self, *args, **kwargs) + result = method(self, *args, **kwargs) + embed_unicode_emoji(self.output) + return result return wrapped @@ -113,12 +116,13 @@ def _asset_directory(): @lru_cache(maxsize=1024) -def _image_path(archive, filename): +def _image_path(archive, filename, original): with _asset_lock: prefix = sha256(archive.encode()).hexdigest()[:16] directory = Path(_asset_directory().name) / prefix directory.mkdir(exist_ok=True) - path = directory / Path(filename).name + codepoints = "-".join(f"{ord(char):x}" for char in original) + path = directory / f"{codepoints}__{Path(filename).name}" if not path.exists(): with ZipFile(archive) as bundle: data = bundle.read(filename) @@ -164,7 +168,7 @@ def replace(match): "Choose a compatible artwork pack." ) return ( - f'' ) @@ -180,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 diff --git a/emoji_unicode.py b/emoji_unicode.py new file mode 100644 index 0000000..256b8f2 --- /dev/null +++ b/emoji_unicode.py @@ -0,0 +1,127 @@ +"""Embed copyable Unicode emoji alongside fixed-color ReportLab emoji artwork. + +ReportLab draws inline PNGs outside the text object. EmojiParagraph emits one +zero-paint Type 3 text glyph at each image position. This module installs a +ToUnicode CMap for the exact source sequence; ordinary text and the chosen +color PNG are left untouched. The glyph is inside the paragraph text run, so +text extraction retains the surrounding reading order. +""" + +import os +from pathlib import Path +import re +from tempfile import NamedTemporaryFile + +import fitz + + +_EMOJI_FONT = re.compile(rb"/EMJ_([0-9a-f]+(?:_[0-9a-f]+)*)\s+[0-9.]+\s+Tf") +_FONT_REF = re.compile(r"/Font\s+(\d+)\s+0\s+R") + + +def emoji_font_name(sequence: str) -> str: + """A PDF Name that losslessly identifies one Unicode emoji sequence.""" + return "EMJ_" + "_".join(f"{ord(char):x}" for char in sequence) + + +def emoji_from_image(image, root: Path) -> str | None: + """Recognize only artwork generated by emoji_markup, not author images.""" + file_name = getattr(image, "fileName", "") + path = Path(file_name) if isinstance(file_name, (str, Path)) else None + if path is None or root not in path.parents or "__" not in path.name: + return None + prefix = path.name.split("__", 1)[0] + if not re.fullmatch(r"[0-9a-f]+(?:-[0-9a-f]+)*", prefix): + return None + try: + return "".join(chr(int(code, 16)) for code in prefix.split("-")) + except ValueError: + return None + + +def emit_unicode_text(canvas, tx, sequence: str, font_size: float, fallback_font: str): + """Insert selectable text without changing PNG placement or text style.""" + active_font = tx._fontname or fallback_font + active_size = tx._fontsize or font_size + restore = canvas._doc.getInternalFontName(active_font) + font = emoji_font_name(sequence) + tx._code.append(f"/{font} {active_size:g} Tf <01> Tj {restore} {active_size:g} Tf") + + +def _make_font(doc, sequence: str, char_proc: int) -> int: + unicode_hex = sequence.encode("utf-16-be").hex().upper() + cmap = ( + "/CIDInit /ProcSet findresource begin\n" + "12 dict begin\n" + "begincmap\n" + "/CIDSystemInfo << /Registry (Adobe) /Ordering (UCS) /Supplement 0 >> def\n" + "/CMapName /EmojiUnicode def\n/CMapType 2 def\n" + "1 begincodespacerange\n<00> \nendcodespacerange\n" + f"1 beginbfchar\n<01> <{unicode_hex}>\nendbfchar\n" + "endcmap\nCMapName currentdict /CMap defineresource pop\nend end\n" + ).encode("ascii") + cmap_ref = doc.get_new_xref() + doc.update_object(cmap_ref, "<< >>") + doc.update_stream(cmap_ref, cmap) + font_ref = doc.get_new_xref() + doc.update_object(font_ref, ( + "<< /Type /Font /Subtype /Type3 " + "/FontBBox [0 0 1000 1000] /FontMatrix [0.001 0 0 0.001 0 0] " + f"/CharProcs << /E1 {char_proc} 0 R >> " + "/Encoding << /Type /Encoding /Differences [1 /E1] >> " + "/FirstChar 1 /LastChar 1 /Widths [1000] " + f"/Resources << >> /ToUnicode {cmap_ref} 0 R >>" + )) + return font_ref + + +def _page_font_table(doc, page) -> int: + """Locate the indirect ReportLab font dictionary on this page.""" + kind, resources = doc.xref_get_key(page.xref, "Resources") + if kind == "xref": + resource_ref = int(resources.split()[0]) + kind, font_entry = doc.xref_get_key(resource_ref, "Font") + if kind == "xref": + return int(font_entry.split()[0]) + else: + match = _FONT_REF.search(resources) + if match: + return int(match.group(1)) + raise RuntimeError("Cannot install Unicode emoji fonts in PDF page resources") + + +def embed_unicode_emoji(path: Path) -> None: + """Attach ToUnicode Type 3 mappings atomically after ReportLab renders.""" + path = Path(path) + with fitz.open(path) as doc: + used = [] + for page in doc: + names = set() + for xref in page.get_contents(): + for match in _EMOJI_FONT.finditer(doc.xref_stream(xref)): + names.add(match.group(1).decode("ascii")) + used.append(names) + if not any(used): + return + char_proc = doc.get_new_xref() + doc.update_object(char_proc, "<< >>") + doc.update_stream(char_proc, b"1000 0 d0\n") + installed = {} + for page, names in zip(doc, used): + if not names: + continue + font_table = _page_font_table(doc, page) + for codepoints in sorted(names): + sequence = "".join(chr(int(code, 16)) for code in codepoints.split("_")) + name = emoji_font_name(sequence) + if name not in installed: + installed[name] = _make_font(doc, sequence, char_proc) + doc.xref_set_key(font_table, name, f"{installed[name]} 0 R") + with NamedTemporaryFile(prefix=".emoji-unicode-", suffix=".pdf", dir=path.parent, + delete=False) as handle: + temporary = Path(handle.name) + try: + doc.save(str(temporary), garbage=3, deflate=True) + os.replace(temporary, path) + finally: + temporary.unlink(missing_ok=True) diff --git a/tests/test_emoji_renderer.py b/tests/test_emoji_renderer.py index c360b72..108c5bf 100644 --- a/tests/test_emoji_renderer.py +++ b/tests/test_emoji_renderer.py @@ -63,6 +63,33 @@ def test_builds_pdf_with_emoji_in_headings_toc_and_wrapped_body(self): self.assertGreater(pages, 2) self.assertIn(b"/Subtype /Image", output.read_bytes()) + def test_color_emoji_copy_as_original_inline_unicode(self): + import fitz + + with TemporaryDirectory() as temp: + root = Path(temp) + source = root / "emoji-copy.md" + source.write_text( + "## Greeting πŸ˜€\n\n" + "Hello πŸ˜€ world πŸ‘πŸ½ family πŸ‘¨β€πŸ‘©β€πŸ‘§β€πŸ‘¦ flag πŸ‡ΊπŸ‡Έ heart ❀️.\n\n" + "Next paragraph: πŸ¦„ then ✨.\n", + encoding="utf-8", + ) + output = root / "emoji-copy.pdf" + renderer = FirstPagePdfRenderer( + source, output, settings=LetterSettings(show_date=False), + ) + renderer.build() + with fitz.open(output) as pdf: + text = " ".join(" ".join(page.get_text(sort=True).split()) + for page in pdf) + self.assertIn( + "Hello πŸ˜€ world πŸ‘πŸ½ family πŸ‘¨β€πŸ‘©β€πŸ‘§β€πŸ‘¦ flag πŸ‡ΊπŸ‡Έ heart ❀️.", text + ) + self.assertIn("Next paragraph: πŸ¦„ then ✨.", text) + self.assertTrue(any(page.get_images() for page in pdf)) + self.assertTrue(pdf[0].search_for("πŸ˜€")) + def test_selected_pack_does_not_fall_back(self): from zipfile import ZipFile from emoji_renderer import emoji_style_scope, validate_emoji_style From 4d7929382427f18bcac1cbc1b80487e36325d8db Mon Sep 17 00:00:00 2001 From: John Wooten <60260750+JFWooten4@users.noreply.github.com> Date: Fri, 13 Nov 2026 03:33:01 -0500 Subject: [PATCH 5/5] =?UTF-8?q?=F0=9F=90=9E=20Verify=20embedded=20PDF=20im?= =?UTF-8?q?ages=20independent=20of=20object=20formatting?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Inspect actual PDF image objects rather than matching ReportLab's former dictionary spacing, which PyMuPDF changes when preserving Unicode emoji mappings. Co-authored-by: ChatGPT 6 --- tests/test_emoji_renderer.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/tests/test_emoji_renderer.py b/tests/test_emoji_renderer.py index 108c5bf..6a6ad64 100644 --- a/tests/test_emoji_renderer.py +++ b/tests/test_emoji_renderer.py @@ -61,7 +61,9 @@ def test_builds_pdf_with_emoji_in_headings_toc_and_wrapped_body(self): ) pages, _, _ = renderer.build() self.assertGreater(pages, 2) - self.assertIn(b"/Subtype /Image", output.read_bytes()) + import fitz + with fitz.open(output) as pdf: + self.assertTrue(any(page.get_images() for page in pdf)) def test_color_emoji_copy_as_original_inline_unicode(self): import fitz