Google Font API 是 Google 提供的一项免费网络字体服务,允许开发者通过简单的 CSS 或 JavaScript 调用在网页中使用高质量的字体,而无需用户本地安装这些字体。
<!DOCTYPE html>
<html>
<head>
<link href="https://fonts.googleapis.com/css2?family=Roboto&display=swap" rel="stylesheet">
<style>
body {
font-family: 'Roboto', sans-serif;
}
</style>
</head>
<body>
<p>这段文字将使用Roboto字体显示</p>
</body>
</html>
// 创建link元素
const link = document.createElement('link');
link.href = 'https://fonts.googleapis.com/css2?family=Open+Sans&display=swap';
link.rel = 'stylesheet';
// 添加到head
document.head.appendChild(link);
// 应用字体
document.body.style.fontFamily = "'Open Sans', sans-serif";
@media print
确保打印时字体正确应用@media print {
body {
font-family: 'Roboto', sans-serif !important;
}
}
document.fonts.ready
API检查字体状态document.fonts.ready.then(() => {
window.print(); // 确保字体加载完成后再打印
});
&text=
参数只加载需要的字符,减少字体文件大小https://fonts.googleapis.com/css2?family=Roboto&text=Hello
原因:
解决方案:
function printWithFonts() {
const font = new FontFace('Roboto', 'url(https://fonts.gstatic.com/s/roboto/v30/KFOmCnqEu92Fr1Mu4mxK.woff2)');
font.load().then(() => {
document.fonts.add(font);
window.print();
}).catch(error => {
console.error('字体加载失败:', error);
window.print(); // 即使字体加载失败也允许打印
});
}
原因:
解决方案:
@media print {
* {
-webkit-print-color-adjust: exact !important;
print-color-adjust: exact !important;
}
}
<link href="https://fonts.googleapis.com/css2?family=Roboto+Flex:wght@100..1000&display=swap" rel="stylesheet">
<style>
.variable-font {
font-family: 'Roboto Flex', sans-serif;
font-variation-settings: "wght" 700, "wdth" 100;
}
</style>
<link rel="preload" href="https://fonts.googleapis.com/css2?family=Roboto&display=swap" as="style" onload="this.onload=null;this.rel='stylesheet'">
<noscript><link href="https://fonts.googleapis.com/css2?family=Roboto&display=swap" rel="stylesheet"></noscript>
通过以上方法,您可以确保从Google Font API获取的字体在网页显示和打印时都能正确呈现。
没有搜到相关的文章