Word 转长图
是什么:将 Word 文档转换为单张长图片,便于分享和预览。
为什么:避免格式错乱,方便在社交媒体、移动设备查看。
Python 示例
python
import subprocess
from pdf2image import convert_from_path
from PIL import Image
import os
def word_to_long_image(docx_path, output_path="output.jpg"):
"""Word 转长图"""
# 生成临时 PDF 文件名
pdf_path = "temp.pdf"
# 1. Word 转 PDF
subprocess.run([
'libreoffice', '--headless', '--convert-to', 'pdf',
'--outdir', '.', docx_path
], capture_output=True)
# 2. PDF 转图片
images = convert_from_path(pdf_path, dpi=150)
# 3. 合并为长图
total_height = sum(img.height for img in images)
max_width = max(img.width for img in images)
long_img = Image.new('RGB', (max_width, total_height), 'white')
y = 0
for img in images:
long_img.paste(img, (0, y))
y += img.height
# 4. 保存结果
long_img.save(output_path, 'JPEG', quality=90)
os.remove(pdf_path) # 清理临时文件
print(f"转换完成: {output_path}")
# 使用示例
word_to_long_image("document.docx", "my_document.jpg")
安装依赖:
bash
pip install pdf2image pillow # 系统还需安装:LibreOffice 和 poppler-utils
一句话总结:通过 LibreOffice 将 Word 转 PDF,再用 pdf2image 拼接成长图,保持原始格式的完美转换。