0

library(officer) library(flextable) library(ggplot2)

I'm creating a shiny app that generates a word document, and I can do that but I also want the users to preview the results before they generate it. I am using pandoc_convert but the plot doesn't display.

I'm not putting my shiny app here as the only problem is with converting the word file to html format.

# Create a ggplot
plot_ggplot <- function() {
  ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width, color = Species)) +
    geom_point() +
    labs(title = "Scatter Plot of Sepal Length vs Sepal Width",
         x = "Sepal Length",
         y = "Sepal Width")
}

# Create a FlexTable
flex_table <- flextable(head(iris))

# Create a Word document
doc <- read_docx()

# Add the FlexTable and ggplot to the document
doc <- body_add_flextable(doc, value = flex_table)
doc <- body_add_gg(doc, value = plot_ggplot())

# Save the Word document
output_file <- "iris_visualizations.docx"
print(doc, target = output_file)
# Convert Word document to HTML
output_html_file <- "iris_visualizations.html"
pandoc_convert(output_file, to = "html", output = output_html_file)
stefan
  • 90,330
  • 6
  • 25
  • 51
Mel
  • 157
  • 9
  • [How to create a Minimal, Reproducible Example](https://stackoverflow.com/help/minimal-reproducible-example) – Jan Jul 26 '23 at 18:05
  • 1
    Just a suggestion: As you want different output formats (and as you already added the `r-markdown` tag), have you thought about using RMarkdown (instead of officer), i.e. create an Rmd template which you can then render both as HTML and/or Word? – stefan Jul 26 '23 at 20:06
  • Hi @stefan that is a good suggestion, I will do that – Mel Aug 07 '23 at 14:59

0 Answers0