代码功能概述
这段 Python 代码定义了一个名为 pdf_to_word
的函数,其主要功能是将 PDF 文件转换为 Word 文件。它支持转换整个 PDF 文件,也可以根据指定的页码范围进行转换。函数会对输入的参数进行检查,确保 PDF 文件存在且路径为字符串类型,转换完成后会返回包含转换结果信息(如文件大小、转换耗时、错误码和错误信息等)的字典。
if __name__ == "__main__":
pdf_path = "example.pdf"
result = pdf_to_word(pdf_path)
print(result)
import os
import time
import logging
from pdf2docx import Converter
# 配置日志记录
logging.basicConfig(level=logging.ERROR, format='%(asctime)s - %(levelname)s - %(message)s')
def get_file_info(pdf_path):
"""
提取PDF文件的目录和文件名(不含扩展名)
:param pdf_path: PDF文件路径
:return: 文件目录和文件名(不含扩展名)
"""
file_dir = os.path.dirname(pdf_path)
file_name = os.path.splitext(os.path.basename(pdf_path))[0]
return file_dir, file_name
def validate_page_nums(page_nums):
"""
验证页码参数的有效性
:param page_nums: 页码参数,如 '1,3-5'
:return: 有效的页码列表,如果无效则返回 None
"""
try:
pages = []
for part in page_nums.split(','):
if '-' in part:
start, end = map(int, part.split('-'))
if start <= 0 or end < start:
return None
pages.extend(range(start - 1, end))
else:
page = int(part)
if page <= 0:
return None
pages.append(page - 1)
return pages
except ValueError:
return None
def pdf_to_word(pdf_path, word_path=None, page_nums=None):
"""
@方法名称: pdf转word
@中文注释: pdf转word
@入参:
@param pdf_path str pdf文件路径
@param page_nums str 页码序号
@出参:
@返回状态:
@return 0 失败或异常
@return 1 成功
@返回错误码
@返回错误信息
@param doc_file str word文件名
@使用范例: pdf_to_word('test.pdf')
"""
result_dict = {
"status": 0,
"error_code": "",
"error_msg": "",
"file_size_mb": 0,
"recognize_time": 0,
"filename": ""
}
try:
if not isinstance(pdf_path, str):
result_dict["error_code"] = "111111"
result_dict["error_msg"] = "pdf文件路径参数类型错误,不为字符串"
return result_dict
if not os.path.isfile(pdf_path):
result_dict["error_code"] = "999999"
result_dict["error_msg"] = f"PDF文件未找到: {pdf_path}"
return result_dict
start_time = time.time()
if not word_path:
file_dir, file_name = get_file_info(pdf_path)
word_path = os.path.join(file_dir, f'{file_name}.docx')
if page_nums:
pages = validate_page_nums(page_nums)
if pages is None:
result_dict["error_code"] = "222222"
result_dict["error_msg"] = "页码参数格式错误"
return result_dict
else:
pages = None
with Converter(pdf_path) as cv:
if pages:
cv.convert(docx_filename=word_path, pages=pages)
else:
cv.convert(docx_filename=word_path, start=0)
file_size = os.path.getsize(word_path)
file_size_mb = round(file_size / (1024 * 1024), 2)
result_dict["file_size_mb"] = file_size_mb
end_time = time.time()
recognize_time = (end_time - start_time) * 1000
recognize_time = round(recognize_time, 2)
result_dict["recognize_time"] = recognize_time
result_dict["error_code"] = "000000"
result_dict["error_msg"] = "pdf转word成功"
result_dict["filename"] = os.path.basename(word_path)
result_dict["status"] = 1
return result_dict
except Exception as e:
logging.error(f"pdf转word异常: {e}")
result_dict["error_code"] = "999999"
result_dict["error_msg"] = "PDF到Word转换过程中发生错误," + str(e)
return result_dict
测试代码示例
if __name__ == "__main__":
pdf_path = "example.pdf"
result = pdf_to_word(pdf_path)
print(result)