Export a markdown file to PDF using Jinja templates and WeasyPrint. Renders markdown through the template system and converts to PDF. Supports metadata like title, author, client, date via YAML frontmatter or arguments. Triggers: "export to pdf", "render pdf", "convert to pdf", "make pdf", "export document as pdf", "pdf export", "generate pdf".
Installer avec Codex ou Claude Copiez ce prompt, collez-le dans Codex, Claude ou un autre assistant, puis laissez-le vérifier la page du skill et l'installer pour vous.
Une commande directe contourne le prompt de vérification. Examinez la source avant de l'exécuter.
Export a markdown file to PDF using Jinja templates and WeasyPrint. Renders markdown through the template system and converts to PDF. Supports metadata like title, author, client, date via YAML frontmatter or arguments. Triggers: "export to pdf", "render pdf", "convert to pdf", "make pdf", "export document as pdf", "pdf export", "generate pdf".
Export to PDF
Export markdown files to professionally styled PDF documents using Jinja2 templates and WeasyPrint.
from weasyprint import HTML, CSS
# Create HTML document with base_url for resolving relative paths (logo, css)
html_doc = HTML(string=html_string, base_url=str(template_path))
# Render to PDF
html_doc.write_pdf(output_path)
Complete Render Function
#!/usr/bin/env python3"""Render markdown to PDF using templates and WeasyPrint."""import re
from pathlib import Path
from datetime import date
import markdown
from jinja2 import Environment, FileSystemLoader
from weasyprint import HTML
BASE_DIR = Path("/Users/john/Documents/Workspace/2Lines/knowledge-base")
TEMPLATES_DIR = BASE_DIR / "_templates"defexport_to_pdf(
markdown_file: str,
template_name: str = "2lines-external",
output_path: str = None,
**options
) -> Path:
"""
Export a markdown file to PDF.
Args:
markdown_file: Path to markdown file (relative to BASE_DIR or absolute)
template_name: Template directory name
output_path: Output PDF file path (optional)
**options: Metadata options (title, author, client, etc.)
Returns:
Path to the generated PDF file
"""# Resolve markdown path
md_path = Path(markdown_file)
ifnot md_path.is_absolute():
md_path = BASE_DIR / md_path
ifnot md_path.exists():
raise FileNotFoundError(f"Markdown file not found: {md_path}")
# Read markdown content
md_content = md_path.read_text()
# Parse YAML frontmatter if present
frontmatter = {}
content = md_content
if md_content.startswith('---'):
match = re.match(r'^---\n(.*?)\n---\n', md_content, re.DOTALL)
ifmatch:
try:
import yaml
frontmatter = yaml.safe_load(match.group(1)) or {}
except:
pass
content = md_content[match.end():]
# Convert markdown to HTML
md = markdown.Markdown(extensions=[
'tables',
'fenced_code',
'codehilite',
'toc',
])
html_content = md.convert(content)
# Extract table of contents
toc_html = md.toc
# Build context (frontmatter, then options override)
context = {
**frontmatter,
**{k: v for k, v in options.items() if v isnotNone},
'content': html_content,
'toc': toc_html,
}
# Set defaultsif'title'notin context:
context['title'] = md_path.stem.replace('-', ' ').title()
if'date'notin context:
context['date'] = date.today().isoformat()
# Load and render template
template_path = TEMPLATES_DIR / template_name
ifnot template_path.exists():
raise FileNotFoundError(f"Template not found: {template_path}")
env = Environment(loader=FileSystemLoader(str(template_path)))
template = env.get_template('base.html')
html_string = template.render(**context)
# Determine output pathif output_path:
out_path = Path(output_path)
ifnot out_path.is_absolute():
out_path = BASE_DIR / out_path
else:
out_path = md_path.with_suffix('.pdf')
out_path.parent.mkdir(parents=True, exist_ok=True)
# Convert to PDF using WeasyPrint# base_url allows WeasyPrint to resolve relative paths (logo.svg, style.css)
html_doc = HTML(string=html_string, base_url=str(template_path) + '/')
html_doc.write_pdf(out_path)
return out_path
Execution Steps
When the user invokes /export-to-pdf, execute:
Parse the request - Extract file path, template name, and options
Verify dependencies - Check that markdown, jinja2, and weasyprint are installed
Run the export - Use Bash to execute Python with the render logic
Report results - Show the output PDF path
Error Handling
Error
Response
File not found
Report error with suggestions for correct path
Template not found
List available templates
Missing dependencies
Show pip install markdown jinja2 weasyprint
WeasyPrint error
Show error message (often related to missing system fonts)