Hello -
I have a gt table that includes sparklines and plots inline. The code broadly follows this excellent post by Albert Rapp.
I'm looking to render the table to a docx document, with the format and charts as it appears in the R Studio Viewer. However, I get unformatted tables with html code.
Would you have any suggestions?
Thanks!
1 Like
Rendering a gt table with sparklines and plots into a Word (DOCX) document is tricky because gt primarily exports as HTML, which Word doesn’t fully support.
Possible Solutions:
-
Use officer
+ flextable
: Convert gt
to flextable
for better Word compatibility.
library(gt)
library(flextable)
library(officer)
gt_tbl <- gt(mtcars)
flex_tbl <- flextable(gt_tbl)
read_docx() %>%
body_add_flextable(flex_tbl) %>%
print(target = "output.docx")
However, inline plots may not render properly.
-
Save Plots as Images & Embed in flextable
:
- Generate sparklines/plots as PNGs.
- Use
flextable::external_img()
to insert them into the Word table.
-
Use webshot
for Screenshot-Based Export:
library(webshot2)
gtsave(gt_tbl, "table.png")
Then insert table.png
into Word manually or via officer
.
Since Word has limited support for HTML-based tables, the best approach is converting to flextable
and embedding images for plots.
1 Like
This is very helpful, thank you very much. I’ll give these a try and see where I land.
Related, is it easier to get from html to pdf (if not word)? I’d be happy to write most of my content in Quarto, render to html and save to pdf, if that was possible.
1 Like