1

ハイライトされたタグを含むテンプレートを作成したいと思います。タグは、R. テンプレート ファイルでテキストを強調表示しましたが、出力ファイルで空白の背景が必要です。

ドキュメントを操作するためofficerの最も成熟したパッケージと思われるため、試してみました。と関数を試しましたが、どちらもフォーマットを変更するオプションを提供していないようです。Rwordbody_replace_all_textbody_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")

テンプレート.docx

テンプレート.docx

出力.docx

ここに画像の説明を入力

desired_output.docx

ここに画像の説明を入力

編集

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")
4

0 に答える 0