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 轉(zhuǎn)換為圖像
images = convert_from_path(pdf_path)
# 創(chuàng)建一個(gè) Word 文檔
document = Document()
# 設(shè)置頁面的頁邊距為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英寸的邊距
# 設(shè)置縮放因子
SCALING_FACTOR = 0.9 # 可根據(jù)需要調(diào)整縮放因子
# 遍歷圖像并插入到 Word 文檔中
for i, img in enumerate(images):
print(f'正在處理第 {i + 1} 頁圖像...')
# 保存圖像到臨時(shí)文件
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
# 計(jì)算插入圖片的寬度和高度,以確保圖片適應(yīng)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
# 添加一個(gè)段落來居中圖片
paragraph = document.add_paragraph()
run = paragraph.add_run()
run.add_picture(temp_img_path, width=Inches(img_width_inch), height=Inches(img_height_inch))
# 設(shè)置段落對(duì)齊方式為居中
paragraph.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
# 如果當(dāng)前不是最后一頁,添加分頁符
if i < len(images) - 1:
document.add_page_break() # 添加分頁符
# 刪除臨時(shí)圖像文件
os.remove(temp_img_path)
# 保存 Word 文檔
print('正在創(chuàng)建文檔...')
document.save(output_docx_path)
print(f"轉(zhuǎn)換完成,輸出文件為: {output_docx_path}")
image.png