実現したいこと
コマンドラインから、引数で渡したPDFファイルを、パスワード付PDFに変換したく
以下のPyhtonプログラムを作成しました。
python
1import pypdf 2import sys 3 4def set_password(src_path, dst_path, user_password, owner_password=None): 5 6 print(src_path) 7 print(ascii(src_path)) 8 print(ascii("C:\\temp\\sample2\\0000000AB・CD 株式会社 御中.PDF")) 9 print("C:\\temp\\sample2\\0000000AB\u30fbCD\u3000株式会社 御中.PDF") 10 11 src_pdf = pypdf.PdfReader(src_path) 12 dst_pdf = pypdf.PdfWriter() 13 dst_pdf.clone_reader_document_root(src_pdf) 14 15 d = {key: src_pdf.metadata[key] for key in src_pdf.metadata.keys()} 16 dst_pdf.add_metadata(d) 17 18 dst_pdf.encrypt(user_password, owner_password) 19 dst_pdf.write(dst_path) 20 21if __name__ == '__main__': 22 args = sys.argv 23 if 5 == len(args): 24 set_password(args[1], args[2],args[3], args[4]) 25 else: 26 print('引数の数が一致しません。')
コードのデバックを行うために、以下launch.jsonファイルを作成し実行したところ
例外エラーが発生しました。
json
1{ 2 // IntelliSense を使用して利用可能な属性を学べます。 3 // 既存の属性の説明をホバーして表示します。 4 // 詳細情報は次を確認してください: https://go.microsoft.com/fwlink/?linkid=830387 5 "version": "0.2.0", 6 "configurations": [ 7 8 { 9 "name": "Python: 現在のファイル", 10 "type": "python", 11 "request": "launch", 12 "program": "${file}", 13 "console": "integratedTerminal", 14 "justMyCode": true, 15 "args": [ 16 "C:\\temp\\sample2\\0000000AB・CD 株式会社 御中.PDF", 17 "C:\\temp\\sample2\\0000000AB・CD 株式会社 御中.PDF", 18 "pass", 19 "pass" 20 ] 21 } 22 ] 23}
発生している問題・分からないこと
引数で渡したパス・ファイル名の中点は削除され、ブランクは¥u3000で
プログラムに引き渡されていると思いますが、回避する方法は無いでしょうか。
¥マークはバックスラッシュで読み替えて下さい。
エラーメッセージ
error
1例外が発生しました: FileNotFoundError 2[Errno 2] No such file or directory: 'C:\\temp\\sample2\\0000000ABCD\u3000株式会社 御中.PDF' 3 File "C:\Users\user\pytest\PDF_pwSet.py", line 8, in set_password 4 src_pdf = pypdf.PdfReader(src_path) 5 File "C:\Users\user\pytest\PDF_pwSet.py", line 21, in <module> 6 set_password(args[1], args[2],args[3], args[4]) 7FileNotFoundError: [Errno 2] No such file or directory: 'C:\\temp\\sample2\\0000000ABCD\u3000株式会社 御中.PDF'
該当のソースコード
python
1src_pdf = pypdf.PdfReader(src_path)
試したこと・調べたこと
- teratailやGoogle等で検索した
- ソースコードを自分なりに変更した
- 知人に聞いた
- その他
上記の詳細・結果
引数のファイル名が半角英数(「ABCD.PDF」等)の場合は、問題なく実行できます。
src_pdf = pypdf.PdfReader(src_path)の部分を
src_pdf = pypdf.PdfReader(r"C:\temp\sample2\0000000AB・CD 株式会社 御中.PDF")に
変更し実行したところ、ファイル名が全角でも問題なくパスワード付のPDFに変換されたためプログラムそのものに問題は無いかと思います。
以下、print文を入れた結果のターミナルに表示
print(src_path)
print(ascii(src_path))
print(ascii("C:\temp\sample2\0000000AB・CD 株式会社 御中.PDF"))
print("C:\temp\sample2\0000000AB\u30fbCD\u3000株式会社 御中.PDF")
結果
C:\temp\sample2\0000000ABCD 株式会社 御中.PDF
'C:\temp\sample2\0000000\uff21\uff22\uff23\uff24\u3000\u682a\u5f0f\u4f1a\u793e \u5fa1\u4e2d.PDF'
'C:\temp\sample2\0000000\uff21\uff22\u30fb\uff23\uff24\u3000\u682a\u5f0f\u4f1a\u793e \u5fa1\u4e2d.PDF'
C:\temp\sample2\0000000AB・CD 株式会社 御中.PDF
補足
windows10
python 3.9.9
pypdf 4.0.1
回答1件
あなたの回答
tips
プレビュー