Skip to content

Commit a82a037

Browse files
committed
add merge pdf python sript
1 parent 8f4d1e4 commit a82a037

3 files changed

Lines changed: 60 additions & 1 deletion

File tree

‎python-note/index.rst‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,4 +11,5 @@
1111
funny
1212
ffmpeg
1313
flaskapi
14+
pdf
1415
uncurl

‎python-note/pdf.rst‎

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
.. _pdf:
2+
3+
合并 pdf
4+
========================================
5+
6+
.. code-block:: python
7+
8+
"""
9+
合并多个 pdf 到一个,使用方式:放到当前文件夹下运行
10+
"""
11+
12+
import os.path
13+
14+
from pyPdf import PdfFileReader, PdfFileWriter # pip install pyPdf
15+
16+
17+
def get_pdf_files(dst_dir):
18+
paths = []
19+
for root, dirs, files in os.walk(dst_dir):
20+
for filespath in files:
21+
if filespath.endswith('.pdf'): # pdf file
22+
abspath = os.path.join(root, filespath)
23+
paths.append(abspath)
24+
return paths
25+
26+
27+
##########################合并同一个文件夹下所有PDF文件########################
28+
def merge_pdf(dst_dir, outfile, sort=True):
29+
output = PdfFileWriter()
30+
curpage = 0
31+
pdf_paths = sorted(get_pdf_files(dst_dir)) if sort else get_pdf_files(dst_dir)
32+
for each in pdf_paths:
33+
print(each)
34+
reader = PdfFileReader(file(each, "rb"))
35+
# 如果pdf文件已经加密,必须首先解密才能使用pyPdf
36+
if reader.isEncrypted == True:
37+
reader.decrypt("map")
38+
# 获得源pdf文件中页面总数
39+
page_count = reader.getNumPages()
40+
curpage += page_count
41+
print(page_count)
42+
43+
for iPage in range(0, page_count):
44+
output.addPage(reader.getPage(iPage))
45+
46+
print("All Pages Number:" + str(curpage))
47+
outputStream = file(dst_dir + outfile, "wb")
48+
output.write(outputStream)
49+
outputStream.close()
50+
51+
52+
def main():
53+
merged = "all.pdf"
54+
merge_pdf("./", merged)
55+
56+
57+
if __name__ == '__main__':
58+
main()

‎python-note/uncurl.rst‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
.. _debug:
1+
.. _uncurl:
22

33
Uncurl
44
========================================

0 commit comments

Comments
 (0)