R 创建并执行一个 officer 字符串

R Create and execute an officer string

我想用我创建的 pdf 创建一个 powerpoint 堆栈。我正在尝试与军官一起做这件事。它手动工作正常,但我想用代码写出 pdf。使用 Two Content 布局,我想将 pdf 的名称写入标题并将 pdf 本身粘贴到 body 中。这是我到目前为止开发的代码。

library(officer)
library(magrittr)
pdfList <- c("pdf1.pdf", "pdf2.pdf", "pdf3.pdf")
pdfDir <- "pdfDir"
my_pres<-read_pptx("presentations/blank.pptx") # a blank pptx from powerpoint
pageStart <- "add_slide(layout='Two Content', master='Office Theme') %>% " 
titleListPre <-  "ph_with_text(type = 'title', str = '"
titleListPost <- "') %>% "
imageListPre <- "ph_with_img(src = 'graphics/SSPs/final/"
imageListPost <- "', type = 'body') "

for (i in pdfList) {
  titleString <- paste0(titleListPre, i, titleListPost)
  imageString <- paste0(imageListPre, i, imageListPost)
  finalString <- paste0(pageStart, titleString, imageString)
   my_pres <- my_pres %>%  eval(parse(text = finalString))
}

我遇到的问题是 for 循环中的最后一行。如果我手动构造该行,如下所示,它会起作用

my_pres <- my_pres %>% add_slide(layout='Two Content', master='Office Theme') %>% ph_with_text(type = 'title', str = 'pdf1.pdf') %>% ph_with_img(src = 'graphics/SSPs/final/pdf1.pdf', type = 'body')

但是 eval/parse 方法不起作用(消息为“invalid 'envir' argument of type 'expression”),as.formula(finalString)

也不起作用

我想出了在哪里做 eval/parse。下面的代码如我所愿。

pageStart <- "add_slide(layout='Two Content', master='Office Theme') %>% " 
titleListPre <-  "ph_with_text(type = 'title', str = '"
titleListPost <- "') %>% "
imageListPre <- "ph_with_img(src = 'graphics/SSPs/final/"
imageListPost <- "', type = 'body') "

for (i in imageList) {
  titleString <- paste0(titleListPre, i, titleListPost)
  imageString <- paste0(imageListPre, i, imageListPost)
  finalString <- paste0("my_pres %>% ",pageStart, titleString, imageString)
  my_pres <- eval(parse(text = finalString))
}