Python合并PDF

具体代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2019-03-25 15:23:25
# @Author : KK
# @Link : http://default.com
# @Version : $Id$

###For Debian10

import PyPDF2
import os
import re


def main():
# find all the pdf files in current directory.
mypath = os.getcwd()
print(mypath)
pattern = r"\.pdf$"
#以下文件路径在debian10中适用
file_names_lst = [mypath + '/'+f for f in os.listdir(mypath) if re.search(pattern, f, re.IGNORECASE)
and not re.search(r'Merged.pdf',f)]

# merge the file.
opened_file = [open(file_name,'rb') for file_name in file_names_lst]
pdfFM = PyPDF2.PdfFileMerger()
for file in opened_file:
pdfFM.append(file)

# output the file.
with open(mypath + '/' +"Merged.pdf", 'wb') as write_out_file:
pdfFM.write(write_out_file)

# close all the input files.
for file in opened_file:
file.close()
if __name__ == '__main__':
main()