首页 > 解决方案 > 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;
}

标签: javascriptcssreactjsprintingfont-face

解决方案


最终我得出结论,我应该使用 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;
}

推荐阅读