如何在Pandoc将.md转PDF时给图片添加换行并解决LaTeX报错
问题:Pandoc Lua过滤器处理图片后生成PDF报错
问题背景
- 我的.md文件中,部分图片后带有换行(LineBreak/SoftBreak),示例:
 *Figure: Premises tab* - 另一部分图片后无换行,示例:
 - 尝试使用Lua脚本给每张图片添加换行,脚本代码如下:
function Image (img) -- remove leading slash from image paths img.src = img.src:gsub('^/', '') -- find the index and values for the size definition and apply them to the image idx, _, width, height = string.find(img.src, "%%20=([%d]*)x([%d]*)") if (idx ~= nil) then img.src = string.sub(img.src, 1, idx - 1) end return { pandoc.RawInline('latex', '\\hfill\\break{\\centering'), img, pandoc.RawInline('latex', '\\par}') } end - 运行以下Pandoc命令生成PDF时出现错误:
报错信息:pandoc test.md -V geometry:margin=1in -H header.tex -o PDFs\test.pdf --lua-filter pdf-filters.lua --pdf-engine=xelatex -V fontsize=9pt -V colorlinks=true -V linkcolor=blueError producing PDF. ! LaTeX Error: There's no line here to end. See the LaTeX manual or LaTeX Companion for explanation. Type H <return> for immediate help. ... l.243 \emph
错误原因
\\break命令要求当前存在已输入的文本行才能生效,若图片处于段落开头或之前无内容,就会触发"There's no line here to end"错误。同时原脚本的LaTeX代码结构不规范,\\centering的包裹方式存在语法问题。
解决方案:修改Lua过滤器
function Image (img) -- 移除图片路径开头的斜杠 img.src = img.src:gsub('^/', '') -- 提取并移除尺寸参数,同时设置图片属性(可选) local idx, _, width, height = string.find(img.src, "%%20=([%d]*)x([%d]*)") if idx then img.src = string.sub(img.src, 1, idx - 1) -- 将提取的尺寸设置为图片属性,保留原显示大小 if width ~= "" then img.attributes.width = width .. "px" end if height ~= "" then img.attributes.height = height .. "px" end end -- 返回独立的居中段落,自动实现前后换行 return pandoc.Para{ pandoc.RawInline('latex', '\\begin{center}'), img, pandoc.RawInline('latex', '\\end{center}\\par') } end
关键修改说明
- 用LaTeX标准的
center环境替代原有的\\centering写法,语法更规范,避免嵌套错误。 - 用
\\par强制结束段落实现换行效果,替代容易触发错误的\\break。 - 将图片包装为
pandoc.Para(段落元素),确保图片作为独立区块存在,自动在前后生成换行。 - 保留原脚本的路径处理逻辑,同时将提取的尺寸参数转换为图片属性,维持原图片显示大小。
内容的提问来源于stack exchange,提问作者H_H
相关产品推荐
相关产品推荐

