vincentarelbundock / tinytable

Simple and Customizable Tables in `R`
https://vincentarelbundock.github.io/tinytable
GNU General Public License v3.0
211 stars 18 forks source link

Word support via HTML via `chromote` #226

Closed vincentarelbundock closed 7 months ago

vincentarelbundock commented 7 months ago
---
format: docx
---

This is a test

```{r}
library(chromote)
b <- ChromoteSession$new()
{
  b$Page$navigate("https://arelbundock.com/trash.html")
  b$Page$loadEventFired()
}

tab <- b$Runtime$evaluate("document.querySelector('table').outerHTML")$result$value
sty <- b$Runtime$evaluate("document.querySelector('style').outerHTML")$result$value

out <- paste(
    "```{=html}",
    tab,
    sty,
    "```",
    sep = "\n")
class(out) <- "knit_asis"
out
vincentarelbundock commented 7 months ago

Maybe with servr to serve the page first.

vincentarelbundock commented 7 months ago
library(chromote)
library(tinytable)

tt(mtcars[1:3, 1:4]) |>
    style_tt(j = 1, color = "white", background = "teal") |>
    save_tt("example.html", overwrite = TRUE)

html_js_to_plain <- function(filename) {
    filename <- path.expand(filename)
    if (!file.exists(filename)) {
        msg <- sprintf("`%s` does not exist.", filename)
        stop(msg, call. = FALSE)
    }
    filename <- paste0("file:", filename)
    b <- ChromoteSession$new()
    b$Page$navigate(filename)
    b$Page$loadEventFired()
    js_code <- "var clone = document.body.cloneNode(true);
                clone.querySelectorAll('script').forEach(script => script.remove());
                clone.outerHTML;"
    body <- b$Runtime$evaluate(js_code)$result$value
    head <- b$Runtime$evaluate("document.querySelector('head').outerHTML")$result$value
    out <- paste('```{=html}', '<html lang="en">', head, body, '</html>', '```', sep = '\n')
    # out <- b$Runtime$evaluate("document.querySelector('html').outerHTML")$result$value
    b$close()
    out <- knitr::asis_output(out)
    return(out)
}

filename <- "~/Downloads/example.html"
html_js_to_plain(filename)
vincentarelbundock commented 7 months ago

pandoc does not recognize CSS, so we're stuck. This is useless for now, but keeping it in the sandbox folder just in case we eventually want "plain" html without having to interpret JS, which may be faster for readers (but slower for writers).