使用Python批量合並PDF文件(帶書簽功能)


網上找了幾個合並pdf的軟件,發現不是很好用,一般都沒有添加書簽的功能。

又去找了下python合並pdf的腳本,發現也沒有添加書簽的功能的。

於是自己動手編寫了一個小工具,使用了PyPDF2。

下面是使用的截圖:

代碼如下: 

 1 #!/usr/bin/env python3
 2 # -*- coding: utf-8 -*-
 3 '''
 4    #文件名:pdfmerge.py
 5    本腳本用來合並pdf文件,輸出的pdf文件按輸入的pdf文件名生成書簽
 6    使用示例如下:
 7    python pdfmerge.py -p "D:\pdf-files" -o "merged-out.pdf" -b True'
 8 
 9    示例說明:
10    要合並的pdf文件所在的路徑: D:\pdf-files
11    合並后的pdf文件的輸出文件名:merged-out.pdf
12    是否從pdf文件中導入書簽的值:True
13 '''
14 import os, sys, codecs
15 from argparse import ArgumentParser, RawTextHelpFormatter
16 from PyPDF2 import PdfFileReader, PdfFileWriter, PdfFileMerger
17 
18 def getfilenames(filepath='',filelist_out=[],file_ext='all'):
19     # 遍歷filepath下的所有文件,包括子目錄下的文件
20     for fpath, dirs, fs in os.walk(filepath):
21         for f in fs:
22             fi_d = os.path.join(fpath, f)
23             if  file_ext == 'all':
24                 filelist_out.append(fi_d)
25             elif os.path.splitext(fi_d)[1] == file_ext:
26                 filelist_out.append(fi_d)
27             else:
28                 pass
29     return filelist_out
30 
31 def mergefiles(path, output_filename, import_bookmarks=False):
32     # 遍歷目錄下的所有pdf將其合並輸出到一個pdf文件中,輸出的pdf文件默認帶書簽,書簽名為之前的文件名
33     # 默認情況下原始文件的書簽不會導入,使用import_bookmarks=True可以將原文件所帶的書簽也導入到輸出的pdf文件中
34     merger = PdfFileMerger()
35     filelist = getfilenames(filepath=path, file_ext='.pdf')
36     if len(filelist) == 0:
37         print("當前目錄及子目錄下不存在pdf文件")
38         sys.exit()
39     for filename in filelist:
40         f = codecs.open(filename, 'rb')
41         file_rd = PdfFileReader(f)
42         short_filename = os.path.basename(os.path.splitext(filename)[0])
43         if file_rd.isEncrypted == True:
44             print('不支持的加密文件:%s'%(filename))
45             continue
46         merger.append(file_rd, bookmark=short_filename, import_bookmarks=import_bookmarks)
47         print('合並文件:%s'%(filename))
48         f.close()
49     out_filename=os.path.join(os.path.abspath(path), output_filename)
50     merger.write(out_filename)
51     print('合並后的輸出文件:%s'%(out_filename))
52     merger.close()
53 
54 if __name__ == "__main__":
55     description="\n本腳本用來合並pdf文件,輸出的pdf文件按輸入的pdf文件名生成書簽\n使用示例如下:"
56     description=description+'\npython pdfmerge.py -p "D:\pdf-files" -o "merged-out.pdf" -b True'
57     description=description+'\n\n'+"示例說明:"
58     description=description+'\n'+"要合並的pdf文件所在的路徑: D:\pdf-files"
59     description=description+'\n'+"合並后的pdf文件的輸出文件名:merged-out.pdf"
60     description=description+'\n'+"是否從pdf文件中導入書簽的值:True"
61 
62     # 添加程序幫助,程序幫助支持換行符號
63     parser = ArgumentParser(description=description, formatter_class=RawTextHelpFormatter)
64 
65     # 添加命令行選項
66 
67     parser.add_argument("-p", "--path",
68                         dest="path",
69                         default=".",
70                         help="PDF文件所在目錄")
71     parser.add_argument("-o", "--output",
72                         dest="output_filename",
73                         default="merged.pdf",
74                         help="合並PDF的輸出文件名",
75                         metavar="FILE")
76     parser.add_argument("-b", "--bookmark",
77                     dest="import_bookmarks",
78                     default="False",
79                     help="是否從pdf文件中導入書簽,值可以是'True'或者'False'")
80 
81     args = parser.parse_args()
82     #try:
83     mergefiles(args.path, args.output_filename, args.import_bookmarks)
84     #except:
85     #    print('Error to merge pdf file:')
86     #    print(sys.exc_info()[0],sys.exc_info()[1])
87         

 

說明:在實際使用過程中,發現因為字符編碼問題,部分pdf文件會報錯,導致代碼無法正常執行。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM