""" Export API for converting HTML/Markdown to PDF and DOCX This module provides endpoints for exporting content from the mobile/web app to various formats (PDF, DOCX, HTML, Markdown). """ from pathlib import Path from io import BytesIO from typing import Optional from fastapi import APIRouter, HTTPException, Depends, Request from fastapi.responses import Response from pydantic import BaseModel, Field from urllib.parse import quote from core.utils.auth_utils import verify_and_get_user_id_from_jwt try: from weasyprint import HTML, CSS except (ImportError, OSError) as e: weasyprint_available = False print(f"[WARNING] WeasyPrint not available: {e}") print("[INFO] To fix on macOS, run: export DYLD_FALLBACK_LIBRARY_PATH=$(brew --prefix)/lib:$DYLD_FALLBACK_LIBRARY_PATH") else: weasyprint_available = True try: from docx import Document from docx.shared import Inches, Pt, RGBColor from docx.enum.text import WD_ALIGN_PARAGRAPH except ImportError: docx_available = False else: docx_available = True try: from bs4 import BeautifulSoup except ImportError: beautifulsoup_available = False else: beautifulsoup_available = True router = APIRouter(prefix="/export", tags=["export"]) class ExportRequest(BaseModel): """Request model for export endpoints""" content: str = Field(..., description="HTML content to export") fileName: str = Field(..., description="Base filename (without extension)") class ExportResponse(BaseModel): """Response model for export endpoints""" success: bool message: str filename: Optional[str] = None # Professional PDF styles matching the Next.js implementation PDF_STYLES = """ * { margin: 0; padding: 0; box-sizing: border-box; } body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif; font-size: 11pt; line-height: 1.6; color: #1a1a1a; padding: 0; margin: 0; background: #fff; } h1, h2, h3, h4, h5, h6 { font-weight: 600; line-height: 1.3; color: #111; letter-spacing: -0.02em; page-break-after: avoid; } h1 { font-size: 18pt; margin: 24pt 0 12pt 0; padding-bottom: 6pt; border-bottom: 1pt solid #e0e0e0; } h1:first-child { margin-top: 0; } h2 { font-size: 15pt; margin: 20pt 0 10pt 0; } h2:first-child { margin-top: 0; } h3 { font-size: 13pt; margin: 16pt 0 8pt 0; } h3:first-child { margin-top: 0; } h4 { font-size: 11pt; margin: 14pt 0 6pt 0; } h4:first-child { margin-top: 0; } h5 { font-size: 11pt; margin: 12pt 0 4pt 0; } h5:first-child { margin-top: 0; } h6 { font-size: 10pt; margin: 12pt 0 4pt 0; color: #555; text-transform: uppercase; letter-spacing: 0.5pt; } h6:first-child { margin-top: 0; } p { margin: 8pt 0; line-height: 1.65; } p:first-child { margin-top: 0; } p:last-child { margin-bottom: 0; } strong, b { font-weight: 600; } em, i { font-style: italic; } u { text-decoration: underline; } s, strike, del { text-decoration: line-through; color: #666; } a { color: #0066cc; text-decoration: underline; } ul, ol { margin: 10pt 0; padding-left: 28pt; } ul:first-child, ol:first-child { margin-top: 0; } ul:last-child, ol:last-child { margin-bottom: 0; } li { margin: 4pt 0; line-height: 1.5; padding-left: 4pt; } li > ul, li > ol { margin: 4pt 0; } blockquote { margin: 12pt 0; padding: 8pt 12pt; border-left: 3pt solid #e0e0e0; background: #fafafa; color: #555; font-style: italic; border-radius: 0 4pt 4pt 0; } code { font-family: 'Courier New', Consolas, 'Lucida Console', monospace; font-size: 10pt; background: #f4f4f5; padding: 2pt 4pt; border-radius: 2pt; color: #1a1a1a; } pre { margin: 12pt 0; padding: 12pt; background: #f4f4f5; border: 1pt solid #e4e4e7; border-radius: 4pt; overflow-x: auto; font-size: 9.5pt; line-height: 1.5; page-break-inside: avoid; } pre code { background: none; padding: 0; border-radius: 0; } table { width: 100%; margin: 14pt 0; border-collapse: collapse; font-size: 10.5pt; page-break-inside: avoid; } th { padding: 8pt 10pt; border: 1pt solid #d0d0d0; text-align: left; font-weight: 600; background: #f8f9fa; } td { padding: 8pt 10pt; border: 1pt solid #d0d0d0; text-align: left; vertical-align: top; } hr { border: none; border-top: 1pt solid #e0e0e0; margin: 20pt 0; } img { max-width: 100%; height: auto; display: block; margin: 12pt 0; page-break-inside: avoid; } @media print { body { font-size: 11pt; -webkit-print-color-adjust: exact; print-color-adjust: exact; } pre { white-space: pre-wrap; word-wrap: break-word; page-break-inside: avoid; } h1, h2, h3, h4, h5, h6 { page-break-after: avoid; } table { page-break-inside: avoid; } img { page-break-inside: avoid; } tr { page-break-inside: avoid; } } @page { size: A4; margin: 20mm; } """ def sanitize_filename(name: str) -> str: """Sanitize filename for safe file system use""" import re return re.sub(r'[^\w\s-]', '', name).strip()[:100] or 'document' def preprocess_html(html: str) -> str: """Preprocess HTML for better conversion""" import re if not html or not isinstance(html, str): return '
' # If content is a full HTML document, extract just the body content # This prevents nested HTML documents when we wrap it later if ']*>(.*?)