pandoc - 用 Word docx 的自定义样式替换标题

Pat*_*nne 6 python pandoc

我正在使用panfrude为 pandoc 编写一个 python 过滤器,以将 Markdown 转换为 Word 文档。通常,pandoc 将 Markdown 标题转换为 Word 的内置样式,称为标题 1、标题 2 等。但是由于我必须使用的 Word 模板的特殊性,我需要将所有 Markdown 标题更改为 Word 中相应的自定义样式,例如标头级别 1 => 标头 1,级别 2 => 标头 2,等等。

这是我为测试过滤器而制作的快速示例 Markdown 文件:

# Heading 1

some text in a paragraph

## Heading 2

a little bit more text down below
Run Code Online (Sandbox Code Playgroud)

本质上,我想转换该 Markdown,就像我写的那样:

<div custom-style="Header1">Heading 1</div>

some text in a paragraph

<div custom-style="Header2">Heading 2</div>

a little bit more text down below
Run Code Online (Sandbox Code Playgroud)

这样,当我跑步时:

pandoc -S test_input.md -o test_output.docx --reference-docx ./custom_styles.docx --filter ./test_filter.py
Run Code Online (Sandbox Code Playgroud)

生成的 Word docx 将使用适当的自定义样式。

跟随?

不管怎样,这是我用 panfute 编写的过滤器:

#! /usr/bin/env python
#coding: utf-8

from panflute import *

def action( elem, doc ):
    if isinstance( elem, Header ):
        return Div( elem, classes=['Header{}'.format(elem.level)] )

def main(doc=None):
    return run_filter( action, doc=doc )

if __name__ == "__main__":
    main()
Run Code Online (Sandbox Code Playgroud)

不幸的是,它并没有用我的自定义 div 来替换 Markdown 标题以进行样式设置。它基本上从另一端出来,就好像根本没有过滤器一样。

我不确定我在这里做错了什么。

Pat*_*nne 7

啊哈!最后我自己想出来了。

from panflute import *

def action( elem, doc ):
    if isinstance( elem, Header ):
        #return Div( elem, attributes={'custom-style': 'Header{}'.format(elem.level)} )
        return Div( Para(*elem.content), attributes={'custom-style': 'Header {}'.format(elem.level)} )

def main(doc=None):
    return run_filter( action, doc=doc )

if __name__ == "__main__":
    main()
Run Code Online (Sandbox Code Playgroud)