【问题标题】:Adding image to flextable and generate my flextable in Word document using Rmarkdown将图像添加到 flextable 并使用 Rmarkdown 在 Word 文档中生成我的 flextable
【发布时间】:2019-11-02 00:46:37
【问题描述】:

首先,我在 Windows 10 中使用 R 3.6.0 和 Rstudio 1.2。

我正在使用 flextable 和 Office 来创建 Word 文档。在这张表中,我插入了一些图像。为此,我正在使用 flextable。当我将此代码与 R 脚本和官员一起使用时。但是,当我在 Rmarkdown 中使用此代码生成 Word 文档时,它不起作用。 Rmardown下的代码:


library(flextable)
library(officer)

img.file <- file.path( R.home("doc"), "html", "logo.jpg" )

myft <- flextable( head(iris))

myft <- compose( myft, i = 1:3, j = 1,
 value = as_paragraph(
   as_image(src = img.file, width = .20, height = .15),
   " blah blah ",
   as_chunk(Sepal.Length, props = fp_text(color = "red"))
 ),
 part = "body")

myft

我有一条消息告诉我:“抱歉,我们无法打开该文档,因为我们发现其内容存在问题。

我认为 flextable 中的图像有问题。当我删除这些图像时,它就起作用了。

【问题讨论】:

    标签: r ms-word r-markdown flextable officer


    【解决方案1】:

    是的,rmarkdown::word_document 不支持在 flextable 中插入图像。

    您将需要包 officedown 才能使用 R Markdown for Word 将图像嵌入到 flextable 中。您只需将output: rmarkdown::word_document 替换为 output: officedown::rdocx_document.

    ---
    date: "`r Sys.Date()`"
    author: "Your Name"
    title: "Untitled"
    output: 
      officedown::rdocx_document
    ---
    
    ```{r setup, include=FALSE}
    knitr::opts_chunk$set(echo = TRUE, fig.cap = TRUE)
    library(officedown)
    ```
    
    ```{r}
    library(flextable)
    library(officer)
    
    img.file <- file.path( R.home("doc"), "html", "logo.jpg" )
    
    myft <- flextable( head(iris))
    
    myft <- compose( myft, i = 1:3, j = 1,
                     value = as_paragraph(
                       as_image(src = img.file, width = .20, height = .15),
                       " blah blah ",
                       as_chunk(Sepal.Length, props = fp_text(color = "red"))
                     ),
                     part = "body")
    
    autofit(myft)
    ```
    

    要安装软件包,请运行以下命令(尚未在 CRAN 上):remotes::install_github("davidgohel/officedown")

    【讨论】:

    • 谢谢大卫,这行得通。关键,officedown!干得好!
    猜你喜欢
    • 2021-12-30
    • 2020-08-15
    • 1970-01-01
    • 1970-01-01
    • 2021-03-06
    • 1970-01-01
    • 2021-08-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多