一個(gè)用于合并pdf的簡(jiǎn)單Python腳本

本文首發(fā)于一個(gè)用于合并pdf的簡(jiǎn)單Python腳本 | 磚瓦匠杜重
轉(zhuǎn)載需注明出處。


在學(xué)校打印店,有時(shí)會(huì)打印很多文件,因?yàn)槲募?shù)量多,過(guò)程會(huì)比較繁瑣。自己沒事動(dòng)手寫了一個(gè)pdf合并的python腳本,方便將多個(gè)pdf文件合并為一。這樣打印時(shí)候只需點(diǎn)開一個(gè)文件打印即可。

使用方法

必要的安裝

需要PythonPyPDF2。Python安裝可在官網(wǎng)找到;PyPDF2可以通過(guò)pip安裝,可以利用命令行工具輸入一下命令

pip install PyPDF2

使用

將需要合并的文件與本文后面的Python腳本放在同一目錄下,運(yùn)行腳本得到Merged.pdf即為合并的pdf文件。

注意:腳本會(huì)將所在目錄下所有pdf文件進(jìn)行合并,須確保目錄下只有需要合并的pdf文件。

使用Tips

按順序合并pdf文件

如果需要按照一定順序合并pdf文件,可以將pdf文件重命名,按順序?qū)⑽募孛麨?code>1.pdf、2.pdf以此類推。

重復(fù)合并同一pdf文件

如果需要將某一pdf文件在合并文件中重復(fù)多次,可以將該文件直接在當(dāng)前目錄下拷貝成多個(gè)副本。

腳本代碼

"""
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()
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容