rendering equations as images and including them in Word/PowerPoint output documents with R Markdown

蓝咒 提交于 2019-12-24 10:30:02

问题


I'm gratuitously cross posting this from the R Studio community page as this is a bit esoteric.

Is there a way to ask Knitr to render my equations from R Markdown into images and then stick the resulting images into my final document? The use case I have in mind is overcoming some of the shortcomings of MSFT Equation editor when knitting to Word/PowerPoint. If the equation was simply an image, then I could have LaTeX quality equations in my MSFT docs, which would be fabulous!

The closest thing I have found is using latex2exp and putting in an R Code chunk that produces a figure which is actually a rendered LaTeX formula. I kinda like this sort of hack, but latex2exp has some limitations.


回答1:


As mentioned in the comments, webtex is an easy solution. Pandoc's --webtex switch has no effect when targeting docx. However, a Lua filter can be used to the same effect.

local mediabag = require 'pandoc.mediabag'
local utils = require 'pandoc.utils'

local function url_encode(str)
  local encode_char = function(c)
    return ("%%%02X"):format(string.byte(c))
  end
  return str
    :gsub("\n", "\r\n")
    :gsub("([^%w%-%_%.%~])", encode_char)
end

local function webtex_url(formula)
  return 'https://latex.codecogs.com/png.latex?' .. url_encode(formula)
end

function Math(el)
  local filename = utils.sha1(el.text) .. '.png'
  local mime, contents = mediabag.fetch(webtex_url(el.text), '.')
  mediabag.insert(filename, mt, contents)
  local img = pandoc.Image({}, filename)
  return el.mathtype == 'DisplayMath'
    and {pandoc.LineBreak(), img, pandoc.LineBreak()}
    or img
end

Save this to a file and pass the file to pandoc via the --lua-filter option. It will convert all equations into png images via webtex.



来源:https://stackoverflow.com/questions/52221946/rendering-equations-as-images-and-including-them-in-word-powerpoint-output-docum

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!