在平時的日常學習生活或辦公生活中,想必大家有過將pdf文件做批量合併,轉Word等方面的操作吧,今天這篇文章就教大家使用python來實現pdf文件的批量合併,轉Word操作。臨近學期末,我這裡就有一個這樣的需求,在網頁上有著幾套選擇題,我把它們存為pdf保存在了本地。為了更加方便的去查找相關字眼的題目,我就編寫了一些python代碼將多個pdf文件進行合併,並實現pdf文件轉Word的功能。溫馨提示:這些功能在現實中是需要收費的,作為我的粉絲,恭喜你們又學到了一招,學到就是賺到。丨
本案例很實用,建議點讚收藏!!!!
這裡使用的第三方模塊有:pdf2docx、PyPDF2,如果有未安裝模塊的夥伴可以在終端上使用以下命令進行安裝:
1pip install pdf2docx
2pip install PyPDF2
出現Successful代表模塊安裝成功!
在前期環境準備工作完成以後,現在我們要做的就是編寫處理業務功能的函數模塊啦!首先來編寫實現多個pdf文件批合併功能,編寫函數pdf_merge(),並提供兩個參數:1、存放多個pdf文件的目錄,2、批合併後生成的文件名。這裡用os模塊的listdir方法幫我們列出目錄中的文件並給我們返回一個列表。在對該列表進行遍歷並過濾出pdf文件,使用列表推導式的方式將目錄中的pdf文件存入處理好的列表當中。並將列表中的pdf文件批量添加到該pdf文件管理器中,最後在將pdf管理器中的pdf文件對象進行寫入(合併操作)就完成pdf的合併操作啦。
1def pdf_merge(target_path, fileName):
2 '''
3 :param target_path: 存放pdf文件的目錄
4 :return:轉換後的文件名
5 '''
6 # target_path = '題目'
7 pdf_lst = [f for f in os.listdir(target_path) if f.endswith('.pdf')]
8 pdf_lst = [os.path.join(target_path, filename) for filename in pdf_lst]
9
10 file_merger = PdfFileMerger()
11 for pdf in pdf_lst:
12 file_merger.append(pdf) # 合併pdf文件
13
14 file_merger.write(fileName) # 合併為merge.pdf
15 return fileName
1def pdf_docx(file):
2 '''
3 :param file:pdf文件
4 :return:
5 '''
6 if file.endswith('pdf'):
7 docx_file = file.replace('pdf', 'docx')
8 pdf = pdf2docx.Converter(file)
9 pdf.convert(docx_file, start=0, end=None)
10 pdf.close()
11 print(f'{docx_file}\t文件轉為完成!')
12 else:
13 print(f'{file}不是一個pdf文件!')
以上就是兩個功能函數的實現,現在來運行代碼看看吧~
代碼運行完畢,可以看到批合併的pdf文件和pdf轉換的文件已經生成好啦~
最後奉上全部代碼:
1import os, pdf2docx
2from PyPDF2 import PdfFileMerger
3
4
5def pdf_merge(target_path, fileName):
6 '''
7 :param target_path: 存放pdf文件的目錄
8 :return:轉換後的文件名
9 '''
10 # target_path = '題目'
11 pdf_lst = [f for f in os.listdir(target_path) if f.endswith('.pdf')]
12 pdf_lst = [os.path.join(target_path, filename) for filename in pdf_lst]
13
14 file_merger = PdfFileMerger()
15 for pdf in pdf_lst:
16 file_merger.append(pdf) # 合併pdf文件
17
18 file_merger.write(fileName) # 合併為merge.pdf
19 return fileName
20
21
22def pdf_docx(file):
23 '''
24 :param file:pdf文件
25 :return:
26 '''
27 if file.endswith('pdf'):
28 docx_file = file.replace('pdf', 'docx')
29 pdf = pdf2docx.Converter(file)
30 pdf.convert(docx_file, start=0, end=None)
31 pdf.close()
32 print(f'{docx_file}\t文件轉為完成!')
33 else:
34 print(f'{file}不是一個pdf文件!')
35
36
37if __name__ == '__main__':
38 file = pdf_merge('題目', 'merge.pdf')
39 pdf_docx(file)
以上就是今天的全部內容了,最後預祝大家聖誕快樂~~
更多精彩內容 ,敬請關注公眾號: