通过使用R

时间:2019-01-31 16:50:36

标签: r powerpoint reporters officer

Ciao

我正在编写代码,以使用Officer软件包生成自动报告。我想知道如何以及是否可以用不同的字体写一些文本。就我而言,我想写一些普通的文字和一些粗体字。

让我告诉你什么。我使用以下函数来生成fp_text对象:

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

我曾经通过使用sum运算符和函数 textProperties 来结合使用 pot 函数:

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

我的问题是:如何将 fp_normal fp_bold 函数与 ph_with_text 函数结合在一起?

2 个答案:

答案 0 :(得分:2)

好的,最后我想我明白了。

要应用不同的样式,就足以将 ph_with_text 函数与 ph_add_text 函数结合起来。

ph_add_text pot 函数执行相同的求和运算符。请记住,要引用某行,您必须提供 id_chr 参数。您可以在运行 ph_with_text 之后立即使用 slide_summary(ppt)命令来推断正确的值。

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

有关 fp_bold()函数的信息,请参阅上面的问题。 至此,我们可以继续使用 ph_add_text 添加其他不同格式的文本(如果想用新行写,也可以添加“ \ n”。

Ciao

答案 1 :(得分:2)

我已经更新了软件包,以使这种操作更加容易。使用id_chr并不容易,下面的代码具有不使用它的优势:)

library(magrittr)
library(officer)

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

pars <- block_list(
  fpar(ftext("not bold ", fp_normal), ftext("and bold", fp_bold)),
  fpar(ftext("red bold text", fp_redbold))
)
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