rr-markdownr-flextable

Is there a way to automatically position and fit a flextable object on a PowerPoint slide using RMarkdown?


The problem

When I generate a flextable object to be printed to a PowerPoint slide using RMarkdown, RMarkdown just sort of...throws the table on the slide.

```{r example}
tibble(
  COL_1 = seq(1, 25),
  COL_2 = seq(1, 25),
  COL_3 = seq(1, 25),
  COL_4 = seq(1, 25),
  COL_5 = seq(1, 25)
) |>
  qflextable() |>
  add_footer_row(values = "This is some example text just to highlight what gets lost in normal formatting.", colwidths = 5)
```

With the above code, I end up with something like this: enter image description here

What I want

Ideally, I'd like my table to be centered on the slide and formatted to fit, as in the below: enter image description here

Does anyone have any suggestions on how I can get the desired result without manually editing the slide in PowerPoint?

Note that this question was previously posed but did not receive a workable answer.


Solution

  • You can achieve that by using "officedown". But it requires some calculation. First know the slide dimensions (with office::slide_size()), then the flextable dimensions (with flextable_dim()) and finally compute the left and top positions that will be used by PowerPoint.

    Flextable can be positioned in the slide with knitr chunk parameters ft.left and ft.top.

    The following is illustrating the quick explanation.

    ---
    output: 
      officedown::rpptx_document:
        reference_doc: template_demo.pptx
    ---
    
    ```{r include=FALSE}
    knitr::opts_chunk$set(echo = FALSE)
    library(officedown)
    library(officer)
    library(flextable)
    library(magrittr)
    
    sl_size <- read_pptx("template_demo.pptx") %>% 
      add_slide(layout = "Title and Content", master = "Office Theme") %>% 
      slide_size()
    
    s_w <- sl_size$width 
    s_h <- sl_size$height
    
    ft <- flextable(head(iris)) %>% 
      fontsize(size = 18, part = "all") %>% 
      theme_vader() %>% 
      autofit()
    
    ft_dim <- flextable_dim(ft)
    
    left <- (s_w/2) - (ft_dim$widths/2)
    top <- (s_h/2) - (ft_dim$heights/2)
    ```
    
    ```{r ft.left=left, ft.top=top}
    ft
    ```
    
    

    enter image description here