1000字范文,内容丰富有趣,学习的好帮手!
1000字范文 > doc/docx/xls/xlsx 转PDF

doc/docx/xls/xlsx 转PDF

时间:2019-07-17 06:30:16

相关推荐

doc/docx/xls/xlsx 转PDF

使用语言 python

使用版本 python3

部分文档不能编辑不能解析文档损坏无法处理,运行前需在本地安装Office

参考链接:/lzhc/p/10893846.html

# -*- coding:utf-8 -*-import osfrom win32com.client import Dispatch, constants, gencache, DispatchExclass PDFConverter:def __init__(self, pathname, export="."):self._handle_postfix = ["doc", "docx", "xls", "xlsx"]self._filename_list = list()self._enumerate_filename(pathname)def _enumerate_filename(self, pathname):"""读取所有文件名"""full_pathname = os.path.abspath(pathname)if os.path.isfile(full_pathname):if self._is_legal_postfix(full_pathname):self._filename_list.append(full_pathname)else:raise TypeError("文件{}后缀名不合法!仅支持如下文件类型:{}。".format(pathname, "、".join(self._handle_postfix)))elif os.path.isdir(full_pathname):for relpath, _, files in os.walk(full_pathname):for name in files:filename = os.path.join(full_pathname, relpath, name)if ".pdf" not in filename:if self._is_legal_postfix(filename):self._filename_list.append(os.path.join(filename))else:raise TypeError("文件 / 文件夹{}不存在或不合法!".format(pathname))def _is_legal_postfix(self, filename):return filename.split(".")[-1].lower() in self._handle_postfix and not os.path.basename(filename).startswith("~")def run_conver(self):"""进行批量处理,根据后缀名调用函数执行转换"""print("需要转换的文件数:", len(self._filename_list))for filename in self._filename_list:postfix = filename.split(".")[-1].lower()funcCall = getattr(self, postfix)print("原文件:", filename)funcCall(filename)print("转换完成!")def doc(self, filename):name = filename.replace(".doc", ".pdf")if os.path.exists(name) == False:doc2pdf(filename, name)def docx(self, filename):name = filename.replace(".docx", ".pdf")if os.path.exists(name) == False:doc2pdf(filename, name)def xls(self, filename):"""xls和xlsx文件转换"""if "xlsx" in filename:name = filename.replace(".xlsx", ".pdf")else:name = filename.replace(".xls", ".pdf")if os.path.exists(name) == False:xlApp = DispatchEx("Excel.Application")xlApp.Visible = FalsexlApp.DisplayAlerts = 0books = xlApp.Workbooks.Open(filename, False)books.ExportAsFixedFormat(0, name)books.Close(False)print("保存PDF文件:", name)xlApp.Quit()def xlsx(self, filename):self.xls(filename)def doc2pdf(input, name):word = Dispatch('Word.Application')doc = word.Documents.Open(input)doc.SaveAs(name, FileFormat=17)doc.Close()print("保存PDF文件:", name)word.Quit()def GenerateSupport():gencache.EnsureModule('{00020905-0000-0000-C000-000000000046}', 0, 8, 4)if __name__ == "__main__":# 支持文件夹批量导入# folder = "temp"# pathname = os.path.join(os.path.abspath("."), folder)# 也支持单个文件的转换pathname = 'C:\\Users\\Administrator\Desktop\Don`tClose\\xlsx\\申通发文'pdfConverter = PDFConverter(pathname)pdfConverter.run_conver()

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。