rmd_tp_docx_function.R

## Function for reading in RMD and spitting out word docs
##Custom made goodness???
#I hope
#Anthony
# FEb2020

#INputs
#inFile ==
#outFile ==

RmdToDOCX <- function (inFile = "", outFile = "", tocDepth = 2, copyFrom = NULL)
{
  if (!is.null(copyFrom)) {
    if (!stringr::str_detect(inFile, paste0("^", copyFrom,
                                            "/"))) {
      stop(paste0("inFile does not start with ", copyFrom,
                  "/ and you are using copyFrom=", copyFrom))
    }
    file.copy(inFile, gsub(paste0("^", copyFrom, "/"), "",
                           inFile), overwrite = TRUE)
    inFile <- gsub(paste0("^", copyFrom, "/"), "", inFile)
  }
  try({
    outDir <- tempdir()
    originalOutFile <- outFile
    #if (RAWmisc::PandocInstalled()) {
    outFile <- unlist(stringr::str_split(outFile, "/"))
    if (length(outFile) == 1) {
      #outDir <- getwd()
    }
    else {
      #outDir <- file.path(getwd(), outFile[-length(outFile)])
      outFile <- outFile[length(outFile)]
    }
    css <- system.file("extdata", "custom.css", package = "RAWmisc")
    rmarkdown::render(input = inFile, output_file = outFile,
                      output_dir = outDir, output_format = rmarkdown::word_document(toc = TRUE,
                                                                                    toc_depth = tocDepth))
    #}
    #else {
    #}
    cmd <- paste0("rm -f ",file.path(getwd(),originalOutFile))
    system(cmd)
    print(cmd)
    cmd <- paste0("cp -f ",file.path(outDir,outFile)," ",file.path(getwd(),originalOutFile))
    system(cmd)
    print(cmd)
  }, TRUE)
  if (!is.null(copyFrom)) {
    file.remove(inFile)
  }
}


#example
RmdToDOCX(
  inFile = "RunWP2.Rmd",outFile = paste0("reports_formatted/WP2_",format(Sys.time(), "%Y_%m_%d"),".docx"))
davan690/beech-publication-wr documentation built on March 29, 2020, 11:09 a.m.