Как добавить гиперссылки в Word docx с помощью officeR?

Как добавить гиперссылку с помощью officeR? В пакете ReporteRs был POT с параметром гиперссылки; но я не вижу ничего близкого удаленно в пакете OfficeR.


person Mike Carmine    schedule 30.10.2017    source источник


Ответы (3)


Вы нашли решение своей проблемы? Я написал функцию для добавления гиперссылки в документ. Однако вам необходимо создать стиль гиперссылки в файле docx шаблона.

add_hyperref = function (x, target="http://www.google.de", 
                         style = NULL, pos = "after") {

  if ( is.null(style) ) 
    style <- x$default_styles$table 
  style_id <- x$doc_obj$get_style_id(style = style, type = "character")

  refID = sprintf("rId%d",x$doc_obj$relationship()$get_next_id())

  x$doc_obj$relationship()$add( refID,
                                type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink",
                                target=target, target_mode="External")

  xml_elt = sprintf("<w:hyperlink r:id='%s' w:history='1'><w:r w:rsidRPr='00CD112F'><w:rPr><w:rStyle w:val='Hyperlink'/></w:rPr><w:t>LINK</w:t></w:r></w:hyperlink>",
                    refID)
  xml_elt = paste0(officer:::wml_with_ns("w:p"), "<w:pPr><w:pStyle w:val=\"", 
                   style_id, "\"/></w:pPr>", xml_elt, "</w:p>")

  body_add_xml(x = x, str = xml_elt, pos = pos)
}

Возможно, есть более подходящее решение, но оно сработало для меня.

person happ    schedule 07.02.2018

У @happ есть отличное решение для документов Word (что, вероятно, является источником вопроса), но я подумал, что стоит отметить, что есть функция для добавления гиперссылки в файл PowerPoint.

https://davidgohel.github.io/officer/reference/ph_hyperlink.html

fileout <- tempfile(fileext = ".pptx")
doc <- read_pptx()
doc <- add_slide(doc, layout = "Title and Content", master = "Office Theme")
doc <- ph_with_text(x = doc, type = "title", str = "Un titre 1")
slide_summary(doc) # read column ph_label here
#>    type id ph_label offx      offy cx   cy       text
#> 1 title  2  Title 1  0.5 0.3003478  9 1.25 Un titre 1
doc <- ph_hyperlink(x = doc, ph_label = "Title 1",href = "https://cran.r-project.org")

print(doc, target = fileout )#> [1] "/private/var/folders/08/2qdvv0q95wn52xy6mxgj340r0000gn/T/RtmpXIYvn5/filef90c6579a4d2.pptx"
person Paul    schedule 12.04.2019

Мне удалось добавить гиперссылку в docx, используя следующий код (см. https://rdrr.io/cran/officer/man/slip_in_text.html):

library(officer)
x <- read_docx()
x <- body_add_par(x, "Hello ", style = "Normal")
x <- slip_in_text(x, "world", style = "strong")
x <- slip_in_text(x, "Message is", style = "strong", pos = "before")
x <- slip_in_text(x, "with a link", style = "strong",
                         pos = "after", hyperlink = "https://davidgohel.github.io/officer/")

print(x, target = tempfile(fileext = ".docx"))

person Emmanuel Hamel    schedule 22.06.2021