PhantomJS字体渲染

PhantomJS font rendering

本文关键字:字体 PhantomJS      更新时间:2023-09-26

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');
}

答案是"取决于"。Phantomjs作为一种"无头"浏览器,与任何其他浏览器类似,因为只有在进行渲染的系统上安装了上述字体,它才能渲染该字体。如果当我点击你的网页时,我的机器上安装了Roboto,那么我会像预期的那样看到Roboto。然而,如果我的本地机器上没有安装Roboto,它将呈现浏览器使用的任何默认回退字体。

Phantomjs完全可以渲染谷歌字体,比如Roboto,如果你把它们作为外部字体加载,从第三方网站链接。或者,更好的是,使用https://github.com/typekit/webfontloader这将为您完成加载web字体的繁重工作。

从Phantomjs2.0开始,Phantomjs能够呈现"websafe"字体。然而,这将再次取决于这些字体是否安装在有问题的机器上。例如,如果您的Web服务器运行的是Linux版本,则可能会出现问题。这是因为"websafe"字体实际上是Microsoft字体,并且已被Windows和OSX等操作系统许可使用。这样的字体不一定安装在其他操作系统中,并且可能需要手动安装,如本文所述。

因为页眉、页脚和内容是分开的,所以需要在每个部分中包含字体。

请按照这个例子,在你的标题中得到字体结果

在标题处添加这个:

"<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('./');

应在标头、中工作

希望它能帮助任何

我花了很多时间来解决类似的问题。我用各种url(绝对路径、相对路径、http url等)定义了@font-face,但什么都不起作用。在将所有字体放入~/.fonts目录、删除CSS中的所有@font-face声明并仅使用font-family之后,一切都开始工作。它是在CentosLinux发行版上运行的(带有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