How to include @font-face within style tag of RMarkdown?

末鹿安然 提交于 2020-05-17 05:45:15

问题


Is it possible to use the CSS @font-face to provide font files to an RMarkdown?

e.g.:

<style>
@font-face {
    font-family: "Custom";
    src: url(https://github.com/stevecondylios/fonts/raw/master/CircularStd-Book.ttf) format("truetype");
}
body {
    font-family: "Custom", Verdana, Tahoma;
}
</style>

Note that the exact same css code above (less the style tags) does work when it's stored in an external .css file locally and referenced in the Rmd's yaml with

---
title: "My Rmarkdown doc"
date: "28 April 2020"
output: 
  html_document:
    css: mystyles.css
---

Ultimate goal

In case this is an A/B problem, my simple goal is to apply a custom font while avoiding using any local files beyond the Rmd file itself (i.e. no local external style sheets, although reading files from the web is fine).

I believe the only two options are either reading a font file in from the web within <style> ... </style>, or base64 encoding the font info within the tags of the Rmd itself. I've been trying both with little success.

A third option could be to provide a url (to a style sheet) to a yaml value, although I am not sure if that's possible

  html_document:
    code_folding: hide
    css: get_file(www.mysite.com/mystyles.css)

Further attempts

For good measure, I also tried

```{r}
css_url <- "https://github.com/stevecondylios/fonts/raw/master/CircularStd-Book.ttf"
```

<style>
@font-face {
    font-family: "Custom";
    src: url(`r css_url`) format("truetype");
}
body {
    font-family: "Custom", Verdana, Tahoma;
}
</style>
```

Update

I have learned you cannot declare @font-face in the HTML body, but must do so in the header. We can indeed add HTML tags into the RMarkdown header, but this reads in an external file, which is precisely what I'm trying to avoid, so am back to square 1.


回答1:


For anyone else who wants to do this, this answer was what helped.

Basically:

  1. Download a .tff (font) file from any font website
  2. Convert it to base64 (on mac, simply base64 myfont.ttf > myfont_base64.txt
  3. Copy the contents of myfont_base64.txt in the placeholder below, and place the whole lot somewhere in your RMarkdown (it doesn't have to be in the HTML <head> as I previously suspected, but anywhere e.g. the <body> is fine)
<style>
@font-face {
    font-family: 'myfont';
    src: url(data:font/truetype;charset=utf-8;base64,<<copied base64 string>>) format('truetype');
    font-weight: normal;
    font-style: normal;
}
body { 
    font-family: "myfont", Verdana, Tahoma;
}
</style>


来源:https://stackoverflow.com/questions/61528612/how-to-include-font-face-within-style-tag-of-rmarkdown

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!