【问题标题】:How to print an html table to pdf?如何将html表格打印为pdf?
【发布时间】:2018-09-19 11:26:37
【问题描述】:

考虑这个简单的例子

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"))

在这里我想要一个非常简单的东西。以pdf 打印此表(可能以管道方式)。我希望表格看起来完全像这样。

我知道这是html,但我们不能在chrome 中将html 页面打印到pdf 吗?必须有办法(我希望)。我不想处理乳胶,也不想创建rnotebook 文档。渲染必须来自我的裸 .R 脚本。这不可能吗?

有什么想法吗? 谢谢!

【问题讨论】:

    标签: r markdown r-markdown


    【解决方案1】:

    这是您生成 pdf 格式表格的部分问题的解决方案。您需要在xtable 中调整表格的样式,以获得所需的斑马条纹和合并的列。一般来说,从 html 到 pdf 的转换并不是那么简单,所以更好的解决方案是首先使用 LaTeX 生成表格(我知道你不想要 LaTeX,但至少这是用 R 和 @ 编译成 pdf 987654324@辛苦了):

    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)
    

    您应该查看https://cran.r-project.org/web/packages/xtable/vignettes/xtableGallery.pdf 以获得您想要的样式。祝你好运。

    编辑: 看来你也可以使用kabelExtra

    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)
    

    【讨论】:

    猜你喜欢
    • 2014-04-04
    • 2016-09-24
    • 2017-07-09
    • 1970-01-01
    • 2019-01-14
    • 2019-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多