DeCODE logo
Generating of DOCX from Markdown header image

How to generate DOCX from Markdown

Markdown is a format, which is usually used for communication and providing documentation for developers and technical products. Markdown supports a lot of necessary features, which help with organizing your documentation. Yet, for sharing the documents, usually used DOCX standard, which can be edited via specialized software, despite markdown can be edited in any text editor. For converting documents, we can use pandoc utility, which can achieve exactly desired behavior by converting from one format to another. Pandoc can be extended by Lua filters and tweaked per our needs.

local cacheLinks = {} -- Stores the found local links in the repository

function file_exists(name)
   if f~=nil then io.close(f) return true else return false end

function Link (link, target, title, attr)
  local linkTarget = -- where the link points to
  if file_exists(linkTarget) then
    print("Found the link: " .. linkTarget)
    table.insert(cacheLinks, linkTarget)
    return {}, {}, {}, {} -- return empty table, which will remove Link from the flow of the document
  return link

function Pandoc(blocks, meta)
  local paragraphs = {}
  for i = 1, #cacheLinks do -- iterate over the local links table
    local fh =[i]) -- read the contents of that linked file
    local contents = -- parse it with pandoc with markdown parser
      fh:read '*a',
    blocks.blocks:extend(contents) -- append parsed data to the end of the document
  return blocks, meta

Then, inside your pipeline, you should call the following:

pandoc --lua-filter fix-links-multiple-files.lua -o output.docx -f markdown -t docx --toc

Photo by Kindel Media: