import markdown
from weasyprint import HTML
# ==========================================
# REUSABLE HTML & CSS LAYOUT TEMPLATE
# ==========================================
PDF_REPORT_TEMPLATE = """
{html_body}
"""
def export_to_pdf(llm_response: str, output_filename: str = "output.pdf") -> None:
"""Converts structured LLM response with a fully clickable, indented manual TOC into a clean PDF."""
# 1. Standard markdown conversion with 'toc' extension enabled.
# This automatically adds unique ID anchors to your and elements
# so that clicking the TOC links will correctly jump down to that section.
html_body = markdown.markdown(
llm_response,
extensions=['fenced_code', 'tables', 'toc']
)
# 2. Inject a styling hook class wrapper around your Table of Contents list block
html_body = html_body.replace('Table of Contents
', 'Table of Contents
')
# Close the div wrapper cleanly right before the next main topic heading begins
html_body = html_body.replace('
1.', '
1.')
# 3. Format the final output document string structure
final_html_content = PDF_REPORT_TEMPLATE.format(html_body=html_body)
# 4. Generate the clickable PDF file
HTML(string=final_html_content).write_pdf(output_filename)