LoginSignup
2
8

More than 1 year has passed since last update.

【業務効率化】Pythonで大量のWordもExcelも一気にPDF化して、ついでに結合する【Windows対応】【Mac対応したい】

Last updated at Posted at 2021-11-10

はじめに

Windowsでのみ動作確認してます。
PDF化はWord、Excelから簡単にできますが、大量のファイルを手作業でPDF化するのが苦痛だったので一発でPDF化、そして結合できるプログラムを作成しました。

こんな感じに動きます。

output.gif

詳しく、コードの解説をしているわけでもないですが、記事読んでいただければ同様の問題を解決できるかと思います。

すぐ使えるスクリプト

環境:
-Windows10
-Python 3.9.6
前提条件:
-pythonがpcにinstall済み
-Excel,Wordをインストール済み
-ターミナル(コマンドプロンプト)を使用可能

使用する外部ライブラリ
pip install docx2pdf
pip install pywin32
pip install PyPDF2
ms2pdf.py
import docx2pdf
import win32com.client
import PyPDF2
import re
import os

def excel2pdf(input_file, output_file):
    #エクセルを開く
    app = win32com.client.Dispatch("Excel.Application")
    app.Visible = True
    app.DisplayAlerts = False
    # Excelでワークブックを読み込む
    book = app.Workbooks.Open(input_file)
    # PDF形式で保存
    xlTypePDF = 0
    book.ExportAsFixedFormat(xlTypePDF, output_file)
    #エクセルを閉じる
    app.Quit()

if __name__ == '__main__':
    # 対象ディレクトリを入力(コピペok)(最後に\(¥)をつけない)
    print("Which dir(full path)?:", end="")
    # 対象フォルダ
    input_dir = (input()+"\\").replace('/', os.sep)
    filenames = os.listdir(input_dir)
    output_dir = (input_dir + "pdf/").replace('/', os.sep)
    # ディレクトリが存在しない場合、ディレクトリを作成する
    if not os.path.exists(output_dir):
        os.makedirs(output_dir)
    for file in filenames:
        # 拡張子が".docx"のものをpdfに変換
        word_match = re.search("\.docx$", file) 
        if word_match: 
            docx2pdf.convert(input_dir+file, output_dir+file[:-5]+".pdf")
            print(file)
        # 拡張子が".xlsx"のものをpdfに変換
        excel_match = re.search("\.xlsx$", file) 
        if excel_match: 
            excel2pdf(input_dir+file, output_dir+file[:-5]+".pdf")
            print(file)
print()
print("-------------------------------")
print("merging PDF from:" + output_dir)
# 結合するPDFファイル一覧を表示
print("↓↓↓↓↓↓↓↓↓↓↓↓ target file ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓")
merger = PyPDF2.PdfFileMerger()

filenames = os.listdir(output_dir) 
num = 0
for file in filenames: 
        merger.append(output_dir + file)
        print(file)
        num += 1
print("↑↑↑↑↑↑↑↑↑↑↑↑ target file ↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑")
print("total: " + str(num) + "file")
print()
print("-------------------------------")
print()
# 結合したPDFの名前を入力
print("What merged file name?:", end="")
merged_file_name = input()
# 拡張子(.pdf)がなければ追加する
if merged_file_name[-4:] != ".pdf":
        merged_file_name += ".pdf"
merger.write(output_dir + merged_file_name)
merger.close()

Something went wrong

使い方
①ターミナル(コマンドプロンプト)でpython ms2pdf.pyを実行
②"Which dir(full path)?:"で対象ディレクトリを入力(コピペok)(最後に(¥)をつけない)
③"What merged file name?:"で結合したPDFの名前を入力
③大量のWordもExcelも一気にPDF化して、ついでに結合してくれる


一つ退屈な作業から解放されました。

参考

2
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
8