Nikola Milic
Nikola Milic

Reputation: 21

Markdown to docx conversion using pypandoc

I have a problem with converting my markdown file to docx file using pypandoc. When I try to convert the file using command:

pypandoc.convert_file('container.md', to='docx', outputfile='result.docx'),

I get a file with no pictures and a message: [WARNING] Could not fetch resource image.png: PandocResourceNotFound "image.png". Second part of my problem is the fact that the tables' borders are not visible at all.

When I convert the same file to pdf, I get no issues. Thanks for the help.

Upvotes: 2

Views: 2696

Answers (1)

Brian
Brian

Reputation: 13593

For the second part of your problem, I've found the following solution.

  1. Run pip install python-docx to install the necessary python module.

  2. Add the following code to your code.

from docx import Document
from docx.oxml.ns import nsdecls
from docx.oxml import parse_xml


# Your original code ...

docx_file_path = 'result.docx'
doc = Document(docx_file_path)

# Go through each table in the document
for table in doc.tables:
    for row in table.rows:
        for cell in row.cells:
            # This xml is for a basic thin border on all sides of a cell
            cell_borders = parse_xml(r'<w:tcBorders xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">'
                                    r'<w:top w:val="single" w:sz="4" w:space="0" w:color="auto"/>'
                                    r'<w:left w:val="single" w:sz="4" w:space="0" w:color="auto"/>'
                                    r'<w:bottom w:val="single" w:sz="4" w:space="0" w:color="auto"/>'
                                    r'<w:right w:val="single" w:sz="4" w:space="0" w:color="auto"/>'
                                    r'</w:tcBorders>')
            # Add these borders to each cell
            cell._tc.get_or_add_tcPr().append(cell_borders)

# Save the document
doc.save(docx_file_path)

The code above adds borders to all the tables in result.docx file.

Upvotes: 0

Related Questions