LoginSignup
3
1

More than 1 year has passed since last update.

pythonで複数のPDFファイルを一括で保護解除

Last updated at Posted at 2022-04-13

複数のPDFファイルの保護を一括で解除するツールを作成したので、ソース公開します。
(python初心者がとりあえず動くもの作っただけなので綺麗なソースではありませんが…)

1.ツール作成を思い立った背景

  • 公式HPからダウンロードできる国家試験の過去問PDFは大抵の場合が保護付き。
  • 学習過程でマーカーを付けたり、ファイル結合や編集を行いたい場面が多々あり、保護が邪魔:worried:

2.ツールの目的

  • 開催回、科目、問題/解答毎に別ファイルになっているPDFの保護解除を一括で行う
  • 1ファイルずつ手作業で保護解除はしたくない:tired_face:

3.ツールの仕様

  • 実行ツールと同じディレクトリ内のPFDファイルを全て保護解除して保存する
  • 動作環境はWindows10
  • pythonで作成

3.1 ツール実行

  1. ツール(exeファイル)を保護解除したいPDFファイルと同一ディレクトリに格納
    before_bulkUnlockPDF.png

  2. 実行中の様子
    r_ulkUnlockPDF.png"~完了"の文字が出たら[X]ボタンで閉じる

  3. フォルダ「unlockPdf」が作成され、配下に保護解除済みPDFが出力された
    after_bulkUnlockPDF.png
    全ファイルが保護解除済み、これでPDFが編集できます:laughing:

3.2 ソース

bulkUnlockPDF.py
import os,sys,glob
from pikepdf import Pdf

#カレントディレクトリに出力用のディレクトリ作成(ない場合のみ)
dirNm = "/unlockPdf"
if not os.path.exists(os.getcwd() + dirNm):
    os.makedirs(os.getcwd() + dirNm)

#カレントディレクトリ内のPDFファイルを取得してループ
files = glob.glob(os.getcwd() + "\*.pdf")
for file in files:
	pdffile = Pdf.open(file,password="")
	newPdf = Pdf.new()
	newPdf.pages.extend(pdffile.pages)
	saveFileNm = os.getcwd() + dirNm + "/" + os.path.basename(file)
	#出力済みフォルダに同名ファイルがない場合、PDF保護解除ファイルを出力
	if not os.path.exists(saveFileNm):
		newPdf.save(saveFileNm)
		print(saveFileNm + "を出力しました。")
	else:
		print(saveFileNm + "は既に存在します。")

#終了メッセージ出力
input("PDFの保護解除完了")

python実行環境をインストールしておらず、実行ツール(exe)だけ欲しい方はこちら
  ↓↓↓
bulkUnlockPDF.exe
  ↑↑↑

4.さいごに感想

  • かねてから勉強したかったpythonを初めてinstallしてツール作成しました:relaxed:
  • python最高~~:heart_eyes: もっと勉強したくなった:hugging:
  • あ、、pythonの勉強は目的ではなくて、試験合格が目的でした:joy:...頑張ります…
3
1
3

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
3
1