最近用CentOS上,用puppeteer把html生成pdf,但是生成文件后,但是中文內容是亂碼。
首先考慮的就是操作系統是否有中文字體,在CentOS 7中發現輸入fc-list :lang=zh命令查看字體返回列表是空;
[root@w183 chinese]# fc-list :lang=zh [root@w183 chinese]#
那么接下來就記錄一下在 CentOS 7中如何安裝思源黑體字體。
上傳字體文件到服務器上
[root@w183 chinese]# ll total 57136 -rw-r--r-- 1 root root 8608184 Jun 11 11:22 SourceHanSansCN-Bold.otf -rw-r--r-- 1 root root 7704352 Jun 11 11:22 SourceHanSansCN-ExtraLight.otf -rw-r--r-- 1 root root 8785564 Jun 11 11:22 SourceHanSansCN-Heavy.otf -rw-r--r-- 1 root root 8297476 Jun 11 11:22 SourceHanSansCN-Light.otf -rw-r--r-- 1 root root 8390148 Jun 11 11:22 SourceHanSansCN-Medium.otf -rw-r--r-- 1 root root 8344108 Jun 11 11:22 SourceHanSansCN-Normal.otf -rw-r--r-- 1 root root 8364840 Jun 11 11:22 SourceHanSansCN-Regular.otf
添加中文字體
首先在/usr/shared/fonts目錄下新建一個目錄chinese
[root@w183 chinese]#mkdir -p /usr/share/fonts/chinese
將上傳的字體文件cp至/usr/shared/fonts/chinese目錄下
[root@w183 chinese]#cp SourceHanSansCN* /usr/share/fonts/chinese/
修改chinese目錄的權限
[root@w183 chinese]#chown -R root:root /usr/share/fonts/chinese
修改字體配置文件
[root@w183 chinese]#vi /etc/fonts/fonts.conf <!-- Font directory list 字體目錄列表 --> <dir>/usr/share/fonts</dir> <dir>/usr/share/fonts/chinese</dir> <!--把我們添加的中文字體位置加進去--> <dir>/usr/share/X11/fonts/Type1</dir> <dir>/usr/share/X11/fonts/TTF</dir> <dir>/usr/local/share/fonts</dir> <dir prefix="xdg">fonts</dir> <!-- the following element will be removed in the future --> <dir>~/.fonts</dir>
輸入:wq保存退出,最后刷新內存中的字體緩存
[root@w183 chinese]#fc-cache
通過fc-list看一下字體列表
[root@w183 chinese]# fc-list :lang=zh /usr/share/fonts/chinese/SourceHanSansCN-Medium.otf: Source Han Sans CN Medium,思源黑體 CN,Source Han Sans CN:style=Regular,Medium /usr/share/fonts/chinese/SourceHanSansCN-ExtraLight.otf: Source Han Sans CN ExtraLight,思源黑體 CN,Source Han Sans CN:style=Regular,ExtraLight /usr/share/fonts/chinese/SourceHanSansCN-Bold.otf: Source Han Sans CN,Source Han Sans CN Bold:style=Bold /usr/share/fonts/chinese/SourceHanSansCN-Normal.otf: Source Han Sans CN Normal,思源黑體 CN,Source Han Sans CN:style=Regular,Normal /usr/share/fonts/chinese/SourceHanSansCN-Regular.otf: Source Han Sans CN,Source Han Sans CN Regular:style=Regular /usr/share/fonts/chinese/SourceHanSansCN-Light.otf: Source Han Sans CN Light,思源黑體 CN,Source Han Sans CN:style=Regular,Light /usr/share/fonts/chinese/SourceHanSansCN-Heavy.otf: Source Han Sans CN Heavy,思源黑體 CN,Source Han Sans CN:style=Bold,Heavy
可以看到已經成功安裝上了中文字體,至此安裝過程就全部結束,再次重新生成pdf可以發現中文樣式和內容均已可以正常顯示了。
總結
簡單記錄一下在CentOS 7中安裝中文字體的問題,希望對遇到同樣問題的同學有所幫助,The End。