使用Pandoc转换Markdown为PDF:部分图片去标题并居中
解决方案:让部分无标题图片居中且不生成Figure标题
针对你的需求,之前的Lua过滤器无效主要是因为属性判断错误和LaTeX包裹方式不对。以下是可行的修正方案:
1. 修正Lua过滤器
替换原来的center.lua为以下代码,它会正确识别.center类,并直接生成LaTeX居中代码,同时避免生成Figure标题:
if FORMAT:match 'latex' then function Image(elem) -- 检查图片是否包含center类 local is_center = false for _, cls in ipairs(elem.classes) do if cls == "center" then is_center = true break end end if is_center then -- 提取宽度属性,默认使用文本宽度 local width = elem.attributes.width or "textwidth" -- 生成LaTeX居中块代码 local latex_code = string.format( '\\begin{center}\n\\includegraphics[%s]{%s}\n\\end{center}', width, elem.src ) -- 返回RawBlock,绕过Pandoc默认的图片处理逻辑 return pandoc.RawBlock('latex', latex_code) end end end
关键改进点:
- 使用
elem.classes(数组)替代旧的elem.className,这是Pandoc 3.x中Image元素存储类的正确方式。 - 直接生成完整的LaTeX居中环境,确保图片被正确居中,同时完全绕过Pandoc的
implicit_figures逻辑,不会生成Figure标题。 - 自动提取你设置的
width属性,保持图片尺寸控制。
2. Markdown图片写法
保持你原来的写法即可,确保图片是单独的块级元素(前后有空行):
{ .center width=200px }
3. 执行转换命令
和之前的命令一致:
pandoc --lua-filter=center.lua <myfile>.md -o <myfile>.pdf
备选方案:结合fig:false属性
如果你希望保留Pandoc部分默认图片处理逻辑,可以在图片属性中添加fig:false,告诉Pandoc不要将其转换为Figure环境,再用过滤器处理居中:
Markdown写法:
{ .center width=200px fig:false }
对应的Lua过滤器:
if FORMAT:match 'latex' then function Image(elem) local is_center = false for _, cls in ipairs(elem.classes) do if cls == "center" then is_center = true break end end if is_center then -- 包裹居中命令 return { pandoc.RawBlock('latex', '\\begin{center}'), elem, pandoc.RawBlock('latex', '\\end{center}') } end end end
这个方案中,fig:false会阻止Pandoc生成Figure标题,过滤器只负责添加居中环境,适合需要保留Pandoc其他图片属性处理(比如默认尺寸)的场景。
内容的提问来源于stack exchange,提问作者nacaru
相关产品推荐
相关产品推荐

