I am trying to create a Word document that is a mixture of inserting converted markdown strings and images. The file generates, however the markdown elements are included at the very end of the document, after the pictures. The best work around for converting markdown is included below (I’m also open to changing this). Here’s my code:
import os
import pypandoc
from docx import Document
doc = Document()
def add_md(txt):
TMP_FILE = 'tmp.docx'
if os.path.exists(TMP_FILE):
os.remove(TMP_FILE)
pypandoc.convert_text(txt, 'docx', 'md', outputfile=TMP_FILE)
tmp_doc = Document(TMP_FILE)
os.remove(TMP_FILE)
for element in tmp_doc.element.body:
doc.element.body.append(element)
add_md('### first')
add_md('### second')
doc.add_picture('./family.jpg')
doc.save('sample.docx')
I would expect the output to be:
- first header
- second header
- photo
However the order is:
- photo
- first header
- second header
I know one work around would be to manually create the xml
for the image and insert it, however I’d like to be able to continue to use the high level docx
functions and still be able to insert md in this manner. Can I have my cake and eat it too?