elong0527 / r4csr

R for Clinical Study Report and Submission
https://r4csr.org/
Other
70 stars 33 forks source link

Add TLF assemble chapter #82

Closed nanxstats closed 2 years ago

nanxstats commented 2 years ago

This PR adds a starter template for the TLF assemble chapter, predominantly based on the existing flow.

The book compiles but the example is a bit rough and obviously needs some extra care to make it a meaningful one under the context of this book.

cc @wangben718

fb-elong commented 2 years ago

Could you also provide the rtf_assemble function source code? It should be a function that rely on officer.

nanxstats commented 2 years ago

This is a clean version.

#' Assemble RTF TLFs
#'
#' Add a set of RTF/TEXT fields into an rdocx object.
#'
#' @param input Character vector of file path.
#' @param output Character string to the output file path.
#' @param landscape Logical vector to determine whether to
#' display files as portrait or landscape.
#'
#' @section Specification:
#' \if{latex}{
#'   \itemize{
#'     \item Transfer files to toggle fields format in Word
#'     \item Insert into Word file using officer
#'   }
#' }
#' \if{html}{
#' The contents of this section are shown in PDF user manual only.
#' }
#'
#' @examples
#' \dontrun{
#' rtf_assemble(
#'   list.files(
#'     "outtable/",
#'     pattern = "*.rtf",
#'     full.names = TRUE
#'   ),
#'   output = "tmp.docx"
#' )
#' }
#'
#' @export
rtf_assemble <- function(input, output, landscape = FALSE) {
  input <- normalizePath(input)

  if (!all(file.exists(input))) {
    warning("Some files do not exist")
  }

  field <- ifelse(grepl("/", input),
    paste0("INCLUDETEXT \"", gsub("/", "\\\\\\\\", input), "\""),
    paste0("INCLUDETEXT \"", gsub("\\", "\\\\", input, fixed = "TRUE"), "\"")
  )

  if (length(landscape) == 1) {
    landscape <- rep(landscape, length(field))
  }

  docx <- officer::read_docx()

  for (i in seq_along(input)) {
    docx <-
      docx %>%
      officer::body_add_fpar(
        officer::fpar(
          officer::ftext("Table "),
          officer::run_word_field("SEQ Table \\* ARABIC"),
          officer::run_linebreak(),
          officer::run_word_field(field[i]),
          officer::run_pagebreak()
        )
      )
    if (landscape[i]) {
      docx <- officer::body_end_section_landscape(docx)
    } else {
      docx <- officer::body_end_section_portrait(docx)
    }
  }

  print(docx, target = output)

  invisible(output)
}