#!/usr/bin/env python3
"""
Convert Markdown to PDF with perfect UTF-8 support using Playwright
"""
import markdown
import os
from playwright.sync_api import sync_playwright
def convert_md_to_pdf(input_file, output_file):
"""Convert markdown file to PDF using browser rendering"""
# Read markdown file
with open(input_file, 'r', encoding='utf-8') as f:
md_content = f.read()
# Convert markdown to HTML
html = markdown.markdown(md_content, extensions=['tables', 'fenced_code', 'codehilite'])
# Add CSS styling
html_with_style = f"""
Freelance Dashboard - Technical Reference
{html}
"""
# Create temporary HTML file
temp_html = output_file.replace('.pdf', '_temp.html')
with open(temp_html, 'w', encoding='utf-8') as f:
f.write(html_with_style)
# Convert HTML to PDF using Playwright
with sync_playwright() as p:
browser = p.chromium.launch()
page = browser.new_page()
page.goto(f'file:///{os.path.abspath(temp_html)}')
page.pdf(
path=output_file,
format='A4',
margin={
'top': '2cm',
'right': '2cm',
'bottom': '2cm',
'left': '2cm'
},
print_background=True
)
browser.close()
# Clean up temporary HTML
if os.path.exists(temp_html):
os.remove(temp_html)
print(f"PDF created successfully: {output_file}")
print(f"File size: {os.path.getsize(output_file) / 1024:.2f} KB")
if __name__ == '__main__':
input_file = r'C:\Users\alexi\Documents\projects\freelance-dashboard\TECHNICAL_REFERENCE_EN.md'
output_file = r'C:\Users\alexi\Documents\projects\freelance-dashboard\TECHNICAL_REFERENCE_EN.pdf'
if os.path.exists(input_file):
convert_md_to_pdf(input_file, output_file)
else:
print(f"Input file not found: {input_file}")