ℕʘʘḆḽḘ
ℕʘʘḆḽḘ

Reputation: 19375

How to print an html table to pdf?

Consider this simple example

library(knitr)
library(kableExtra)
dt <- mtcars[1:5, 1:4]

# HTML table
kable(dt, format = "html", caption = "Demo Table") %>%
  kable_styling(bootstrap_options = "striped",
                full_width = F) %>%
  add_header_above(c(" ", "Group 1" = 2, "Group 2[note]" = 2)) %>%
  add_footnote(c("table footnote"))

enter image description here

Here I want a very simple thing. To print this table in a pdf (possibly in a pipe-able way). I want the table to look exactly like this.

I know this is html, but arent we able to print html pages to pdf in chrome? There has to be a way (I hope). I do not want to deal with latex and I do not want to create an rnotebook document. The rendering has to come from my bare .R script. Is that impossible?

Any ideas? Thanks!

Upvotes: 0

Views: 3388

Answers (1)

trosendal
trosendal

Reputation: 1234

Here is a solution to part of your problem of generating a table in pdf form. You will need to tweak the styling of your table in xtable in order to get the zebra stripe you want and merged columns. Generally speaking conversion from html to pdf is not so straightforward, so a better solution is to use LaTeX to generate your table in the first place (I know you didn't want LaTeX, but at least this is compiled to pdf with R and xtable does the hard work):

library(xtable)
dt <- mtcars[1:5, 1:4]
filename <- tempfile(fileext = ".tex")
capture.output(print(xtable(dt)), file = filename)
foo <- readLines(filename)
writeLines(c("\\documentclass[hidelinks]{article}",
             "\\begin{document}",
             foo,
             "\\end{document}"),
           con = filename)
tools::texi2dvi(filename, pdf = TRUE)

You should have a look at https://cran.r-project.org/web/packages/xtable/vignettes/xtableGallery.pdf to get your styling the way you want it. Good luck.

Edit: Seems you can use kabelExtra too:

library(knitr)
library(kableExtra)
dt <- mtcars[1:5, 1:4]

# LaTeX table
a <- kable(dt, format = "latex", caption = "Demo Table") %>%
  kable_styling(bootstrap_options = "striped",
                full_width = F) %>%
  add_header_above(c(" ", "Group 1" = 2, "Group 2[note]" = 2)) %>%
    add_footnote(c("table footnote"))

filename <- tempfile(fileext = ".tex")
capture.output(a, file = filename)
foo <- readLines(filename)
writeLines(c("\\documentclass[hidelinks]{article}",
             "\\begin{document}",
             foo,
             "\\end{document}"),
           con = filename)
tools::texi2dvi(filename, pdf = TRUE)

Upvotes: 1

Related Questions