word转html的python实现方案

aspose.words

使用的是aspose.words的库,相关参考:
Convert WORD To HTML - Python (aspose.com)
找了很多方案,感觉这个是转换效果最好的

docker实现

阅读官方的文档,aspose.words需要的环境比较复杂,因此考虑做成一个docker镜像实现
需要的环境:gcc6+,python3,donet/runtime
dockerfile:

FROM mcr.microsoft.com/dotnet/runtime:latest
 
RUN apt-get update && apt-get install -y build-essential
RUN apt-get update && apt-get install -y python3.9 python3.9-dev pip
ARG ENVTYPE
ENV EXCHANGE_ENV=$ENVTYPE
ENV PIP_MIRROR=http://mirrors.aliyun.com/pypi/simple/
ENV PIP_TRUST_HOST=mirrors.aliyun.com
 
ADD . /
RUN cp -f /usr/share/zoneinfo/Asia/Shanghai /etc/localtime
 
RUN pip install --upgrade pip -i $PIP_MIRROR --trusted-host $PIP_TRUST_HOST
RUN pip install pyinstaller -i $PIP_MIRROR --trusted-host $PIP_TRUST_HOST
RUN pip install \
    -i $PIP_MIRROR --trusted-host $PIP_TRUST_HOST \
    aspose-words

文件写好后执行docker命令

docker build -t words:v1 .

编写word.py处理word

import aspose.words as aw
 
lic = aw.License()
try:
    lic.set_license("/var/www/Aspose.Words.Python.NET.lic")
    print("License set successfully.")
except RuntimeError as err:
    # We do not ship any license with this example, visit the Aspose site to obtain either a temporary or permanent license.
    print("\nThere was an error setting the license: {0}".format(err))
 
doc = aw.Document("/var/www/aaa.docx")
doc.save("/var/www/Output.html")

申请的是试用lic:Aspose.Words.Python.NET.lic有效期一个月,感觉确实比libreoffice转换的效果要好很多

word转html执行

假设你的word.py和待转换的aaa.docx在/home/tmp目录
执行命令:

docker run --rm -v /home/tmp:/var/www words:v1 python3 /var/www/word.py

容器运行完毕后就会在/home/tmp目录中生成Output.html,如果文档中包含图片,会生成图片

  • --rm 表示运行后删除容器
  • -v /原目录:/目标目录 都是绝对路径,用于将执行docker环境的目录挂载到docker容器中
  • words:v1 就是指定的镜像名称及版本

图片处理

可以根据html中img的src,读取图片,然后上传到对象存储中,将本地图片路径替换为对象存储路径
到此为止,一份完整的html就搞好了
html标签内的style,如果不要,可以用一些过滤的方式将其剔除,可以在js中进行处理

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容