python实现pdf转换为word文档,尽量保持格式不变

from pdf2docx import Converter

def convert_pdf_to_word(pdf_path, docx_path, font_path):
    # 创建 pdf2docx.Converter 对象,用于进行 PDF 到 Word 文档的转换操作。
    cv = Converter(pdf_path)
    # 设置系统默认字体文件的路径
    cv.font_path = font_path
    #  docx_path  转换后的文档路径   start end 用于指定转换的页面范围  为None 则转换整个pdf文件
    cv.convert(docx_path, start=0, end=None)
    # 关闭转换器
    cv.close()


# pdf文件名
pdf_file = "2023_PDF.pdf"
# word文件名
word_file = "output.docx"
default_font = r"C:\Windows\Fonts\Candarai.ttf"  # 替换为系统默认字体文件的路径

convert_pdf_to_word(pdf_file, word_file, default_font)

上述方法适用于 一般的pdf转换。像简历之类的pdf转换会报字体错误。

查看系统所有字体路径

import matplotlib.font_manager as fm

# 获取系统中可用的字体列表
font_list = fm.findSystemFonts()

# 打印字体列表
for font_path in font_list:
    print(font_path)

查看指定字体路径

import os
from ctypes import windll, create_unicode_buffer


def find_arial_font_path():
    # 获取 Arial 字体文件的完整路径
    font_name = "Calibri"
    buffer_size = 1024
    font_buffer = create_unicode_buffer(buffer_size)

    # 获取 Windows 系统目录路径
    result = windll.kernel32.GetSystemWindowsDirectoryW(font_buffer, buffer_size)
    if result == 0:
        return None

    windows_directory = font_buffer.value
    font_file = os.path.join(windows_directory, "Fonts", font_name + ".ttf")

    if os.path.isfile(font_file):
        return font_file
    else:
        return None


# 查找 Calibri 字体的路径
arial_font_path = find_arial_font_path()
print(arial_font_path)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

吞掉星星的鲸鱼

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值