![見出し画像](https://assets.st-note.com/production/uploads/images/146420759/rectangle_large_type_2_58dbdf87439970d4d323577fdb99173a.png?width=1200)
python:htmlをpdfにする
Pythonでhtmlをpdfにする方法です。
ただしシンプルなhtmlが書いてあるWebサイト限定です。おしゃれなWebサイトはうまいこと印刷されず、エラーになる事をご了承ください。
そのため、有償記事化を断念しました。
仕様
1.python実行後の「URL入力」画面にhtmlのURLを入力します。
2.ダウンロードフォルダに「HtmlToPdf_yyyymmddhhnnss.pdf」というpdfファイルを出力し、ダウンロードフォルダとpdfファイルを起動します。
サンプル
1.画面にこちらのURL「https://note.com/good_lilac166/n/nf5db01b06427」を入力します。
![](https://assets.st-note.com/img/1720269271228-T16O002zEm.png)
2.以下のpdfファイルが出力され、ダウンロードフォルダとpdfファイルが起動します。
![](https://assets.st-note.com/img/1720269305875-ExEvLyivGW.png?width=1200)
本題
1.「https://wkhtmltopdf.org/downloads.html」から「wkhtmltox」をダウンロードします。
以下のソースは「7z Archive (XP/2003 or later)」の「64-bit」をダウンロードした例です。
2.7zip(https://7-zip.opensource.jp/)を使用して、ダウンロードした「wkhtmltox-0.12.6-1.mxe-cross-win64.7z」を展開してください。
以下のソースの展開先は「C:\resource\wkhtmltox-0.12.6-1.mxe-cross-win64\wkhtmltox\bin」にしています。
必要に応じてソース内のパスを変えてください。
3.パッケージをinstallします。
pip install requests pdfkit
4.以下、ソースです。
import os
import pdfkit
import subprocess
import requests
import tkinter as tk
from tkinter import messagebox, simpledialog
from datetime import datetime
# wkhtmltopdfのパスを明示的に指定する
config = pdfkit.configuration(wkhtmltopdf=r'C:\resource\wkhtmltox-0.12.6-1.mxe-cross-win64\wkhtmltox\bin\wkhtmltopdf.exe')
# Tkinterのルートウィンドウを作成
root = tk.Tk()
root.withdraw() # ルートウィンドウを非表示にする
try:
# URLをユーザーに入力してもらう
url = simpledialog.askstring("URL入力", " 変換するWebページのURLを入力してください ")
if url:
# ページの内容を取得
response = requests.get(url)
if response.status_code == 200:
# HTMLを一時ファイルに保存
temp_html_path = os.path.join(os.getcwd(), "HtmlToPdf.html")
with open(temp_html_path, 'wb') as f:
f.write(response.content)
# 出力ファイルのパスを設定(ファイル名はURLのホスト名 + 現在の日時)
html_file_name = os.path.splitext(os.path.basename(temp_html_path))[0]
current_time = datetime.now().strftime("%Y%m%d%H%M%S")
output_filename = f"{html_file_name}_{current_time}.pdf"
download_path = os.path.join(os.path.expanduser('~'), 'Downloads')
output_path = os.path.join(download_path, output_filename)
# PDFに変換する際のオプション設定
options = {
'quiet': '',
'disable-javascript': '',
'enable-local-file-access': '',
}
# PDFに変換
pdfkit.from_file(temp_html_path, output_path, configuration=config, options=options)
print(f"PDFをダウンロードフォルダに作成しました: {output_path}")
# PDFをデフォルトのPDFビューアーで開く
subprocess.Popen([output_path], shell=True)
# ダウンロードフォルダをエクスプローラーで開く(重複を避ける)
if not os.path.exists(output_path):
subprocess.Popen(['explorer', download_path])
# 一時ファイルを削除
if os.path.exists(temp_html_path):
os.remove(temp_html_path)
else:
messagebox.showerror("エラー", f"ページを取得できませんでした。ステータスコード: {response.status_code}")
else:
print("URLが入力されませんでした。")
except requests.RequestException as e:
error_message = f"リクエスト中にエラーが発生しました: {e}"
print(error_message)
messagebox.showerror("エラー", error_message)
except OSError as e:
error_message = f"OSErrorが発生しました: {e}"
print(error_message)
messagebox.showerror("エラー", error_message)
except Exception as e:
error_message = f"予期しないエラーが発生しました: {e}"
print(error_message)
messagebox.showerror("エラー", error_message)