rpdfr-markdownr-flextableline-spacing

How to reduce line spacing with flextable() in R Markdown to PDF


When knitting to HTML, flextable::line_spacing(space = 0) does what is expected: reducing the line spacing. When knitting to PDF, it does not. See the code below and the screenshot. I am using flextable version 0.7.3.

Setting the height has a similar effect, besides some of my real data runs on more lines, so setting an exact row height is not OK. Since I have conditional formatting in my real data, flextable is easier than, for instance, kableExtra::column_spec().

How can I get the PDF produced with flextable with actual reduced line spacing?

Screenprint_code_and_outputs

---
output:
  pdf_document:
    latex_engine: xelatex
  html_document:
    df_print: paged
---

```{r, echo = FALSE, message = FALSE}
library(tidyverse)
cars %>%
  head(10) %>%
  flextable::flextable() %>%
  flextable::line_spacing(space = 0,
                          part = "body",
                          unit = "mm")
```
 

Solution

  • Yes, PDF output does not support line spacing. There is a specific parameter for that, ft.arraystretch (height of each row relative to its default height - only for latex tables):

    ---
    output:
      pdf_document:
        latex_engine: xelatex
      html_document:
        df_print: paged
    ---
    
    ```{r, echo = FALSE, message = FALSE, ft.arraystretch = 1}
    library(tidyverse)
    cars %>%
      head(10) %>%
      flextable::flextable() %>%
      flextable::line_spacing(space = 0,
                              part = "body",
                              unit = "mm")
    ```