Search code examples
rmagrittrofficer

R Create and execute an officer string


I want to create a powerpoint stack with pdfs I have created. I'm attempting to do this with officer. It works fine manually but I want to write the pdf out in code. Using a Two Content layout I want to write the name of the pdf into the title and paste the pdf itself into the body. Here is the code I've developed so far.

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

The problem I'm having is the last line in the for loop. If I manually construct that line, as in the following, it works

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

But the eval/parse approach doesn't work (with this message "invalid 'envir' argument of type 'expression") and neither does as.formula(finalString)


Solution

  • I figured out where to do eval/parse. The code below works as I wanted.

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