I'm trying to render image inside a flextable with R Markdown, which on render gives word document.
Sample R Markdown code:
---
title: "Untitled"
output: word_document
params:
img_path1: Excel whole.png
---
library(officer)
library(flextable)
library(kableExtra)
virus_summary <- data.frame(
Task = "Word Table",
"Completion Date" = as.character(format(Sys.Date(), '%B %d, %Y')),
stringsAsFactors = FALSE
)
img_object <- as_image(src = "./Excel whole.png", width = 1)
virus_tbl <- virus_summary |>
flextable() |>
compose(
j = "Task",
i = 1,
value = as_paragraph(
as_chunk("\n"),
as_chunk("Word Table"),
as_chunk("\n"),
as_chunk("\n"),
img_object
)
) |>
border_remove() |>
hline(part = "all", border = fp_border(color="black")) |>
vline(border = fp_border(color="black")) |>
vline_left(border = fp_border(color="black")) |>
hline_top(part = "all", border = fp_border(color="black")) |>
bold(bold = TRUE, part = "header") |>
width(width = 7.9, j = 1,unit = "cm") |>
width(width = 6.5, j = 2,unit = "cm") |>
padding(padding = 10, part = "all")
virus_tbl
In here you can use any image as you want.
Problem: When I run the code chunk only the image path is showing up instead of the image inside the table and same while knitting the R Markdown into word document.
Output of above code: Output Table
I get an error while running your script because source parameter for image of flextable::as_image()
is src
and not x
. With kableExtra, there is also a function named as_image()
, solution is to use the following:
img_object <- flextable::as_image(src = img.file, width = 1)
Without the conflicts that could happen with kableExtra, another point is that images in flextable can not be outputed with rmarkdown::word_document()
, it must be processed with officedown. See the note in as_image()
documentation:
This chunk option requires package officedown in a R Markdown context with Word output format.