python 合并word文件_python实现word转pdf

验证过ppt也可以合并成pdf文件,确实很高效,什么pdf转换器的再也不用了~

需要下载模块pywin32,程序中导入模块为win32com。

# -*- coding:utf-8 -*-

import os

from win32com.client import Dispatch,DispatchEx

from win32com.client import constants

from win32com.client import gencache

import re

def getfilenames(filepath=‘‘,filelist_out=[],file_ext=‘all‘):

for fpath, dirs, fs in os.walk(filepath):

for f in fs:

fi_d = os.path.join(fpath, f)

if file_ext == ‘.doc‘:

if os.path.splitext(fi_d)[1] in [‘.doc‘,‘.docx‘]:

filelist_out.append(re.sub(r‘\\‘,‘/‘,fi_d))

else:

if file_ext == ‘all‘:

filelist_out.append(fi_d)

elif os.path.splitext(fi_d)[1] == file_ext:

filelist_out.append(fi_d)

else:

pass

filelist_out.sort()

return filelist_out

# Word to PDF

def wordtopdf(filelist,targetpath):

valueList = []

try:

gencache.EnsureModule(‘{00020905-0000-0000-C000-000000000046}‘, 0, 8, 4)

# 开始转换

w = Dispatch("Word.Application")

for fullfilename in filelist:

(filepath,filename) = os.path.split(fullfilename) # 分割文件路径和文件名

softfilename = os.path.splitext(filename) # 分割文件名和扩展名

os.chdir(filepath)

doc = os.path.abspath(filename)

os.chdir(targetpath)

pdfname = softfilename[0] + ".pdf"

output = os.path.abspath(pdfname)

pdf_name = output

try:

doc = w.Documents.Open(doc, ReadOnly=1)

doc.ExportAsFixedFormat(output, constants.wdExportFormatPDF,

Item=constants.wdExportDocumentWithMarkup,

CreateBookmarks=constants.wdExportCreateHeadingBookmarks)

except Exception as e:

print(e)

if os.path.isfile(pdf_name):

valueList.append(pdf_name)

else:

print(‘转换失败!‘)

return False

w.Quit(constants.wdDoNotSaveChanges)

return valueList

except TypeError as e:

print(‘出错了!‘)

print(e)

return False

if __name__ == ‘__main__‘:

sourcepath = r"E:/xxx/xxx" # 指定源路径(Word文档所在路径)

targetpath = r"E:/xxx/xxx/pdf/" # 指定目标路径(PDF保存路径)

filelist = getfilenames(sourcepath,[],‘.doc‘) # 获取Word文档路径

valueList = wordtopdf(filelist,targetpath) # 实现将Word文档批量转换为PDF

if valueList:

print("转换成功")

else:

print("没有要转换的Word文档或者转换失败!请检查!")

原文:https://www.cnblogs.com/hqczsh/p/12811683.html

实现Python实现Word无损PDF,可以使用Python-docx和PyPDF2。首先,使用Python-docxWord文档换为PDF格式,然后使用PyPDF2PDF文件合并为一个PDF。以下是实现的步骤: 1. 安装Python-docx和PyPDF2。 2. 使用Python-docx打开Word文档。 3. 创建一个空的PDF文件。 4. 遍历Word文档的每一页,将每一页的内容添加到PDF文件中。 5. 保存并关闭PDF文件。 6. 使用PyPDF2将所有生成的PDF文件合并为一个PDF文件。 以下是一个示例代码: ```python from docx import Document from PyPDF2 import PdfWriter def word_to_pdf(word_file, pdf_file): # 打开Word文档 doc = Document(word_file) # 创建一个空的PDF文件 pdf_writer = PdfWriter() for page_num, page in enumerate(doc.pages): # 将每一页的内容添加到PDF文件pdf_writer.add_page(page) # 保存PDF文件 with open(pdf_file, 'wb') as f: pdf_writer.write(f) # 关闭Word文档 doc.close() # 调用函数进行word_to_pdf('input.docx', 'output.pdf') ``` 请将`input.docx`替换为要换的Word文档的路径,将`output.pdf`替换为保存PDF的路径。 这样,您就可以使用Python实现Word无损PDF了。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *3* [太方便了!利用Python对批量PdfWord](https://blog.csdn.net/lyc2016012170/article/details/117719980)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] - *2* [Python实用功能之pdf文件png图片数据](https://blog.csdn.net/Together_CZ/article/details/126335438)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值