【问题标题】:Cannot add image from docx file to html file using pypandoc无法使用 pypandoc 将图像从 docx 文件添加到 html 文件
【发布时间】:2021-11-30 18:43:09
【问题描述】:

我正在尝试使用 python 中的 pypandoc 包将 docx 文件转换为 html 文件。这是我的代码(删除了文件路径)-

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)

它不会插入 docx 文件中存在的图像,并且文本的颜色全部更改为黑白。我应该怎么做才能将所有图像放在 html 文件中并保持所有文本格式不变?

【问题讨论】:

    标签: html python-3.x docx pypandoc


    【解决方案1】:

    也许你可以试试 docx2html。代码如下:

    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)
    

    【讨论】:

    • docx2html 在 python 3 上存在安装问题。任何其他解决方案都同样有帮助。
    【解决方案2】:

    也许你可以试试下面这个组件。

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-04-10
      • 2018-04-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-18
      • 1970-01-01
      • 2015-03-01
      相关资源
      最近更新 更多