Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support for localized names #8

Open
yisibl opened this issue Aug 24, 2022 · 1 comment
Open

Support for localized names #8

yisibl opened this issue Aug 24, 2022 · 1 comment

Comments

@yisibl
Copy link

yisibl commented Aug 24, 2022

Many CJK fonts have localized names, do we support modifying them now?

e.g.

{
en: "Source Han Sans SC"
}, {
 zh: "思源黑体"
}
@fmnijk
Copy link

fmnijk commented Aug 23, 2024

Here is a modified script that works.
Usage:python fontname.py "Source Han Sans SC" -sc 思源黑体 -tc 思源黑體 -hc 思源黑體 -mo 思源黑體 -sg 思源黑体 a.ttf

#!/usr/bin/env python3

# ==========================================================================
# fontname.py
# Copyright 2019 Christopher Simpkins
# MIT License
#
# Dependencies:
#   1) Python 3.6+ interpreter
#   2) fonttools Python library (https://github.com/fonttools/fonttools)
#         - install with `pip3 install fonttools`
#
# Usage:
#   python fontname.py "English Name" [-sc "简体名"] [-tc "繁體名"] [-hk "香港名"] [-hc "香港名"] [-mo "澳門名"] [-sg "新加坡名"] [FONT PATH 1] <FONT PATH ...>
#
# Notes:
#   Use quotes around font names that include spaces
# ===========================================================================

import os
import sys
import argparse

from fontTools import ttLib
from fontTools.ttLib.tables._n_a_m_e import NameRecord

def update_name_record(tt, en_name, sc_name=None, tc_name=None, hk_name=None, mo_name=None, sg_name=None):
    name = tt['name']
    
    # 刪除現有的名稱記錄
    name.names = [record for record in name.names if record.nameID not in (1, 3, 4, 6)]

    # 添加英文名稱
    for platform_id, encoding_id, language_id in [(1, 0, 0), (3, 1, 1033)]:
        name.setName(en_name, 1, platform_id, encoding_id, language_id)
        name.setName(en_name, 4, platform_id, encoding_id, language_id)
        name.setName(en_name.replace(" ", "") + "-Regular", 6, platform_id, encoding_id, language_id)

    # 添加唯一標識符
    name.setName(en_name, 3, 1, 0, 0)
    name.setName(en_name, 3, 3, 1, 1033)

    # 定義中文變體及其對應的 langID
    chinese_variants = [
        (sc_name, 2052, "Simplified Chinese"),
        (tc_name, 1028, "Traditional Chinese"),
        (hk_name, 3076, "Traditional Chinese (Hong Kong)"),
        (mo_name, 5124, "Traditional Chinese (Macau)"),
        (sg_name, 4100, "Simplified Chinese (Singapore)")
    ]

    # 添加各種中文名稱
    for ch_name, lang_id, lang_name in chinese_variants:
        if ch_name:
            for nameID in (1, 4):
                record = NameRecord()
                record.nameID = nameID
                record.platformID = 3
                record.platEncID = 1
                record.langID = lang_id
                record.string = ch_name
                name.names.append(record)

def main():
    parser = argparse.ArgumentParser(description="Update font name in TTF files.")
    parser.add_argument("en_name", help="English font name")
    parser.add_argument("-sc", "--sc_name", help="Simplified Chinese font name")
    parser.add_argument("-tc", "--tc_name", help="Traditional Chinese font name")
    parser.add_argument("-hk", "--hk_name", help="Traditional Chinese font name (Hong Kong)")
    parser.add_argument("-hc", "--hc_name", help="Alternative Traditional Chinese font name (Hong Kong)")
    parser.add_argument("-mo", "--mo_name", help="Traditional Chinese font name (Macau)")
    parser.add_argument("-sg", "--sg_name", help="Simplified Chinese font name (Singapore)")
    parser.add_argument("font_paths", nargs="+", help="Paths to font files")

    args = parser.parse_args()

    # 如果提供了 -hc,使用它作為 Hong Kong 名稱
    hk_name = args.hc_name if args.hc_name else args.hk_name

    for font_path in args.font_paths:
        if not file_exists(font_path):
            sys.stderr.write(
                f"[fontname.py] ERROR: the path '{font_path}' does not appear to be a valid file path.{os.linesep}"
            )
            sys.exit(1)

        tt = ttLib.TTFont(font_path)

        update_name_record(tt, args.en_name, args.sc_name, args.tc_name, hk_name, args.mo_name, args.sg_name)

        if "CFF " in tt:
            try:
                cff = tt["CFF "]
                cff.cff[0].FamilyName = args.en_name
                cff.cff[0].FullName = args.en_name
                cff.cff.fontNames = [args.en_name.replace(" ", "") + "-Regular"]
            except Exception as e:
                sys.stderr.write(f"[fontname.py] ERROR: unable to write new names to CFF table: {e}")

        try:
            tt.save(font_path)
            print(f"[OK] Updated '{font_path}' with the name '{args.en_name}'", end="")
            chinese_names = [
                ("Simplified Chinese", args.sc_name),
                ("Traditional Chinese", args.tc_name),
                ("Traditional Chinese (Hong Kong)", hk_name),
                ("Traditional Chinese (Macau)", args.mo_name),
                ("Simplified Chinese (Singapore)", args.sg_name)
            ]
            for lang, name in chinese_names:
                if name:
                    print(f", {lang} name '{name}'", end="")
            print()
        except Exception as e:
            sys.stderr.write(
                f"[fontname.py] ERROR: unable to write new name to OpenType name table for '{font_path}'. {os.linesep}"
            )
            sys.stderr.write(f"{e}{os.linesep}")
            sys.exit(1)

def file_exists(filepath):
    """Tests for existence of a file on the string filepath"""
    return os.path.exists(filepath) and os.path.isfile(filepath)

if __name__ == "__main__":
    main()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants