EDIT: I should have just googled before responding. It seems such a filter I described below already exists: https://github.com/timofurrer/pandoc-mermaid-filter.
I haven’t done it for mermaid, but here is a method that should work.
Pandoc works by converting every document type into an intermediate AST representation, then encoding that AST again into the new format. It allows you to modify this AST by a filter before the encoding is done.
For example, take this md (removed the 3 backticks inside the md doc, because it confuses the forum:
$ cat test.md
This is a mermaid diagram
{three backticks here}mermaid
graph TD
A[CREATIVITY] --> B[Combinatorial]
A[CREATIVITY] --> C[Exploratory]
{three backticks here}
The AST is a JSON:
pandoc -t json test.md | jq
{
"blocks": [
{
"t": "Para",
"c": [
{
"t": "Str",
"c": "This"
},
{
"t": "Space"
},
{
"t": "Str",
"c": "is"
},
{
"t": "Space"
},
{
"t": "Str",
"c": "a"
},
{
"t": "Space"
},
{
"t": "Str",
"c": "mermaid"
},
{
"t": "Space"
},
{
"t": "Str",
"c": "diagram"
}
]
},
{
"t": "CodeBlock",
"c": [
[
"",
[
"mermaid"
],
[]
],
"graph TD\nA[CREATIVITY] --> B[Combinatorial]\nA[CREATIVITY] --> C[Exploratory]"
]
}
],
"pandoc-api-version": [
1,
17,
5,
1
],
"meta": {}
}
Note that there is a CodeBlock
node in the tree, with type “mermaid”.
You should be able to write a filter to run the content of the block through something like this to generate an image, then insert replace the CodeBlock
node with an image reference.
Then, when pandoc writes the latex then pdf, it’ll get included as an image.