python 如何將office文件轉(zhuǎn)換為PDF
在平時(shí)的工作中,難免需要一些 小Tip 來(lái)解決工作中遇到的問題,今天的文章給大家安利一個(gè)方便快捷的小技巧,將 Office(doc/docx/ppt/pptx/xls/xlsx)文件批量或者單一文件轉(zhuǎn)換為 PDF 文件。 不過在做具體操作之前需要在 PC 安裝好 Office,再利用 Python 的 win32com 包來(lái)實(shí)現(xiàn) Office 文件的轉(zhuǎn)換操作。
安裝 win32com
在實(shí)戰(zhàn)之前,需要安裝 Python 的 win32com,詳細(xì)安裝步驟如下:
使用 pip 命令安裝
pip install pywin32
如果我們遇到安裝錯(cuò)誤,可以通過python -m pip install ?upgrade pip更新云端的方式再進(jìn)行安裝即可:
python -m pip install --upgrade pip
下載離線安裝包安裝
如果 pip 命令未安裝成功的話還可以下載離線包安裝,方法步驟如下: 首先在官網(wǎng)選擇對(duì)應(yīng)的 Python 版本下載離線包:https://sourceforge.net/projects/pywin32/files/pywin32/Build%20221/ 下載好后傻瓜式安裝好即可。
文件轉(zhuǎn)換邏輯
詳細(xì)代碼如下:
class PDFConverter: def __init__(self, pathname, export=’.’): self._handle_postfix = [’doc’, ’docx’, ’ppt’, ’pptx’, ’xls’, ’xlsx’] # 支持轉(zhuǎn)換的文件類型 self._filename_list = list() #列出文件 self._export_folder = os.path.join(os.path.abspath(’.’), ’file_server/pdfconver’) if not os.path.exists(self._export_folder): os.mkdir(self._export_folder) 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 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(’需要轉(zhuǎn)換的文件數(shù)是:’, len(self._filename_list)) for filename in self._filename_list: postfix = filename.split(’.’)[-1].lower() funcCall = getattr(self, postfix) print(’原文件:’, filename) funcCall(filename) print(’轉(zhuǎn)換完成!’)
doc/docx 轉(zhuǎn)換為 PDF
doc/docx 轉(zhuǎn)換為 PDF 部分代碼如下所示:
def doc(self, filename): name = os.path.basename(filename).split(’.’)[0] + ’.pdf’ exportfile = os.path.join(self._export_folder, name) print(’保存 PDF 文件:’, exportfile) gencache.EnsureModule(’{00020905-0000-0000-C000-000000000046}’, 0, 8, 4) pythoncom.CoInitialize() w = Dispatch('Word.Application') pythoncom.CoInitialize() # 加上防止 CoInitialize 未加載 doc = w.Documents.Open(filename) doc.ExportAsFixedFormat(exportfile, constants.wdExportFormatPDF,Item=constants.wdExportDocumentWithMarkup,CreateBookmarks=constants.wdExportCreateHeadingBookmarks) w.Quit(constants.wdDoNotSaveChanges)def docx(self, filename): self.doc(filename)
ppt/pptx 轉(zhuǎn)換為 PDF
ppt/pptx 轉(zhuǎn)換為 PDF 部分代碼如下:
def ppt(self, filename): name = os.path.basename(filename).split(’.’)[0] + ’.pdf’ exportfile = os.path.join(self._export_folder, name) gencache.EnsureModule(’{00020905-0000-0000-C000-000000000046}’, 0, 8, 4) pythoncom.CoInitialize() p = Dispatch('PowerPoint.Application') pythoncom.CoInitialize() ppt = p.Presentations.Open(filename, False, False, False) ppt.ExportAsFixedFormat(exportfile, 2, PrintRange=None) print(’保存 PDF 文件:’, exportfile) p.Quit() def pptx(self, filename): self.ppt(filename)
xls/xlsx 轉(zhuǎn)換為 PDF
def xls(self, filename): name = os.path.basename(filename).split(’.’)[0] + ’.pdf’ exportfile = os.path.join(self._export_folder, name) pythoncom.CoInitialize() xlApp = DispatchEx('Excel.Application') pythoncom.CoInitialize() xlApp.Visible = False xlApp.DisplayAlerts = 0 books = xlApp.Workbooks.Open(filename, False) books.ExportAsFixedFormat(0, exportfile) books.Close(False) print(’保存 PDF 文件:’, exportfile) xlApp.Quit() def xlsx(self, filename): self.xls(filename)
執(zhí)行邏輯轉(zhuǎn)換
if __name__ == '__main__': # 支持文件夾批量導(dǎo)入 #folder = ’tmp’ #pathname = os.path.join(os.path.abspath(’.’), folder) # 也支持單個(gè)文件的轉(zhuǎn)換 pathname = 'G:/python_study/test.doc' pdfConverter = PDFConverter(pathname) pdfConverter.run_conver()
總結(jié)
今天的文章主要是 Python 實(shí)戰(zhàn)之小工具的運(yùn)用,希望對(duì)大家有所幫助,下一期將講解如何通過接口的方式通過文件服務(wù)器來(lái)下載文件并轉(zhuǎn)換,敬請(qǐng)期待。。。 So 今天的小 Tip 你安利到了嗎?
示例代碼
https://github.com/JustDoPython/python-examples/tree/master/chaoxi/FilesToPDF
以上就是python 如何將office文件轉(zhuǎn)換為PDF的詳細(xì)內(nèi)容,更多關(guān)于python Office 文件轉(zhuǎn) PDF的資料請(qǐng)關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. 使用Python和百度語(yǔ)音識(shí)別生成視頻字幕的實(shí)現(xiàn)2. msxml3.dll 錯(cuò)誤 800c0019 系統(tǒng)錯(cuò)誤:-2146697191解決方法3. CSS可以做的幾個(gè)令你嘆為觀止的實(shí)例分享4. 在JSP中使用formatNumber控制要顯示的小數(shù)位數(shù)方法5. php中sort函數(shù)排序知識(shí)點(diǎn)總結(jié)6. 怎樣才能用js生成xmldom對(duì)象,并且在firefox中也實(shí)現(xiàn)xml數(shù)據(jù)島?7. css代碼優(yōu)化的12個(gè)技巧8. axios和ajax的區(qū)別點(diǎn)總結(jié)9. xml中的空格之完全解說(shuō)10. 利用ajax+php實(shí)現(xiàn)商品價(jià)格計(jì)算
