yihui / knitr

A general-purpose tool for dynamic report generation in R
https://yihui.org/knitr/
2.36k stars 873 forks source link

Svglite device and custom fonts inside knitr #2272

Closed Darxor closed 10 months ago

Darxor commented 11 months ago

Using custom fonts with svglite device (with {systemfonts}, rather than loading them via {extrafont}) leads to issues:

Example

In my example I used Montserrat font (can be installed as system font from google fonts).

An .rmd like one bellow will produce warnings as one above and text in the chart will be rendered incorrectly.

---
title: "svglite reprex"
output: html_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(
  echo = TRUE,
  dev = "svglite",
  fig.height = 4L,
  fig.width = 8L
)

Example

Systemfonts successfully finds the font.

systemfonts::match_font("Montserrat")
library(ggplot2)
chart_data <- data.frame(
  x = -2L:2L,
  y = -2L:2L,
  label = "example text here"
)
ggplot(chart_data, aes(x, y)) +
  ggtext::geom_richtext(
    aes(label = label),
    size = 3L,
    family = "Montserrat"
  )
Produced chart:
![chart-1](https://github.com/yihui/knitr/assets/1351765/4c0d6dc7-c001-4452-b05a-dcf6a9fb4eb3)
Note: this chart will be absolutely fine when rendered with `svglite` directly.

## Proposed solution
The issue is caused by using a pdf device at the time of calling `evaluate()` in `eng_r()`, if chunk device was set to svglite. 
A change to `chunk_device()` to support `svglite` device seems to fix this and produces a report with no warnings and no visual issues. I will provide a PR for this.

![chart-2](https://github.com/yihui/knitr/assets/1351765/69caa457-8d37-48c9-be98-8742d6f69b90)

Issue is reproducible to me under macOS and Ubuntu

<details>
<summary>Session info</summary>

```r
r$> xfun::session_info('knitr')
R version 4.3.1 (2023-06-16)
Platform: aarch64-apple-darwin20 (64-bit)
Running under: macOS Ventura 13.4.1, RStudio 0

Locale: en_US.UTF-8 / en_US.UTF-8 / en_US.UTF-8 / C / en_US.UTF-8 / en_US.UTF-8

time zone: Europe/Moscow
tzcode source: internal

Package version:
  evaluate_0.21   graphics_4.3.1  grDevices_4.3.1 highr_0.10      knitr_1.43      methods_4.3.1   stats_4.3.1     tools_4.3.1     utils_4.3.1     xfun_0.39       yaml_2.3.7 

By filing an issue to this repo, I promise that

I understand that my issue may be closed if I don't fulfill my promises.

github-actions[bot] commented 4 months ago

This old thread has been automatically locked. If you think you have found something related to this, please open a new issue by following the issue guide (https://yihui.org/issue/), and link to this old issue if necessary.