Word 转 PDF
是什么:将 Microsoft Word 文档转换为 PDF 格式。
为什么:PDF 具有更好的跨平台兼容性、固定布局和安全性。
Python 示例
方法一:使用 python-docx 和 reportlab(纯文本转换)
python
from docx import Document
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import letter
def docx_to_txt_pdf(docx_path, pdf_path):
"""将 Word 文档文本内容转换为 PDF"""
doc = Document(docx_path)
pdf = canvas.Canvas(pdf_path, pagesize=letter)
y = 750 # 起始Y坐标
line_height = 14
for paragraph in doc.paragraphs:
if y < 50: # 换页
pdf.showPage()
y = 750
pdf.drawString(50, y, paragraph.text)
y -= line_height
pdf.save()
# 使用示例
docx_to_txt_pdf("document.docx", "output.pdf")
方法二:使用 comtypes(Windows,需要安装 Word)
python
import comtypes.client
def docx_to_pdf_windows(docx_path, pdf_path):
"""使用 Word 应用程序进行转换(Windows)"""
word = comtypes.client.CreateObject('Word.Application')
word.Visible = False
try:
doc = word.Documents.Open(docx_path)
doc.SaveAs(pdf_path, FileFormat=17) # 17 = PDF 格式
doc.Close()
finally:
word.Quit()
# 使用示例
docx_to_pdf_windows(r"C:\path\to\document.docx", r"C:\path\to\output.pdf")
方法三:使用 libreoffice(跨平台)
python
import subprocess
import os
def docx_to_pdf_libreoffice(docx_path, pdf_path):
"""使用 LibreOffice 进行转换"""
cmd = [
'libreoffice', '--headless', '--convert-to', 'pdf',
'--outdir', os.path.dirname(pdf_path),
docx_path
]
subprocess.run(cmd, check=True)
# 使用示例
docx_to_pdf_libreoffice("document.docx", "output.pdf")
推荐方案
安装依赖
bash
# 方法一:纯文本转换 pip install python-docx reportlab # 方法二:Windows Office 转换 pip install comtypes # 方法三:LibreOffice 转换 # 需要安装 LibreOffice 软件
完整示例(推荐 LibreOffice)
python
import subprocess
import sys
def convert_word_to_pdf(input_file, output_file=None):
"""
将 Word 文档转换为 PDF
Args:
input_file: 输入的 .docx 或 .doc 文件路径
output_file: 输出的 .pdf 文件路径(可选)
"""
if output_file is None:
output_file = input_file.replace('.docx', '.pdf').replace('.doc', '.pdf')
try:
# 使用 LibreOffice 转换
cmd = ['libreoffice', '--headless', '--convert-to', 'pdf', input_file]
result = subprocess.run(cmd, capture_output=True, text=True, check=True)
print(f"转换成功: {input_file} -> {output_file}")
return True
except subprocess.CalledProcessError as e:
print(f"转换失败: {e}")
return False
except FileNotFoundError:
print("请先安装 LibreOffice")
return False
# 使用示例
convert_word_to_pdf("报告.docx", "报告.pdf")
各方案对比
| 方法 | 优点 | 缺点 | 适用场景 |
|---|---|---|---|
| ReportLab | 纯 Python,跨平台 | 只转换文本,丢失格式 | 简单文档 |
| Word COM | 完美保持格式 | 仅 Windows,需要安装 Office | Windows 服务器 |
| LibreOffice | 跨平台,格式保持好 | 需要安装软件 | 生产环境推荐 |
一句话总结:Word 转 PDF 推荐使用 LibreOffice 命令行工具,跨平台且能完美保持格式,适合生产环境使用。