代码之家  ›  专栏  ›  技术社区  ›  stefan

在flextable中设置公式的字体系列和大小

  •  2
  • stefan  · 技术社区  · 4 年前

    我正在寻找一个选项来设置公式的字体系列和大小 flextable

    通常,可以通过sugar函数设置表、行和列的字体系列和大小 flextable::font flextable::fontsize 然而,无论是在HTML输出中,还是在导出到docx时,两者都不会对公式的字体族和大小产生影响。

    运行下面的reprex可以为 文本 列,但不适用于 公式

    library(flextable)
    
    # Note: Running the reprex requires the `equatags` package. 
    # Also equatags::mathjax_install() must be executed
    # to install necessary dependencies. See ?flextable::as_equation.
    
    eqs <- c(
      "(ax^2 + bx + c = 0)",
      "a \\ne 0",
      "x = {-b \\pm \\sqrt{b^2-4ac} \\over 2a}"
    )
    text = LETTERS[1:3]
    df <- data.frame(text = text, formula = eqs)
    df
    #>   text                                 formula
    #> 1    A                     (ax^2 + bx + c = 0)
    #> 2    B                                a \\ne 0
    #> 3    C x = {-b \\pm \\sqrt{b^2-4ac} \\over 2a}
    
    ft <- flextable(df)
    ft <- compose(
      x = ft, j = "formula",
      value = as_paragraph(as_equation(formula, width = 2))
    )
    ft <- width(ft, j = 2, width = 2)
    ft <- fontsize(ft, size = 20, part = "all")
    
    fn <- tempfile(fileext = ".docx")
    save_as_docx(ft, path = fn)
    if (FALSE) fs::file_show(fn) # Set to TRUE to show file
    
    0 回复  |  直到 4 年前
        1
  •  3
  •   Allan Cameron    4 年前

    要控制行高度,需要指定 hrule(ft, i = 1:3, rule = 'atleast') 以及通过 height_all

    ft <- flextable(df)
    ft <- compose(
      x = ft, j = "formula",
      value = as_paragraph(as_equation(formula, width = 3, height = 2))
    )
    ft <- width(ft, j = 1:2, width = 2)
    ft <- hrule(ft, i = 1:3, rule = 'atleast')
    ft <- height_all(ft, height = 1)
    ft <- fontsize(ft, size = 20, part = "all")
    

    不幸的是,这并没有改变方程的大小:

    enter image description here

    组成第二列的mathjax公式(包括文本字符)被呈现为SVG路径,它们的大小和字体家族都是固定的。

    如果你深入研究flextable代码,当你这样做的时候,你会发现

    1. print(ft) 它调用
    2. flextable:::print.flextable 哪个调用
    3. htmltools_value(ft) ,它调用
    4. flextable:::html_str(ft) ,它调用
    5. flextable:::html_gen(ft) ,生成实际的html。

    公式字符串直接在内部传递 html_gen equatags::transform_mathjax ,它不接受任何大小或字体家族参数,只输出默认的mathjax-svg。svg图像以固定大小合并到表格单元格中。

    为了改变svg的大小,你需要参与svg黑客攻击,在简单缩放的情况下,这并不太困难:

    html_format <- as.character(htmltools_value(ft))
    html_format <- gsub('<svg ',
                        '<svg transform=\"scale(2)\" ',
                        html_format, fixed = TRUE)
    

    这个 html_format 对象只是flextable的html字符串,可以进行渲染 像这样:

    dir <- tempfile()
    dir.create(dir)
    htmlFile <- file.path(dir, "index.html")
    writeLines(html_format, con = htmlFile)
    rstudioapi::viewer(htmlFile)
    

    导致

    enter image description here

    当然,这些都不是理想的,但这只是flextable通过等式渲染公式的一个限制。

    不幸的是,Mathjax does not allow for arbitrary fonts to be used ,所以这将更加难以实现。

    推荐文章