javascript - React js:要在新选项卡中打印组件时加载字体
问题描述
我编写了一个以特定格式打印接收到的数据的组件。该组件使用 printData 方法进行打印。此方法接收需要打印的组件 ID,将其放入新选项卡中,然后打印。问题是我在整个程序中使用了特定的字体并为其定义了字体并将字体文件放入项目中。但是当这个组件在新选项卡中打开时,无法加载字体。如果您知道此问题的解决方案或者您有更好的解决方案,请指导我。谢天谢地。
export function printData(printDivId) {
const mywindow = window.open("", "PRINT");
mywindow.document.write(document.getElementById(printDivId).innerHTML);
mywindow.document.close();
mywindow.focus();
mywindow.print();
mywindow.close();
return true;
}
解决方案
最终我得出结论,我应该使用 CDN 链接而不是字体文件。这样,在新窗口中,我通过链接加载字体并将该样式添加到整个页面。printData 方法可以这样更新:
export function printData(printDivId) {
const mywindow = window.open("", "PRINT");
mywindow.document.write(
'<html><head><style>@font-face {font-family: BYekan;src: url("//db.onlinewebfonts.com/t/52ce4de2efeeb8b18dcbd379711224f3.eot");src: url("//db.onlinewebfonts.com/t/52ce4de2efeeb8b18dcbd379711224f3.eot?#iefix")format("embedded-opentype"),url("//db.onlinewebfonts.com/t/52ce4de2efeeb8b18dcbd379711224f3.woff2")format("woff2"),url("//db.onlinewebfonts.com/t/52ce4de2efeeb8b18dcbd379711224f3.woff")format("woff"),url("//db.onlinewebfonts.com/t/52ce4de2efeeb8b18dcbd379711224f3.ttf")format("truetype"),url("//db.onlinewebfonts.com/t/52ce4de2efeeb8b18dcbd379711224f3.svg#B Yekan")format("svg");} body,html {font-family: BYekan !important;}</style></head><body>'
);
mywindow.document.write(document.getElementById(printDivId).innerHTML);
mywindow.document.write("</body></html>");
mywindow.document.close();
mywindow.focus();
mywindow.print();
mywindow.close();
return true;
}
推荐阅读
- jpa - wildfly-preview-25.0.0.Final - Jakarta 'org.hibernate.ogm.jpa.HibernateOgmPersistence' 未找到
- microservices - 不共享数据库的微服务设计
- windows - 为什么 .npmrc 未定义(在 Windows 上)?
- python - 如何在pygame python中渲染多行字符串
- ruby-on-rails - RSpec 控制器 GET #index 测试返回一个空的 ActiveRecord 数组而不是我的模型
- reactjs - algolia + reactjs:自动完成插件查询建议:显示空白用户界面
- javascript - 以特定方式更改给定字符串的顺序
- sql - 针对数据集在表中运行多个 SQL 查询
- javascript - 角度的电子邮件验证
- ios - 在 Safari Web Extension (iOS 15) 中将消息从应用程序 (popup.js) 发送到 JS (content.js)