使用 R Markdown 将方程渲染为图像并将它们包含在 Word/PowerPoint 输出文档中 [英] rendering equations as images and including them in Word/PowerPoint output documents with R Markdown

查看:37
本文介绍了使用 R Markdown 将方程渲染为图像并将它们包含在 Word/PowerPoint 输出文档中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无偿地交叉发布此来自 R Studio 社区页面,因为这有点深奥.

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

有没有办法让 Knitr 将我的方程从 R Markdown 渲染成图像,然后将生成的图像粘贴到我的最终文档中?我想到的用例是在编织到 Word/PowerPoint 时克服 MSFT 公式编辑器的一些缺点.如果方程只是一个图像,那么我可以在我的 MSFT 文档中包含 LaTeX 质量方程,这太棒了!

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!

我发现的最接近的是 使用 latex2exp 并放入一个 R 代码块,产生一个实际上是渲染的 LaTeX 公式的图形.我有点喜欢这种 hack,但是 latex2exp 有一些限制.

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.

推荐答案

正如评论中提到的,webtex 是一个简单的解决方案.Pandoc 的 --webtex 开关在定位 docx 时不起作用.但是,可以使用 Lua 过滤器达到相同的效果.

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

将其保存到文件中,并通过 --lua-filter 选项将文件传递给 pandoc.它将通过 webtex 将所有方程转换为 png 图像.

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.

这篇关于使用 R Markdown 将方程渲染为图像并将它们包含在 Word/PowerPoint 输出文档中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆