import os
from weasyprint import HTML
# ==========================================
# 1. レイアウトを生成するメイン関数
# ==========================================
def generate_layout(style_code, images, texts):
# Linux Mint環境でのパス設定
base_dir = os.path.dirname(os.path.abspath(__file__))
# スタイル解析
is_vertical = style_code[3] == 'T' # Tなら縦書き
writing_mode = "vertical-rl" if is_vertical else "horizontal-tb"
css_content = f"""
@page {{
size: A4;
margin: 15mm;
}}
body {{
writing-mode: {writing_mode};
font-family: "Sawarabi Mincho", serif;
margin: 0;
padding: 0;
line-height: 1.8;
}}
.container {{
display: grid;
grid-template-columns: repeat(4, 1fr); /* 4段構成 */
gap: 8mm;
height: 260mm;
}}
.item {{
width: 100%;
}}
/* --- 回り込み設定 (復活) --- */
.wrap-img {{
float: right; /* 縦書きでは「上」に配置 */
width: 40%; /* 段の幅に対する写真のサイズ */
margin-left: 5mm; /* 写真と文字の間の隙間 */
margin-bottom: 3mm;
}}
/* --- 段ごとの開始位置(高さ)調整 --- */
.item-2 {{
margin-top: 10mm; /* 2段めを大きく下げます */
}}
.item-3 {{
margin-top: 10mm; /* 3段めを少し下げます */
}}
/* 通常の画像設定 */
.normal-img {{
width: 100%;
height: auto;
display: block;
margin-bottom: 5mm;
}}
h2 {{
font-size: 1.1rem;
margin-bottom: 10px;
border-bottom: 1px solid #ccc;
writing-mode: horizontal-tb; /* ラベルは見やすく横書きに */
}}
"""
html_content = f"""
<!DOCTYPE html>
<html lang="ja">
<head><style>{css_content}</style></head>
<body>
<div class="container">
<div class="item item-1">
<h2># 1段め</h2>
<h1><p>{texts[0]}</p></h1>
<img src="{images[0]}" class="normal-img">
</div>
<div class="item item-2">
<h2># 2段め</h2>
<img src="{images[1]}" class="wrap-img">
<p>{texts[1]}</p>
</div>
<div class="item item-3">
<h2># 3段め</h2>
<img src="{images[2]}" class="wrap-img">
<p>{texts[2]}</p>
</div>
<div class="item">
<h2># 4段め</h2>
<p>{texts[3]}</p>
</div>
</div>
</body>
</html>
"""
# --- PDF出力実行 ---
output_path = os.path.join(base_dir, "output_434T.pdf")
HTML(string=html_content, base_url=base_dir).write_pdf(output_path)
print(f"PDFを作成しました: {output_path}")
# ==========================================
# 2. 実行部分
# ==========================================
if __name__ == "__main__":
base_dir = os.path.dirname(os.path.abspath(__file__))
text_files = ["t.txt", "a.txt", "b.txt", "c.txt"]
image_files = ["photo1.jpg", "photo2.jpg", "photo3.jpg"]
try:
# ファイルからテキストを読み込み
loaded_texts = []
for f_name in text_files:
path = os.path.join(base_dir, f_name)
with open(path, "r", encoding="utf-8") as f:
loaded_texts.append(f.read())
# プログラム実行
generate_layout("434T", image_files, loaded_texts)
except Exception as e:
print(f"エラーが発生しました: {e}")
|