1. OTF是什么?

OTF(OpenType Font) 是由 Adobe 和 Microsoft 共同开发的字体格式,
.ttf(TrueType Font)的功能得到了扩展,同时包含高级排版功能。

  • ✅ 多种字体功能(连字、替代字形等)
  • ✅ 支持 Unicode
  • .ttf 的通用性更强(尤其在专业设计工具中更受欢迎)

在 Ubuntu 中,特别是作为 系统或 PDF 渲染字体 的 OTF 被广泛使用。


2. 检查 Ubuntu 中安装的 OTF 字体

可以通过终端使用以下命令进行检查:

fc-list | grep "\.otf"

也可以用特定字体名称进行过滤:

fc-list | grep "Nimbus Sans" | grep "\.otf"

3. 当想在网页上使用系统字体时

在网页上无法直接使用系统安装的字体。
因为访问网站的 客户端计算机可能没有该字体

→ 因此必须在网页服务器上提供字体,最有效的格式是 .woff2


4. OTF → WOFF2 转换是关键!

OTF to WOFF2 font conversion illustration

📦 安装转换工具

sudo apt install woff2

🔄 转换命令

woff2_compress YourFont.otf

→ 结果:YourFont.woff2

自动转换脚本

#!/bin/bash
export LC_ALL=C
# [1] 目标字体名称
read -p "请输入要转换为 woff2 的字体:" FONT_NAME

# [2] 设置结果保存路径
DEST_DIR="$HOME/fonts/$(echo $FONT_NAME | tr ' ' '_' | tr '[:upper:]' '[:lower:]')/woff2"

# [3] 检查转换工具
if ! command -v woff2_compress &> /dev/null; then
    echo "❌ 找不到 'woff2_compress' 命令。请安装后使用:"
    echo "    sudo apt install woff2"
    exit 1
fi

# [4] 创建结果文件夹
mkdir -p "$DEST_DIR"

# [5] 从系统字体列表中提取包含 .otf 的且 FONT_NAME 的路径
echo "🔍 正在搜索名称为 '$FONT_NAME' 的 .otf 字体..."
font_paths=$(fc-list | grep "$FONT_NAME" | grep "\\.otf" | cut -d: -f1 | sort | uniq)

if [ -z "$font_paths" ]; then
    echo "❌ 找不到与 '$FONT_NAME' 对应的 .otf 字体。"
    exit 1
fi

# [6] 执行转换循环
for font_file in $font_paths; do
    base_name=$(basename "$font_file" .otf)
    output_file="$DEST_DIR/${base_name}.woff2"

    if [ -f "$output_file" ]; then
        echo "⚠️  已存在: $output_file → 跳过"
        continue
    fi

    echo "🔄 正在转换: $base_name.otf → $base_name.woff2"

    if ! cp "$font_file" "/tmp/${base_name}.otf"; then
        echo "❌ 复制失败: $font_file → 跳过"
        continue
    fi

    woff2_compress "/tmp/${base_name}.otf"
    mv "/tmp/${base_name}.woff2" "$output_file"
    rm "/tmp/${base_name}.otf"
    echo "✅ 已保存: $output_file"
done

echo "🎉 所有转换完成!保存位置: $DEST_DIR"

需要的人可以使用我撰写的上面脚本。运行得非常好。


5. 如何在网站上使用转换后的 woff2 文件

将其放入网页项目的 static/fonts/ 目录,并在 CSS 中声明:

@font-face {
  font-family: '您的自定义字体';
  src: url('/static/fonts/YourFont.woff2') format('woff2');
  font-weight: normal;
  font-style: normal;
}

现在可以在 HTML 中像这样使用:

<body style="font-family: '您的自定义字体', sans-serif;">
  您好!这是自定义字体。
</body>

6. 结论

项目 要点
.otf 字体 在 Ubuntu 系统中广泛安装
在网页中使用 因客户端PC上没有,所以需要转换为 .woff2
优化方法 使用 woff2_compress 转换后在静态中提供
结果 快速字体加载,可反映专用字体设计

对于希望将 Ubuntu 系统与 Web 服务更紧密连接的开发者来说,
otf → woff2 转换是一个必备的技能。 💪