【问题标题】:PhantomJS font renderingPhantomJS 字体渲染
【发布时间】:2014-12-09 09:48:53
【问题描述】:
PhantomJS 可以渲染网页中嵌入的 truetype 字体吗?
我有这样的css
@font-face {
font-family: 'Roboto';
font-style: normal;
font-weight: normal;
src: local('Roboto-Regular.ttf'), url('Roboto-Regular.ttf') format('truetype');
}
【问题讨论】:
标签:
javascript
phantomjs
webfonts
truetype
【解决方案1】:
我花了很多时间来解决类似的问题。我用各种 url(绝对路径、相对路径、http url 等)定义了 @font-face,但没有任何效果。将所有字体放入 ~/.fonts 目录后,一切都开始工作,删除 CSS 中的所有 @font-face 声明并仅使用 font-family。它在 CentOS Linux 发行版上(带有phantomjs-prebuilt 模块,版本:2.1.16),但我认为它也适用于其他版本。
html, body {
font-family: 'Roboto Condensed', sans-serif;
zoom: 0.70; /* fix for too large fonts */
}
$ ls ~/.fonts/
drwxr-xr-x. 2 root root 4096 06-03 15:16 .
drwxr-xr-x. 10 root root 4096 04-15 13:56 ..
-rw-r--r--. 1 root root 11358 2017-05-26 LICENSE.txt
-rw-r--r--. 1 root root 175888 2017-05-26 RobotoCondensed-BoldItalic.ttf
-rw-r--r--. 1 root root 169800 2017-05-26 RobotoCondensed-Bold.ttf
-rw-r--r--. 1 root root 175188 2017-05-26 RobotoCondensed-Italic.ttf
-rw-r--r--. 1 root root 175380 2017-05-26 RobotoCondensed-LightItalic.ttf
-rw-r--r--. 1 root root 168004 2017-05-26 RobotoCondensed-Light.ttf
-rw-r--r--. 1 root root 170284 2017-05-26 RobotoCondensed-Regular.ttf
【解决方案2】:
因为页眉页脚和内容是分开的,所以您需要在每个部分中包含字体。
请按照示例并在标题中获取字体结果
在标题处添加:
"<style> "+
"@font-face {"+
" format('ttf'); "+
"font-family: 'Open Sans'; "+
"font-style: normal; "+
"font-weight: 400; "+
"src: url(" + url + "/fonts/Open_Sans/OpenSans-Regular.ttf) format('truetype');"+
"} " +
"* { font-family: 'Open Sans'; } </style > "
参数 url 定义为运行 phantomjs.exe 的路径,并使用:
url = 'file:///' + fs.absolute('./');
应该在标题中工作,
希望对大家有帮助
【解决方案3】:
答案是“视情况而定”。 Phantomjs,作为一个“无头”浏览器,与任何其他浏览器类似,如果该字体安装在进行渲染的系统上,它只能渲染上述字体。如果我在访问您的网页时在我的机器上安装了 Roboto,那么我将按预期看到 Roboto。但是,如果我的本地计算机上没有安装 Roboto,它将呈现我的浏览器使用的任何默认后备字体。
如果您将 Google 字体(如 Roboto)加载为从第三方网站链接的外部字体,Phantomjs 不仅能够渲染 Google 字体。或者,更好的是,使用https://github.com/typekit/webfontloader,它将为您完成加载网络字体的繁重工作。
从 Phantomjs 2.0 开始,phantomjs 能够呈现“websafe”字体。但是,这将再次取决于这些字体是否安装在相关机器上。例如,如果您的网络服务器运行的是 Linux 风格,您可能会遇到问题。这是因为“网络安全”字体实际上是 Microsoft 字体,并且已获得许可,可用于 Windows 和 OSX 等操作系统。此类字体不一定安装在其他操作系统中,可能需要手动安装,如here 所述。