|
| 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() |
0 commit comments