Morris Johnson
Morris Johnson

Reputation: 98

Rendering and outputing a .docx file in r shiny

The prior MS Word format, i.e, .doc, can easily be displayed in as shiny output using the htmltools::htmltemplate function. Not so, it seems, with .docx files, since they are xml. I've been trying to use the officer package which can read .docx files and produce an officer rdocx object. Then I try using the officer::to_html function which is supposed to convert a the officer-produced object into an HTML string. However, the error returned is:

"Error in UseMethod("to_html") : no applicable method for 'to_html' applied to an object of class "rdocx".

Clearly I am not understanding something.

Here is a reprex using the example from the documentation that produces the above error:

library(officer)

pinst <- plot_instr({
  z <- c(rnorm(100), rnorm(50, mean = 5))
  plot(density(z))
})

template <- system.file(package = "officer",
                        "doc_examples", "landscape.docx")
doc_2 <- read_docx(path = template)
doc_2 <- body_add_par(doc_2, "This is a table", style = "heading 2")
doc_2 <- body_add_table(doc_2, value = mtcars)
doc_2 <- body_add_par(doc_2, "This is a plot", style = "heading 2")
doc_2 <- body_add_plot(doc_2, pinst)

doc2html <- to_html(doc_2)

Officer is a great package, but is perhaps over-qualified for this use case? In any case, I'd appreciate any advice. I simply need to be able to display a .docx (xml) file as html in a shiny container, e.g. a tabpanel.

Upvotes: 1

Views: 362

Answers (1)

kraggle
kraggle

Reputation: 347

I made an officer::fpar() object and that converted to HTML. I know the usage is very vague in the functions definition.

object <- officer::fpar(officer::ftext("HELLO WORLD"))

officer::to_html(object)

"<p style=\"margin:0pt;text-align:left;border-bottom: 0.00pt solid transparent;border-top: 0.00pt solid transparent;border-left: 0.00pt solid transparent;border-right: 0.00pt solid transparent;padding-top:0pt;padding-bottom:0pt;padding-left:0pt;padding-right:0pt;line-height: 1;background-color:transparent;\"><span style=\"\">HELLO WORLD</span></p>"

Upvotes: 0

Related Questions