Cannot add image from docx file to html file using pypandoc

380 Views Asked by At

I am trying to convert a docx file to html file using pypandoc package in python. Here's my code(removed the file paths) -

import pypandoc
filename = <filepath>
output=pypandoc.convert(filename,to='html',extra_args=['--extract-media=<foldername>'])
filename=os.path.splitext(filename)[0]
filename="{0}.html".format(filename)
with open(filename,'w') as f:
  if type(output) is not str: 
     output=output.encode("utf-8")
  f.write(output)

It doesn't insert the images present in the docx file, and colour of the texts are all changed to black and white. What should I do to place all images in the html file and keep all text formatting intact?

2

There are 2 best solutions below

1
On

Maybe you could try docx2html. Code as follows:

import os.path
from shutil import copyfile

from docx2html import convert

def handle_image(image_id, relationship_dict):
    image_path = relationship_dict[image_id]
    # Now do something to the image. Let's move it somewhere.
    _, filename = os.path.split(image_path)
    destination_path = os.path.join('/tmp', filename)
    copyfile(image_path, destination_path)

    # Return the `src` attribute to be used in the img tag
    return 'file://%s' % destination

html = convert('path/to/docx/file', image_handler=handle_image)
0
On

Maybe you could try this component as below.

pip install mammoth
import mammoth

with open("document.docx", "rb") as docx_file:
    result = mammoth.convert_to_html(docx_file)
    html = result.value # The generated HTML
    messages = result.messages # Any messages, such as warnings during conversion