#python #プログラミング #初心者
import os
import comtypes.client
# Wordファイルが格納されているフォルダ
input_folder = r”D:\youtube\pytho_機能\WordファイルをPDF化”
# PDF出力先フォルダ(同じフォルダに保存する場合はinput_folderと同じにする)
output_folder = input_folder
# Wordアプリケーションを起動
word = comtypes.client.CreateObject(“Word.Application”)
word.Visible = False # バックグラウンドで実行
# フォルダ内のファイルを取得
for file in os.listdir(input_folder):
if file.endswith(“.docx”): # .docxファイルのみ対象
input_path = os.path.join(input_folder, file)
output_path = os.path.join(output_folder, file.replace(“.docx”, “.pdf”))
# Wordを開いてPDFとして保存
doc = word.Documents.Open(input_path)
doc.SaveAs(output_path, FileFormat=17) # 17 = PDF
doc.Close()
# Wordアプリケーションを終了
word.Quit()
print(“PDF変換が完了しました。”)
import os
import comtypes.client
# Wordファイルが格納されているフォルダ
input_folder = r”D:youtubepytho_機能WordファイルをPDF化”
log_file = os.path.join(input_folder, “conversion_log.txt”) # ログファイル
# Wordアプリケーションを起動
word = comtypes.client.CreateObject(“Word.Application”)
word.Visible = False # バックグラウンドで実行
def convert_to_pdf(input_path):
“””WordファイルをPDFに変換”””
try:
output_path = input_path.rsplit(“.”, 1)[0] + “.pdf” # .docx → .pdf への変換
if os.path.exists(output_path):
return f”スキップ: output_path(既に存在)”
doc = word.Documents.Open(input_path)
doc.SaveAs(output_path, FileFormat=17) # 17 = PDF
doc.Close()
return f”変換成功: output_path”
except Exception as e:
return f”エラー: input_path → e”
def process_folder(folder):
“””フォルダ内のWordファイルを再帰的に処理”””
log_entries = []
for root, _, files in os.walk(folder):
for file in files:
if file.endswith((“.doc”, “.docx”)): # .doc と .docx 両方対応
input_path = os.path.join(root, file)
result = convert_to_pdf(input_path)
log_entries.append(result)
print(result)
# ログをファイルに書き出し
with open(log_file, “w”, encoding=”utf-8″) as f:
f.write(“n”.join(log_entries) + “n”)
# フォルダを処理
process_folder(input_folder)
# Wordアプリケーションを終了
word.Quit()
print(“PDF変換が完了しました。ログを確認してください。”)



コメント