【问题标题】:Is it possible to generate the RTable (FlexTable) in pdf with RMarkdown?是否可以使用 RMarkdown 生成 pdf 格式的 RTable (FlexTable)?
【发布时间】:2016-11-09 21:16:30
【问题描述】:

我只是好奇是否可以使用 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))),但它不起作用。

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

【问题讨论】:

    标签: r pdf r-markdown flextable


    【解决方案1】:

    这并不是一个答案,而只是一个指向解决此问题的可能方向的指针。通常,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)
    }
    

    【讨论】:

    • 非常感谢您的代码!我一定会努力的!我认为“Screenshot the html”是解决这个问题的一个很好的方向。此外,如果可以通过这种方式解决此问题,我们可以应用/扩展相同的方法将交互式图形输出为 pdf 问题。例如,如果我想保存“rpivotTable”(用于数据透视表的非常有用且灵活的 r 包之一)的结果,我可以截取 html 的屏幕截图并将图像返回给 knitr!再次感谢您的帮助!
    【解决方案2】:

    感谢@Yihui,

    我发现了这个问题。基本上,解决方案是通过webshot函数和knitr::include_graphics截屏,将这个png文件插入到pdf输出中。

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

    ```{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 的这个小问题?

    谢谢!

    【讨论】:

      猜你喜欢
      • 2020-08-15
      • 2013-05-08
      • 1970-01-01
      • 2019-11-02
      • 2016-01-30
      • 2011-08-10
      • 1970-01-01
      • 1970-01-01
      • 2020-11-30
      相关资源
      最近更新 更多