【轉】利用Python將多個PDF合並為一個


  • 本腳本用來合並pdf文件,輸出的pdf文件按輸入的pdf文件名生成書簽

  • 使用示例如下:

    python pdfmerge.py -p "D:\pdf-files" -o "merged-out.pdf" -b True'
    
    • 1
  • 示例說明:
    要合並的pdf文件所在的路徑: D:\pdf-files
    合並后的pdf文件的輸出文件名:merged-out.pdf
    是否從pdf文件中導入書簽的值:True

  • 所用模塊:PyPDF2argparse及其他

  • 測試環境:3.7.1

  • 實現代碼:

import os, sys, codecs from argparse import ArgumentParser, RawTextHelpFormatter from PyPDF2 import PdfFileReader, PdfFileWriter, PdfFileMerger def getfilenames(filepath='',filelist_out=[],file_ext='all'): # 遍歷filepath下的所有文件,包括子目錄下的文件 for fpath, dirs, fs in os.walk(filepath): for f in fs: fi_d = os.path.join(fpath, f) if file_ext == 'all': filelist_out.append(fi_d) elif os.path.splitext(fi_d)[1] == file_ext: filelist_out.append(fi_d) else: pass return filelist_out def mergefiles(path, output_filename, import_bookmarks=False): # 遍歷目錄下的所有pdf將其合並輸出到一個pdf文件中,輸出的pdf文件默認帶書簽,書簽名為之前的文件名 # 默認情況下原始文件的書簽不會導入,使用import_bookmarks=True可以將原文件所帶的書簽也導入到輸出的pdf文件中 merger = PdfFileMerger() filelist = getfilenames(filepath=path, file_ext='.pdf') if len(filelist) == 0: print("當前目錄及子目錄下不存在pdf文件") sys.exit() for filename in filelist: f = codecs.open(filename, 'rb') file_rd = PdfFileReader(f) short_filename = os.path.basename(os.path.splitext(filename)[0]) if file_rd.isEncrypted == True: print('不支持的加密文件:%s'%(filename)) continue merger.append(file_rd, bookmark=short_filename, import_bookmarks=import_bookmarks) print('合並文件:%s'%(filename)) f.close() out_filename=os.path.join(os.path.abspath(path), output_filename) merger.write(out_filename) print('合並后的輸出文件:%s'%(out_filename)) merger.close() if __name__ == "__main__": description="\n本腳本用來合並pdf文件,輸出的pdf文件按輸入的pdf文件名生成書簽\n使用示例如下:" description=description+'\npython pdfmerge.py -p "D:\pdf-files" -o "merged-out.pdf" -b True' description=description+'\n\n'+"示例說明:" description=description+'\n'+"要合並的pdf文件所在的路徑: D:\pdf-files" description=description+'\n'+"合並后的pdf文件的輸出文件名:merged-out.pdf" description=description+'\n'+"是否從pdf文件中導入書簽的值:True" # 添加程序幫助,程序幫助支持換行符號 parser = ArgumentParser(description=description, formatter_class=RawTextHelpFormatter) # 添加命令行選項 parser.add_argument("-p", "--path", dest="path", default=".", help="PDF文件所在目錄") parser.add_argument("-o", "--output", dest="output_filename", default="merged.pdf
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM