2

我只是好奇是否可以使用 RMarkdown 生成 pdf 格式的 RTable(FlexTable)?我可以在 html 输出中生成它,但它不适用于 pdf 输出。我用谷歌搜索了这个问题,但没有确切的答案。

我的代码:

```{r, echo=FALSE, results='asis'}
library(ReporteRsjars)
library(ReporteRs)
library(rtable)
library(dplyr)
vanilla.table(iris)
```

由于它可以用word生成,我认为它可以用于pdf。

我已经尝试过cat(as.html(vanilla.table(iris))),但它不起作用。

我可以友好地问一下您是否对此有任何想法?

4

2 回答 2

2

谢谢@易慧,

我想通了这个问题。基本上,解决方案是按webshot功能截取屏幕截图knitr::include_graphics并将此 png 文件插入到 pdf 输出中。

请在您的降价中尝试这段代码:

```{r TableJiena, out.width = "700px", out.length = "400px"}

insert_screenshot = function(x) {
  if (!inherits(x, c('html', 'shiny.tag'))) return()
  htmltools::save_html(x, 'temp.html')
  res = webshot::webshot('temp.html', 'my-screenshot.png')
  knitr::include_graphics(res)
}
insert_screenshot(htmltools::HTML(as.html(vanilla.table(head(iris)))))
```

如果您想获得简化的代码,请在 Markdown 中尝试这段代码。

```{r TableJiena, out.width = "700px", out.length = "400px"}
webshot::webshot(htmltools::HTML(as.html(vanilla.table(head(iris)))), 'my-screenshot.png')
knitr::include_graphics('my-screenshot.png')
```

但是这个解决方案有个小问题:PNG图片的解决方案不是很高,不知道为什么每列之间有流量。此外,一些单行打印成双行。

谁能弄清楚如何解决这个小问题webshot

谢谢!

于 2016-11-15T18:05:59.127 回答
2

这并不意味着是一个答案,而只是一个指向解决这个问题的可能方向的指针。通常,R Markdown 文档的 R 代码块中的 HTML 输出不适用于 PDF 输出,因为 HTML 和 LaTeX 完全不同。但是,有一种间接的方法可以到达那里,即截取 HTML 输出的屏幕截图并插入图像。当输出格式不是 HTML 时,这种方法在knitr中用于处理 HTML 小部件。您可以在https://github.com/yihui/knitr/blob/master/R/plot.R找到技术细节 (见html_screenshot()函数)。

基本思想是将 HTML 输出保存为*.html文件,使用webshot包(需要 PhantomJS)截取屏幕截图,然后将图像返回给knitr。将这个想法推广到任何 HTML 输出应该不会太难,但我没有仔细考虑过。但这并不意味着您不能自己实现它。下面是我在脑海中打出的草图,当然还有很多细节需要改进:

insert_screenshot = function(x) {
  if (!inherits(x, c('html', 'shiny.tag'))) return()
  htmltools::save_html(x, 'temp.html')
  res = webshot::webshot('temp.html', 'my-screenshot.png')
  knitr::include_graphics(res)
}
于 2016-11-09T21:45:13.223 回答