python实现word文档合并同时转pdf,保留原本样式

import os
from glob import glob
from docx import Document
from docxcompose.composer import Composer
from win32com import client

def merge_doc(source_file_path_list,target_file_path):
    # 填充分页符文档
    page_break_doc = Document()
    page_break_doc.add_page_break()
    # 定义新文档
    target_doc = Document(source_file_path_list[0])
    target_composer = Composer(target_doc)
    for i in range(len(source_file_path_list)):
        # 跳过第一个作为模板的文件
        if i==0:
            continue
        # 填充分页符文档
        target_composer.append(page_break_doc)
        # 拼接文档内容
        f = source_file_path_list[i]
        target_composer.append(Document(f))
    # 保存目标文档
    target_composer.save(target_file_path)

# word转pdf
def convertType(source,convert,type):
    if type == 17:
        word = client.Dispatch('kwps.Application')
    if type == 16:
        word = client.Dispatch('Word.Application')
    word.DisplayAlerts = False
    # 打开源文件
    doc = word.Documents.Open(source)
    # 将内容复制到新的文件中
    doc.SaveAs(convert, type)
    doc.Close()
    word.Quit()

if __name__ == '__main__': 
    source_path = r"F:\www\doctopdf\public"
    save_path = r'F:\www\doctopdf\target.docx'
    convert_path = r"F:\www\doctopdf\target.pdf"
    source_list = []
    files_list = glob(os.path.join(source_path, '*'))
    number_of_sections = len(files_list)
    for i in range(0, number_of_sections):
        # 文件后缀
        suffix = os.path.splitext(files_list[i])[1]
        # 文件路径 不包含后缀
        url = os.path.splitext(files_list[i])[0]
        if suffix == '.doc' or suffix == '.docx':
            if suffix == '.doc':
                # 合并后文件地址
                convert = url + ".docx"
                # 合并word
                convertType(files_list[i], convert, 16)
                os.remove(files_list[i])
                files_list[i] = convert
            source_list.append(files_list[i])
    merge_doc(source_list, save_path)
    # word转pdf
    convertType(save_path, convert_path, 17)
    print('----merge success----')
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值