Pandoc:Markdown转LaTeX时保留图片居中与尺寸设置
问题
我有如下mwe.md Markdown文件:
### Short version for testing <div style="text-align: center;"> <img src="myimage.jpeg" style="width: 200px; height: auto;" title="myimage.jpeg"/> </div>
执行pandoc mwe.md -o mwe.html转成HTML后,再用pandoc mwe.html -o mwe.tex转LaTeX,得到的结果是:
\subsubsection{Short version for testing}\label{short-version-for-testing} \includegraphics{myimage.jpeg}
想要得到的目标LaTeX内容为:
\subsubsection{Short version for testing}\label{short-version-for-testing} \begin{center} \includegraphics[width=200]{myimage.jpeg} \end{center}
另外还有一个问题:把mwe.html转PDF时,图片虽居中但尺寸过大。请问该怎么操作?是否需要编写filter实现?
解决方案
方法1:改用原生Markdown语法(最简便)
放弃在Markdown里写HTML,用pandoc支持的原生语法实现居中+指定尺寸,转换时能直接保留格式:
### Short version for testing ::: center {width=200} :::
或者用HTML风格的居中标签(pandoc同样支持):
### Short version for testing <center> {width=200px} </center>
直接执行pandoc mwe.md -o mwe.tex就能生成目标LaTeX代码,转PDF时图片尺寸也会符合设置,不会过大。
方法2:编写Lua Filter处理现有HTML
如果必须保留原HTML结构,需要写一个Lua Filter来提取样式信息并转换为LaTeX格式:
- 创建
image-style-filter.lua文件,内容如下:
-- 处理居中的div容器 function Div(el) if el.attributes.style and string.find(el.attributes.style, "text-align: center") then return pandoc.RawBlock("latex", "\\begin{center}") .. el.content .. pandoc.RawBlock("latex", "\\end{center}") end end -- 提取图片的宽度样式 function Image(el) if el.attributes.style then local width_val = string.match(el.attributes.style, "width: (%d+)px") if width_val then el.attributes.width = width_val el.attributes.style = nil end end return el end
- 执行转换命令时加载这个filter:
转LaTeX:
pandoc mwe.html --lua-filter=image-style-filter.lua -o mwe.tex
转PDF:
pandoc mwe.html --lua-filter=image-style-filter.lua -o mwe.pdf
这样就能同时实现图片居中、指定宽度,解决PDF中图片过大的问题。
内容的提问来源于stack exchange,提问作者Ulrich
相关产品推荐
相关产品推荐

