利用Python将PDF图片格式转WORD

from pdf2image import convert_from_path
from docx import Document
from docx.shared import Inches
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
import os

# PDF 文件路径
pdf_path = 'AAA.pdf'  # 替换为你的 PDF 文件路径
output_docx_path = 'AAA.docx'  # 输出的 Word 文件路径

# 将 PDF 转换为图像
images = convert_from_path(pdf_path)

# 创建一个 Word 文档
document = Document()

# 设置页面的页边距为0
sections = document.sections
for section in sections:
    section.left_margin = section.right_margin = section.top_margin = section.bottom_margin = Inches(0)

# A4 页面的宽高
A4_WIDTH_INCHES = 8.27
A4_HEIGHT_INCHES = 11.69

# 最大宽高限制
MAX_WIDTH = A4_WIDTH_INCHES - 0.5  # 留出0.5英寸的边距
MAX_HEIGHT = A4_HEIGHT_INCHES - 0.5  # 留出0.5英寸的边距

# 设置缩放因子
SCALING_FACTOR = 0.9  # 可根据需要调整缩放因子

# 遍历图像并插入到 Word 文档中
for i, img in enumerate(images):
    print(f'正在处理第 {i + 1} 页图像...')
    # 保存图像到临时文件
    temp_img_path = 'temp_image.png'
    img.save(temp_img_path, 'PNG')

    # 获取图像的宽高比
    img_width, img_height = img.size
    img_aspect_ratio = img_width / img_height

    # 计算插入图片的宽度和高度,以确保图片适应A4页面
    if img_aspect_ratio > 1:  # 宽图
        img_width_inch = min(MAX_WIDTH, A4_WIDTH_INCHES * SCALING_FACTOR)
        img_height_inch = img_width_inch / img_aspect_ratio
        if img_height_inch > MAX_HEIGHT:
            img_height_inch = MAX_HEIGHT
            img_width_inch = img_height_inch * img_aspect_ratio
    else:  # 竖图
        img_height_inch = min(MAX_HEIGHT, A4_HEIGHT_INCHES * SCALING_FACTOR)
        img_width_inch = img_height_inch * img_aspect_ratio
        if img_width_inch > MAX_WIDTH:
            img_width_inch = MAX_WIDTH
            img_height_inch = img_width_inch / img_aspect_ratio

    # 添加一个段落来居中图片
    paragraph = document.add_paragraph()
    run = paragraph.add_run()
    run.add_picture(temp_img_path, width=Inches(img_width_inch), height=Inches(img_height_inch))

    # 设置段落对齐方式为居中
    paragraph.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER

    # 如果当前不是最后一页,添加分页符
    if i < len(images) - 1:
        document.add_page_break()  # 添加分页符

    # 删除临时图像文件
    os.remove(temp_img_path)

# 保存 Word 文档
print('正在创建文档...')
document.save(output_docx_path)

print(f"转换完成,输出文件为: {output_docx_path}")
image.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容