python合并多个PDF到一个PDF
python合并多个PDF到一个PDF
pycharm为例,先安装 PyPDF2 这个库,然后将所有需要合并的pdf ,比如按照 1 2 3 4 的名称,放入和下列代码一样的目录下,执行下列代码即可,会生成一个 merged.pdf
合并后的内容顺序,也会按照 1 2 3 4 的顺序。
import PyPDF2
import os
import re
def main():
# find all the pdf files in current directory.
mypath = os.getcwd()
pattern = r"\.pdf$"
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()
作者: 轻烟随风
当前文章地址: https://www.zyxpp.com/pythonmergepdf/
来源: 轻烟随风的博客
文章版权归作者所有,欢迎转载
当前文章地址: https://www.zyxpp.com/pythonmergepdf/
来源: 轻烟随风的博客
文章版权归作者所有,欢迎转载
THE END
二维码
文章目录
关闭
共有 0 条评论