需求背景
centos7 下 JAVA 生成圖片水印時中文亂碼,原因是沒有安裝中文字體。
安裝中文字體
以下是基于 Centos7 手動安裝中文字體的詳細步驟。當測試或者生產環境服務器比較多的時候,建議使用自動化運維工具。
# 安裝字體庫
$ yum -y install fontconfig
# 查看是否有中文字體
$ fc-list :lang=zh
# 創建中文字體目錄
$ mkdir /usr/share/fonts/chinese
# 在 windows 的 C:WindowsFonts 目錄下找到相應的字體 copy 到 chinese 目錄下,這里以 宋體 為例
$ scp simsun.ttc simsunb.ttf root@xxxxx:/usr/share/fonts/chinese
# 查看是否有中文字體
$ fc-list :lang=zh
/usr/share/fonts/chinese/simsun.ttc: SimSun,宋體:style=Regular,常規
/usr/share/fonts/chinese/simsun.ttc: NSimSun,新宋體:style=Regular,常規
Ansible 批量安裝
通常測試或者生產環境服務器比較多,下面記錄如何使用 Ansbile 來批量安裝中文字體。
# ansbile playbook 執行
$ ansible-playbook fonts.yml
# 驗證所有服務器是否生效
$ ansible all -m shell -a "fc-list :lang=zh"
sever01 | SUCCESS | rc=0 >>
/usr/share/fonts/chinese/simsun.ttc: SimSun,宋體:style=Regular,常規
/usr/share/fonts/chinese/simsun.ttc: NSimSun,新宋體:style=Regular,常規
sever02 | SUCCESS | rc=0 >>
/usr/share/fonts/chinese/simsun.ttc: SimSun,宋體:style=Regular,常規
/usr/share/fonts/chinese/simsun.ttc: NSimSun,新宋體:style=Regular,常規
......
fonts.yml 內容:
---
- name: Install Chinese Fonts.
hosts: all
remote_user: root
become: yes
become_method: sudo
become_user: root
roles:
- fonts
ansible playbook 目錄結構(刪除了無用目錄):
$ tree roles/fonts
roles/fonts
├── files
│ ├── simsun.ttc
│ └── simsunb.ttf
└── tasks
└── main.yml
2 directories, 3 files
task/main.yml 內容:
---
# tasks file for fonts
- name: install fontconfig.
yum:
name: "{{ item }}"
state: installed
with_items:
- fontconfig
ignore_errors: true
- name: mkdir /usr/share/fonts/chinese.
file:
path: /usr/share/fonts/chinese
state: directory
mode: 0755
- name: Copy fonts to agent.
copy:
src: "{{ item }}"
dest: /usr/share/fonts/chinese
with_items:
- simsun.ttc
- simsunb.ttf