本文首發(fā)于一個用于合并pdf的簡單Python腳本 | 磚瓦匠杜重
轉載需注明出處步咪。
在學校打印店摇天,有時會打印很多文件瞪浸,因為文件數量多货徙,過程會比較繁瑣航揉。自己沒事動手寫了一個pdf合并的python腳本骤视,方便將多個pdf文件合并為一弛作。這樣打印時候只需點開一個文件打印即可举娩。
使用方法
必要的安裝
需要Python和PyPDF2锐墙。Python安裝可在官網找到礁哄;PyPDF2可以通過pip安裝,可以利用命令行工具輸入一下命令
pip install PyPDF2
使用
將需要合并的文件與本文后面的Python腳本放在同一目錄下溪北,運行腳本得到Merged.pdf
即為合并的pdf文件桐绒。
注意:腳本會將所在目錄下所有pdf文件進行合并,須確保目錄下只有需要合并的pdf文件之拨。
使用Tips
按順序合并pdf文件
如果需要按照一定順序合并pdf文件茉继,可以將pdf文件重命名,按順序將文件重命名為1.pdf
蚀乔、2.pdf
以此類推烁竭。
重復合并同一pdf文件
如果需要將某一pdf文件在合并文件中重復多次,可以將該文件直接在當前目錄下拷貝成多個副本吉挣。
腳本代碼
"""
A simple python script to merge all the pdf files in the directory where this script is located.
@author: Chong Du
"""
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()