6

I'm using panflute to write a python filter for pandoc to convert Markdown into a Word document. Normally, pandoc converts Markdown headers into Word's built-in styles called Heading 1, Heading 2, etc. But due to the particulars of the Word template I have to use, I instead need to change all Markdown headers into corresponding custom styles in Word such that Header level 1 => Header1, level 2 => Header2, etc.

Here's a quick sample Markdown file I made to test my filter:

# Heading 1

some text in a paragraph

## Heading 2

a little bit more text down below

Essentially, I want to convert that Markdown as if I had written it like:

<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

So that way, when I run:

pandoc -S test_input.md -o test_output.docx --reference-docx ./custom_styles.docx --filter ./test_filter.py

The resulting Word docx will use the appropriate custom styles.

Follow?

Anyway, here's the filter I've written using panflute:

#! /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()

Which, unfortunately, does not replace the Markdown headers with my custom divs for styling. It basically comes out the other end as if there was no filter in place at all.

I'm not sure what I'm doing wrong here.

Patrick Wynne
  • 1,864
  • 15
  • 20
  • I'm not familiar with panflute, maybe ask on the pandoc-discuss mailing list? – mb21 May 03 '17 at 06:40
  • Hi Patrick, I have exactly the same problem and want to solve it using `pandocfilters` r package, which should do the same... One thing I do not unterstand to get me started. Can I somehow save the `output` in a textfile to start developing my filter. So basically the input of `doc` in your script. – drmariod Nov 11 '22 at 17:10
  • Just a note that in Word jargon, there is a huge difference between headings and headers. https://addbalance.com/word/headersheadings.htm – Charles Kenyon Nov 12 '22 at 00:43

1 Answers1

7

Aha! Finally figured it out on my own.

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()
Patrick Wynne
  • 1,864
  • 15
  • 20