Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mutliple formatted text on pptx by using officer package on R

Ciao,

I'm writing a code to generate an automatic report using officer package. I was wondering how and if I can write some text with different font. In my case I'd like to write some normal text and some bold words.

Let me show you what I get. I use these functions to generate fp_text objects:

fp_normal <- function(){
return( fp_text(color = "black", font.size = 16,
        bold = FALSE, italic = FALSE,
        underlined = FALSE, font.family = "Arial", 
        shading.color = "transparent") )
}


fp_bold <- function(){
return( fp_text(color = "black", font.size = 16,
        bold = TRUE, italic = FALSE,
        underlined = FALSE, font.family = "Arial", 
        shading.color = "transparent") )
}

I used to use combination of pot function by using sum operator and function textProperties:

pot("not bold ") + pot("and bold", textProperties(font.weight = "bold") )

My question is: how should I combine fp_normal and fp_bold functions with ph_with_text function?

like image 231
clarkmaio Avatar asked Jan 31 '19 16:01

clarkmaio


2 Answers

I have updated the package to make that kind of operation easier. Usage of id_chr is not easy and the code below give the advantage to not use it :)

library(magrittr)
library(officer)

fp_normal <- fp_text(font.size = 24)
fp_bold <- update(fp_normal, bold = TRUE)
fp_red <- update(fp_normal, color = "red")

pars <- block_list(
  fpar(ftext("not bold ", fp_normal), ftext("and bold", fp_bold)),
  fpar(ftext("red text", fp_red))
)
my_pres <- read_pptx() %>%
  add_slide(layout = "Title and Content", master = "Office Theme") %>%
  ph_with(pars, location = ph_location_type(type = "body") ) 

print(my_pres, target = "test.pptx")

result

like image 74
David Gohel Avatar answered Oct 19 '22 18:10

David Gohel


Ok, at the end I think I've got it.

To apply different styles is in enough to combine ph_with_text function with ph_add_text function.

Namely ph_add_text do the same sum operator do for pot function. Keep in mind that, in order to refer to a certain line you have to provide id_chr argument. You can deduce the correct value by using slide_summary(ppt) command just after you run ph_with_text.

ppt <- read_pptx()
ppt <- add_slide(ppt, "Title and Content", master = "Office Theme")
ppt <- ph_with_text(ppt, "Some NOT bold text ", type = "body", index = 1)

slide_summary(ppt) # I see that the id is 2. Now I can delete this line.

ppt <- ph_add_text(ppt, "and some bold text", type = "body", style = fp_bold(), id_chr = 2)
print(ppt, target = "boldTest.pptx")

For the fp_bold() function see above in the question. Ad this point we can add other pieces of text with different formats by keeping using ph_add_text (and maybe "\n" if we want write in new lines.

Ciao

like image 30
clarkmaio Avatar answered Oct 19 '22 18:10

clarkmaio