1

How does one add a hyperlink using officeR? In the ReporteRs package there was a POT with a hyperlink parameter; but I dont see anything remotely close in the OfficeR package.

3 Answers3

2

Have you found a solution for your problem? I wrote a function to add the hyperlink to the document. However, you have to create a the style of the Hyperlink in a template docx file

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)
}

There might be a nicer solution, but it worked for me.

happ
  • 100
  • 10
0

@happ has a great solution for Word documents (which is probably the source of the question), but I thought it was worth noting that there is a function to add a hyperlink to a PowerPoint file.

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"
Paul
  • 105
  • 2
  • 10
0

I was able to add a hyperlink in a docx using the following code (see 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"))

Emmanuel Hamel
  • 1,769
  • 7
  • 19