import markdown
from fpdf import FPDF, XPos, YPos

class PDF(FPDF):
    def header(self):
        pass

    def footer(self):
        pass

    def chapter_title(self, title):
        self.set_font('MSGothic', '', 16)
        self.cell(0, 10, title, new_x=XPos.LMARGIN, new_y=YPos.NEXT, align='C')

    def chapter_body(self, body):
        self.set_font('MSGothic', '', 12)
        self.multi_cell(0, 10, body)
        self.ln()

def markdown_to_html(markdown_text):
    html = markdown.markdown(markdown_text)
    return html

def html_to_pdf(html, output_filename):
    pdf = PDF()
    pdf.add_page()
    
    # MS Gothicフォントを追加
    pdf.add_font('MSGothic', '', r'C:\Windows\Fonts\msgothic.ttc')

    # HTMLを行ごとに処理してPDFに変換
    lines = html.split('\n')
    for line in lines:
        if line.startswith('<h1>'):
            text = line.replace('<h1>', '').replace('</h1>', '')
            pdf.chapter_title(text)
        elif line.startswith('<h2>'):
            text = line.replace('<h2>', '').replace('</h2>', '')
            pdf.chapter_title(text)
        elif line.startswith('<p>'):
            text = line.replace('<p>', '').replace('</p>', '')
            pdf.chapter_body(text)
        elif line.startswith('<li>'):
            text = line.replace('<li>', '').replace('</li>', '')
            pdf.chapter_body(f'- {text}')

    # PDFファイルを保存
    pdf.output(output_filename)

# 使用例
markdown_text = """
# これは見出し1

これは段落です。

## これは見出し2

- リストの項目1
- リストの項目2
- リストの項目3

[リンクのテキスト](https://example.com)
"""

html_output = markdown_to_html(markdown_text)
html_to_pdf(html_output, 'output.pdf')
