Заменить текст и цвет фона текстового документа - PullRequest
0 голосов
/ 29 октября 2018

Я хотел бы создать шаблон с тегами, которые выделены. Теги должны быть заменены некоторыми данными с R. Я выделил текст в файле шаблона и хочу, чтобы в выходном файле был пустой фон.

Я пробовал officer, потому что он кажется самым зрелым R -пакетом для манипулирования word документами. Я пробовал функции body_replace_all_text и body_replace_text_at_bkm, но ни один из них не предоставляет возможности изменить форматирование.

Я полностью открыт для другого подхода. Жесткие требования заключаются в том, что шаблон и выходной файл должны редактироваться нетехническим сотрудником (таким образом, документ Word), а поля ввода в шаблоне должны быть каким-то образом выделены. Это означает, что если сотрудник вручную отредактирует шаблон , он не пропустит ни одного тега.

код

library(officer)
library(magrittr)

template <- read_docx("template.docx")

pattern <- "<tags>"
replacement <- "tags"
template <- template %>%
  body_replace_all_text(pattern, replacement)

pattern <- "<color.*?/color>"
replacement <- "yellow"
template <- template %>%
  body_replace_all_text(pattern, replacement)

print(template, target = "output.docx")

template.docx

template.docx

output.docx

enter image description here

desired_output.docx

enter image description here

Редактировать

Решил эту проблему, исправив пакет officer. Это немного странно, поэтому я все еще открыт для более чистого решения.

replace_all_text.custom = function( oldValue, newValue, onlyAtCursor=TRUE, warn = TRUE, ... ) {

  oldValue <- enc2utf8(oldValue)
  newValue <- enc2utf8(newValue)

  replacement_count <- 0

  base_node <- if (onlyAtCursor) self$get_at_cursor() else self$get()

  # For each matching text node...
  for (text_node in xml_find_all(base_node, ".//w:t")) {
    # ...if it contains the oldValue...
    if (grepl(oldValue, xml_text(text_node), ...)) {
      replacement_count <- replacement_count + 1
      # Replace the node text with the newValue.
      xml_text(text_node) <- gsub(oldValue, newValue, xml_text(text_node), ...)
      # remove background color
      xml_remove(xml_find_all(text_node, "..//w:highlight"))
    }
  }

  # Alert the user if no replacements were made.
  if (replacement_count == 0 && warn) {
    search_zone_text <- if (onlyAtCursor) "at the cursor." else "in the document."
    warning("Found 0 instances of '", oldValue, "' ", search_zone_text)
  }

  self
}

docx_part.custom <- officer:::docx_part
docx_part.custom$public_methods$replace_all_text <- replace_all_text.custom

assignInNamespace("docx_part", docx_part.custom, ns = "officer")
...