目录
安装库:pip install spire.doc -i https://pypi.tuna.tsinghua.edu.cn/simple
使用spire.doc库将word转图片后产生水印文字:Evaluation Warning: The document was created with Spire.Doc for Python.原因是商业库,需要购买官方许可证。这点难不倒爱创新的我!!
初步实现
以下代码输出的结果图片都带
from spire.doc import Document, ImageType, FileFormat
def word_img(docx_file_path, image_save_path):
# 加载文档
document = Document()
document.LoadFromFile(docx_file_path)
for i in range(document.GetPageCount()): # 遍历所有页
imageStream = document.SaveImageToStreams(i, ImageType.Bitmap) # 转换页面为图片流
with open(fr'{image_save_path}\{docx_file_path.split('\\')[-1].split('.')[0]}_图{i + 1}.png',
'wb') as imageFile:
imageFile.write(imageStream.ToArray())
document.Close()
解决方法
因为spire.doc库很强大,除了将word转为png图片还能转为其他格式的文件,但是都会有水印。
那么问题就是如何方便去水印了。
spire.doc 可将文档转为svg格式文件,而svg可通过html读取,那当然,我们可以通过去掉html中的水印解决问题了。
测试发现如果文档有多页时,转换后的第一页水印和其他页不一样,
第一页如下:
其他页如下:
这里不直接生成png格式的图片,而是生成svg文件,再通过读写svg文件的方法将水印部分的内容去掉,这里个人保留其水印标签,通过代码实现替换或去除,替换时可将其改为自己想要的水印内容。
word转SVG文件
def word_img(docx_file_path, image_save_path): # 将word转为SVG格式文件
document = Document()
document.LoadFromFile(docx_file_path)
document.SaveToFile(fr'{image_save_path}\{docx_file_path.split('\\')[-1].split('.')[0]}_.svg', FileFormat.SVG)
document.Close()
SVG文件取水印
有时打开SVG文件读写时不知道文件编码 会报错,提供两种读取文件编码的方法如下,将文件编码传给open() 的 encoding 参数即可。