Search code examples
rflextable

Getting flextable to knit to PDF


I feel like I've gone down a rabbit hole when all I want is some nice tables in my pdf. Long story, here goes:

I want to print some tables to a PDF from r markdown. I usually use Kable and it works fine. That being said, this table is going to have some really long values, and an unknown number of columns that get generated, and I was having a hard time specifying which column would be what width when I didn't know yet in kable. Anyhow, that led me to flextable.

When I knit to html, the table looks great, like so: enter image description here

But I'm having trouble knitting to pdf. I understand, via other stack answers, that flextable's need to be saved as images to be plotted to pdf. So I have code like this:

ft <- flextable(x)
ft <- autofit(ft)
tf <- tempfile(fileext = ".png")
## Not run: 
if( require("webshot2") ){
 save_as_image(x = ft, path = "myimage.png")
}

plot(tf)

But at first it gave me the error that I didn't have the webshot2 package, so after some trouble I installed that (it didn't line up with my version of R (I'm on rstudio.cloud) and then when I try to run it now, it says enter image description here

Am I missing something obvious? How do I save a flextable as an image and then plot it in my pdf?

I've also tried Joanna's solution here: Is it possible to generate the RTable (FlexTable) in pdf with RMarkdown? and r tells me could not find function "as.html". Even though both flextable and htmltools have been loaded.

P.s. providing reproducible data would be very long given all the code that generates the tables and the fact I need it to knit into a pdf, will provide rstudio.cloud link if anyone is interested


Solution

  • You can now produce PDF without the need of webshot package (flextable >= 0.6.0):

    ---
    title: "Untitled"
    output: 
      pdf_document:
        latex_engine: xelatex
    ---
    
    ```{r setup, include=FALSE}
    knitr::opts_chunk$set(echo = TRUE)
    library(flextable)
    ```
    
    ```{r}
    ft <- flextable(head(airquality))
    ft <- autofit(ft)
    theme_vader(ft)
    ```
    
    
    

    enter image description here