Pandoc转换Markdown至Word时如何统一设置字体与字号?
Great question! The reason your mainfont settings aren't working is that those parameters are designed for LaTeX/PDF output, not DOCX. Pandoc handles DOCX formatting differently—it relies on Word's built-in styles rather than LaTeX-style font variables. Let's walk through two reliable ways to set a universal font and size for your document:
Method 1: Use a Custom Reference DOCX Template (Most Intuitive & Controllable)
This is Pandoc's recommended approach for consistent DOCX formatting, as it lets you fully control every style:
- Export Pandoc's default reference template
Run this command in your terminal to generate a base Word template that matches Pandoc's default styling:pandoc -o reference.docx --print-default-data-file reference.docx - Modify the template's styles
Open the generatedreference.docxin Word 2016, then use the Styles panel (click the small arrow in the bottom-right corner of the "Styles" group under the "Home" tab):- Locate all styles used in your document: "Normal" (body text), "Heading 1" through "Heading 6", "List Paragraph", "Block Quote", etc.
- Right-click each style, select Modify, then set the font to Arial/Palatino, adjust the font size, and check "New documents based on this template" before saving the change.
- Make sure to update every style you want to standardize—Pandoc maps Markdown elements directly to these Word styles.
- Convert with your custom template
When converting your Markdown file, specify your modified template with the--reference-docflag:pandoc your-document.md -o output.docx --reference-doc=reference.docx
Method 2: Quick Fix with a Lua Filter (For Batch Adjustments)
If you want a lightweight alternative without modifying a template, you can use a simple Lua filter to enforce font settings across all text elements:
- Create a file named
set-universal-font.luawith this code:-- Apply target font to all paragraph text function Para(el) el.attributes["font-family"] = "Arial" return el end -- Apply target font to headings function Header(el) el.attributes["font-family"] = "Arial" return el end -- Add more element types (like lists, quotes) if needed - Run the conversion with the filter:
Note: This method is less comprehensive than using a template, as Word's built-in styles may override some settings. Sticking with the reference template is better for long-term consistency.pandoc your-document.md -o output.docx --lua-filter=set-universal-font.lua
Why Your Previous Attempts Failed
Just to clarify: The mainfont YAML setting and --variable mainfont command-line parameter only work when generating PDFs via LaTeX. They have no effect on DOCX output, which is why those changes didn't show up in your Word files.
内容的提问来源于stack exchange,提问作者user136555

