Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Build off of {officer} #6

Open
matt-dray opened this issue Jul 10, 2023 · 0 comments
Open

Build off of {officer} #6

matt-dray opened this issue Jul 10, 2023 · 0 comments
Labels
enhancement New feature or request

Comments

@matt-dray
Copy link
Owner

matt-dray commented Jul 10, 2023

Use officer::docx_summary() to get the basics out, like the text and the doc styles. Then we can supply the appropriate markdown.

library(officer)
path <- r"{C:\Users\matt.dray\Documents\Temp\demo.docx}"
doc <- read_docx(path)
content <- docx_summary(doc)

markup_map <- c(
  "Title"     = "#",
  "heading 1" = "##",
  "heading 2" = "###",
  "heading 3" = "####"
)

content$markup <- markup_map[content$style_name]

content$govspeak <- ifelse(
  !is.na(content$markup),
  paste(content$markup, content$text),
  content$text
)

content$govspeak
# [1] "# This is the title"                                                        
# [2] "## This is a heading 1"                                                     
# [3] "This is some text. This is in bold. This is in italics. This is underlined."

But the font styles are missing from the {officer} output (unless there's a way to turn on this functionality?). So might have to dig into the unzipped docx file with e.g. wordup::wu_read(). We can then grab the styles, even if it is a bit awkward (remembering that some styles aren't accepted on GOV.UK, see #7).

body_list <- wordup::wu_read(path)
str(body_list, give.attr = FALSE, max.level = 3)

lapply(
  1:6,
  function(x) {
    list(
      text = body_list$document$body[[3]][[x]][["t"]][[1]],
      style = names(body_list$document$body[[3]][[x]][["rPr"]])[[1]]
    )
  }
)
# [[1]]
# [[1]]$text
# [1] "This is some text. "
# 
# [[1]]$style
# NULL
# 
# 
# [[2]]
# [[2]]$text
# [1] "This is in bold."
# 
# [[2]]$style
# [1] "b"
# 
# 
# [[3]]
# [[3]]$text
# [1] " "
# 
# [[3]]$style
# NULL
# 
# 
# [[4]]
# [[4]]$text
# [1] "This is in italics."
# 
# [[4]]$style
# [1] "i"
# 
# 
# [[5]]
# [[5]]$text
# [1] " "
# 
# [[5]]$style
# NULL
# 
# 
# [[6]]
# [[6]]$text
# [1] "This is underlined."
# 
# [[6]]$style
# [1] "u"

It's then a case of pasting like **This is bold**, since the text was recognised as 'b' style (italics was 'i', underlined was 'u').

@matt-dray matt-dray added the enhancement New feature or request label Jul 10, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

1 participant