|
| 1 | +import os |
| 2 | +from win32com.client import Dispatch, constants, gencache, DispatchEx |
| 3 | +import pythoncom |
| 4 | +#import sys |
| 5 | + |
| 6 | +# sys.coinit_flags = 0 |
| 7 | +class PDFConverter: |
| 8 | + def __init__(self, pathname, export='.'): |
| 9 | + self._handle_postfix = ['doc', 'docx', 'ppt', 'pptx', 'xls', 'xlsx'] |
| 10 | + self._filename_list = list() |
| 11 | + self._export_folder = os.path.join(os.path.abspath('.'), 'file_server/pdfconver') |
| 12 | + if not os.path.exists(self._export_folder): |
| 13 | + os.mkdir(self._export_folder) |
| 14 | + self._enumerate_filename(pathname) |
| 15 | + |
| 16 | + def _enumerate_filename(self, pathname): |
| 17 | + ''' |
| 18 | + 读取所有文件名 |
| 19 | + ''' |
| 20 | + full_pathname = os.path.abspath(pathname) |
| 21 | + if os.path.isfile(full_pathname): |
| 22 | + if self._is_legal_postfix(full_pathname): |
| 23 | + self._filename_list.append(full_pathname) |
| 24 | + else: |
| 25 | + raise TypeError('文件 {} 后缀名不合法!仅支持如下文件类型:{}。'.format(pathname, '、'.join(self._handle_postfix))) |
| 26 | + elif os.path.isdir(full_pathname): |
| 27 | + for relpath, _, files in os.walk(full_pathname): |
| 28 | + for name in files: |
| 29 | + filename = os.path.join(full_pathname, relpath, name) |
| 30 | + if self._is_legal_postfix(filename): |
| 31 | + self._filename_list.append(os.path.join(filename)) |
| 32 | + else: |
| 33 | + raise TypeError('文件/文件夹 {} 不存在或不合法!'.format(pathname)) |
| 34 | + |
| 35 | + def _is_legal_postfix(self, filename): |
| 36 | + return filename.split('.')[-1].lower() in self._handle_postfix and not os.path.basename(filename).startswith( |
| 37 | + '~') |
| 38 | + |
| 39 | + def run_conver(self): |
| 40 | + ''' |
| 41 | + 进行批量处理,根据后缀名调用函数执行转换 |
| 42 | + ''' |
| 43 | + print('需要转换的文件数:', len(self._filename_list)) |
| 44 | + for filename in self._filename_list: |
| 45 | + postfix = filename.split('.')[-1].lower() |
| 46 | + funcCall = getattr(self, postfix) |
| 47 | + print('原文件:', filename) |
| 48 | + funcCall(filename) |
| 49 | + print('转换完成!') |
| 50 | + |
| 51 | + def doc(self, filename): |
| 52 | + ''' |
| 53 | + doc 和 docx 文件转换 |
| 54 | + ''' |
| 55 | + name = os.path.basename(filename).split('.')[0] + '.pdf' |
| 56 | + exportfile = os.path.join(self._export_folder, name) |
| 57 | + print('保存 PDF 文件:', exportfile) |
| 58 | + gencache.EnsureModule('{00020905-0000-0000-C000-000000000046}', 0, 8, 4) |
| 59 | + pythoncom.CoInitialize() |
| 60 | + w = Dispatch("Word.Application") |
| 61 | + pythoncom.CoInitialize() # 加上防止 CoInitialize 未加载 |
| 62 | + doc = w.Documents.Open(filename) |
| 63 | + doc.ExportAsFixedFormat(exportfile, constants.wdExportFormatPDF, |
| 64 | + Item=constants.wdExportDocumentWithMarkup, |
| 65 | + CreateBookmarks=constants.wdExportCreateHeadingBookmarks) |
| 66 | + w.Quit(constants.wdDoNotSaveChanges) |
| 67 | + |
| 68 | + def docx(self, filename): |
| 69 | + self.doc(filename) |
| 70 | + def xls(self, filename): |
| 71 | + ''' |
| 72 | + xls 和 xlsx 文件转换 |
| 73 | + ''' |
| 74 | + name = os.path.basename(filename).split('.')[0] + '.pdf' |
| 75 | + exportfile = os.path.join(self._export_folder, name) |
| 76 | + pythoncom.CoInitialize() |
| 77 | + xlApp = DispatchEx("Excel.Application") |
| 78 | + pythoncom.CoInitialize() |
| 79 | + xlApp.Visible = False |
| 80 | + xlApp.DisplayAlerts = 0 |
| 81 | + books = xlApp.Workbooks.Open(filename, False) |
| 82 | + books.ExportAsFixedFormat(0, exportfile) |
| 83 | + books.Close(False) |
| 84 | + print('保存 PDF 文件:', exportfile) |
| 85 | + xlApp.Quit() |
| 86 | + |
| 87 | + def xlsx(self, filename): |
| 88 | + self.xls(filename) |
| 89 | + |
| 90 | + def ppt(self, filename): |
| 91 | + ''' |
| 92 | + ppt 和 pptx 文件转换 |
| 93 | + ''' |
| 94 | + name = os.path.basename(filename).split('.')[0] + '.pdf' |
| 95 | + exportfile = os.path.join(self._export_folder, name) |
| 96 | + gencache.EnsureModule('{00020905-0000-0000-C000-000000000046}', 0, 8, 4) |
| 97 | + pythoncom.CoInitialize() |
| 98 | + p = Dispatch("PowerPoint.Application") |
| 99 | + pythoncom.CoInitialize() |
| 100 | + ppt = p.Presentations.Open(filename, False, False, False) |
| 101 | + ppt.ExportAsFixedFormat(exportfile, 2, PrintRange=None) |
| 102 | + print('保存 PDF 文件:', exportfile) |
| 103 | + p.Quit() |
| 104 | + |
| 105 | + def pptx(self, filename): |
| 106 | + self.ppt(filename) |
| 107 | + |
| 108 | +if __name__ == "__main__": |
| 109 | + # 支持文件夹批量导入 |
| 110 | + #folder = 'tmp' |
| 111 | + #pathname = os.path.join(os.path.abspath('.'), folder) |
| 112 | + # 也支持单个文件的转换 |
| 113 | + pathname = "G:/python_study/test.doc" |
| 114 | + pdfConverter = PDFConverter(pathname) |
| 115 | + pdfConverter.run_conver() |
| 116 | + |
0 commit comments