【Gist】Ubuntu 下非 root 用戶用 apt 安裝 Microsoft core fonts(包括Times New Roman)的 bash shell 腳本

背景

個人R語言作圖被要求使用 Times New Roman,一種有版權的在 Linux 下非預裝的字體。數據在公共雲服務器上進行分析,作爲租戶之一是沒有 root 權限的,曾經要求管理員安裝該字體但是不了了之。唉,需求無法滿足,“自己動手豐衣足食”纔是程序猿的本質不是?

apt 安裝

Ubuntu 下非 root 用戶雖然用不了apt install,但是可以用apt source獲取包源碼自行構建並安裝在指定的用戶目錄(這裏我指定的是~/apt)啊。圍繞這一點可以使用下面的 bash shell 腳本:

# clean
rm cabextract*
rm -rf cabextract*
rm msttcorefonts*
rm -rf msttcorefonts*

# cabextract
# Reference: http://corefonts.sourceforge.net/
cabBinDir=~/apt # install our package here
if [[ ! -f "${cabBinDir}/bin/cabextract" ]];then
  apt source cabextract
  rm cabextract*
  cabDir=`ls | grep "cabextract*"`
  cd $cabDir
  ./configure --prefix $cabBinDir
  make
  make install
  cd ..
fi

# temporary environment variable
export PATH=$cabBinDir/bin:$PATH

# ms fonts
apt source msttcorefonts
rm msttcorefonts*
fontDir=`ls | grep "msttcorefonts*"`
cd $fontDir
./debian/rules
mkdir -p cab-contents
cat ./debian/tmp/usr/share/package-data-downloads/ttf-mscorefonts-installer | grep -oP http://.*\.exe | while read i
do
  wget -t 0 $i
  cabextract --lowercase --directory=cab-contents `basename $i`
done

# Reference: https://www.wikihow.com/Install-TrueType-Fonts-on-Ubuntu
# If you don't have root/sudo privileges on the machine, you can put the TTF files in the ~/.fonts directory instead.
mkdir -p ~/.fonts
mv ./cab-contents/*.ttf ~/.fonts/

R語言檢查字體安裝

~/.fonts/大法好,無需手動配置就能被R語言自動檢測到字體文件的存在。

library(sysfonts)
font_files()
# 	path	file	family	face	version	ps_name
# 18	~/.fonts	times.ttf	Times New Roman	Regular	Version 2.82	TimesNewRomanPSMT
# 19	~/.fonts	timesbd.ttf	Times New Roman	Bold	Version 2.82	TimesNewRomanPS-BoldMT
# 20	~/.fonts	timesbi.ttf	Times New Roman	Bold Italic	Version 2.82	TimesNewRomanPS-BoldItalicMT
# 21	~/.fonts	timesi.ttf	Times New Roman	Italic	Version 2.82	TimesNewRomanPS-ItalicMT

字體使用

我需要使用該字體的場合之一是VennDiagram包的venn.diagram函數,韋恩圖中每個圈(category)的標籤字體用cat.fontfamily參數指定。
我發現一般字體能通過其ps_name來引用,這種方法應該是不需要showtext包協助(字變圖,不可,我還要用 Inkscape 後期修圖的),也不需要sysfontfont_add函數來手動添加目標字體的(試過但是會被替代字體Nimbus Roman取代)。
然而 Times New Roman 有點特殊,要使用該字體,輸入的參數cat.fontfamily的值不是TimesNewRomanPSMT而是TimesNewRoman,等你查看ggsave保存下來的 svg 文件的源碼就會發現Times New Roman這個字體是被硬編碼進 svg 文件中的了,保存爲 jpeg 格式也是 Times New Roman 字體,就很 nice!完爆font_add函數叫天天不應叫地地不靈。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章