zhangguanzhang's Blog

ttf转woff工具谷歌woff2的静态编译

字数统计: 442阅读时长: 2 min
2022/03/17

ttf 转 woff 的工具太少了,离线安装的方案基本没有,所以找了个工具静态编译

由来

ttf 转 woff 的工具太少了,nodejs 的 ttf2woff 脚本无法离线安装,所以找了个工具静态编译

过程

推荐ubuntu 上编译,缺的依赖自行安装,可能是

1
2
3
4
5
6
7
8
sed -ri 's/(ports|deb|security|archive).(debian.org|ubuntu.com)/mirrors.aliyun.com/g' /etc/apt/sources.list
apt-get update
export DEBIAN_FRONTEND=noninteractive
apt-get install -y \
build-essential \
gcc \
make \
pkg-config

下载源码

1
2
git clone --recursive https://github.com/google/woff2.git
cd woff2

默认编译出的 woff2_compress 只有一个参数,而 ttf2woff 的执行是 ttf2woff /opt/xx/a.ttf /opt/xx/a.woff,需要我们 hack 下源码:

1
vi src/woff2_compress.cc

diff 信息为如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
diff --git a/src/woff2_compress.cc b/src/woff2_compress.cc
index 36e8fca..264dbfc 100644
--- a/src/woff2_compress.cc
+++ b/src/woff2_compress.cc
@@ -13,13 +13,13 @@


int main(int argc, char **argv) {
- if (argc != 2) {
- fprintf(stderr, "One argument, the input filename, must be provided.\n");
+ if (argc != 3) {
+ fprintf(stderr, "two argument, the input and output filename, must be provided.\n");
return 1;
}

std::string filename(argv[1]);
- std::string outfilename = filename.substr(0, filename.find_last_of(".")) + ".woff2";
+ std::string outfilename(argv[2]);
fprintf(stdout, "Processing %s => %s\n",
filename.c_str(), outfilename.c_str());
std::string input = woff2::GetFileContent(filename);

编译

1
2
3
4
5
6
7
8
9
10
11
export LFLAGS=-static
make clean all

#查看
$ ldd woff2_*
woff2_compress:
not a dynamic executable
woff2_decompress:
not a dynamic executable
woff2_info:
not a dynamic executable

构建替换的话,可以

1
2
3
4
5
...
FROM zhangguanzhang/woff2:amd64 AS tools
...
COPY --from=tools /woff2_* /usr/bin/

需要改名的话自行更改

arm64 编译

高版本 docker + qemu-aarch64-static

1
2
3
docker pull --platform arm64 ubuntu:20.04
docker run --rm -ti -v `which qemu-aarch64-static`:/usr/bin/qemu-aarch64-static \
-v $PWD:/opt -w /opt ubuntu:20.04

后续

客户有个字体转换失败,切成 node 的 https://github.com/fontello/ttf2woff 了,找了下 pkg 可以静态编译

1
2
3
4
5
6
FROM node:18-slim as build
RUN npm install ttf2woff pkg -g && \
pkg -o /ttf2woff --targets linuxstatic `which ttf2woff`

FROM scratch AS bin
COPY --from=build /ttf2woff /
CATALOG
  1. 1. 由来
  2. 2. 过程
  3. 3. arm64 编译
  4. 4. 后续