[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6HXGCP5687A2W86RMY2GEGK":3,"skill-same:01M6HXGCP5687A2W86RMY2GEGK":78},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":26,"publishedAt":39,"linkOnly":40,"markdownContent":41,"markdownBody":42,"frontMatter":43,"refName":44,"commitSha":45,"skillDirectory":46,"forksCount":47,"repositoryHtmlUrl":48,"repositoryHomepageUrl":6,"ownerHtmlUrl":49,"ownerBlogUrl":50,"ownerDescription":6,"updatedAt":51,"install":52,"resources":65},"01M6HXGCP5687A2W86RMY2GEGK","document-gen-resilient-multiformat",null,"Resilient multi-format document generation with environment checks, auto-sanitization, and fallback engines","HKUDS\u002FAgentPilot","HKUDS","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F118165258?v=4","01M6HW8VRNZP64G0P4MVJW2KKQ","✨Data Intelligence Lab@HKU✨","01M6HW8VWZVHBRHYH3T330PFWV",8029,"MIT","https:\u002F\u002Fgithub.com\u002FHKUDS\u002FAgentPilot\u002Fblob\u002Fmain\u002Fopenspace\u002Flegacy\u002Fv1\u002Fgdpval_bench\u002Fskills\u002Fdocument-gen-fallback-enhanced-enhanced-618c9b\u002FSKILL.md",[18,23],{"categoryNo":19,"categoryName":20,"taxonomyType":21,"taxonomyTypeDesc":22},"01JBSEEDCAT000000000000002","文档处理","SCENARIO","使用场景",{"categoryNo":24,"categoryName":25,"taxonomyType":21,"taxonomyTypeDesc":22},"01JBSEEDCAT000000000000023","Skill与智能体开发",[27,28,29,30,31,32,33,34,35,36,37,38],"document","document gen resilient multiformat","document gen resilient","format","environment","auto","fallback","generation","multi","document generation","with","sanitization","2026-11-10 10:12:30",false,"---\nname: document-gen-resilient-multiformat\ndescription: Resilient multi-format document generation with environment checks, auto-sanitization, and fallback engines\n---\n\n# Resilient Document Generation Workflow (Multi-Format + Unicode-Safe)\n\n## When to Use\n\nUse this skill when generating documents in multiple formats (`.docx`, `.pdf`, `.html`) and you need:\n- **Reliable execution** with pre-flight environment verification\n- **Automatic Unicode handling** based on target format\n- **Fallback options** when primary tools (pandoc\u002FLaTeX) are unavailable\n- **Clear error isolation** through discrete, observable steps\n\n**Trigger this workflow when:**\n- `shell_agent` returns unknown\u002Funclear errors on document generation\n- You need multiple output formats from one source\n- Documents contain special characters, symbols, or non-ASCII text\n- Previous PDF generation attempts failed due to encoding or missing dependencies\n\n## Pre-Flight Environment Check\n\n**Before starting**, verify your environment has the required tools:\n\n```\nrun_shell\ncommand: which pandoc && pandoc --version | head -1\n```\n\n```\nrun_shell\ncommand: which pdflatex || which xelatex || which wkhtmltopdf || echo \"No PDF engine found\"\n```\n\n```\nrun_shell\ncommand: python3 -c \"import fpdf; print('fpdf2 available')\" 2>\u002Fdev\u002Fnull || echo \"fpdf2 not available\"\n```\n\n```\nrun_shell\ncommand: python3 -c \"import reportlab; print('reportlab available')\" 2>\u002Fdev\u002Fnull || echo \"reportlab not available\"\n```\n\n**If pandoc is missing:** Install via `apt-get install pandoc` or `brew install pandoc`\n\n**If no PDF engine found:** Choose fallback approach:\n- Install LaTeX: `apt-get install texlive-latex-recommended texlive-fonts-recommended`\n- Or use wkhtmltopdf: `apt-get install wkhtmltopdf`\n- Or use Python fallback (fpdf2\u002Freportlab) - see Alternative PDF Generation section\n\n## Core Technique\n\nSplit the workflow into discrete, observable steps with automatic format detection:\n1. **Environment check** → Verify tools are available\n2. **Content creation** → Use `write_file` to create source Markdown\n3. **Auto-sanitization** → Conditionally sanitize based on target format (PDF needs it, DOCX\u002FHTML don't)\n4. **Format conversion** → Use appropriate tool for each format with fallback options\n5. **Verification** → Check output files exist and validate content\n\n## ⚠️ Unicode & Format Compatibility Matrix\n\n| Format | Unicode Support | Sanitization Needed | Recommended Engine |\n|--------|-----------------|---------------------|-------------------|\n| `.docx` | Excellent | No | pandoc (default) |\n| `.html` | Excellent | No | pandoc (default) |\n| `.pdf` | Limited (LaTeX) | **Yes** | xelatex > pdflatex > wkhtmltopdf > fpdf2 |\n| `.pptx` | Good | No | pandoc (if available) or python-pptx |\n\n### Critical Unicode Characters for PDF\n\n| Character | Issue | Safe Replacement |\n|-----------|-------|------------------|\n| `—` (em dash) | May not render | `--` or `-` |\n| `–` (en dash) | May not render | `-` |\n| `\" \"` (curly quotes) | Encoding errors | `\" \"` (straight quotes) |\n| `' '` (curly apostrophe) | Encoding errors | `'` (straight apostrophe) |\n| `…` (ellipsis) | May not render | `...` |\n| `→` `←` `↑` `↓` (arrows) | LaTeX incompatibility | `->` `\u003C-` `^` `v` |\n| `✓` `✗` (checkmarks) | May not render | `[x]` `[ ]` |\n| `★` `●` (symbols) | May not render | `*` `-` |\n| `©` `®` `™` | May require packages | `(c)` `(r)` `(tm)` |\n| Non-ASCII letters (é, ñ, ü) | Font-dependent | Use xeLaTeX or replace |\n\n## Step-by-Step Workflow\n\n### Step 0: Pre-Flight Check\n\nVerify environment before proceeding:\n\n```\nrun_shell\ncommand: pandoc --version >\u002Fdev\u002Fnull 2>&1 && echo \"PANDOC_OK\" || echo \"PANDOC_MISSING\"\n```\n\n**If PANDOC_MISSING**: Either install pandoc or use Alternative PDF Generation (Python-based)\n\n### Step 1: Create Source Content with write_file\n\nWrite your document content as Markdown to a source file:\n\n```\nwrite_file\npath: \u002Ftmp\u002Fdocument_source.md\ncontent: |\n  # Document Title\n  \n  ## Section 1\n  Content with original unicode characters...\n  \n  ## Section 2\n  More content...\n```\n\n### Step 2: Conditional Unicode Sanitization\n\n**Only sanitize if generating PDF**. Create sanitized version for PDF conversion:\n\n```\nwrite_file\npath: \u002Ftmp\u002Fdocument_source_sanitized.md\ncontent: |\n  # Document Title\n  \n  ## Section 1\n  Content with unicode replaced (em-dash -> --, curly quotes -> straight, etc.)\n  \n  ## Section 2\n  More content...\n```\n\n**Optional: Use sanitization script** (see Unicode Sanitization Script section below):\n\n```\nrun_shell\ncommand: .\u002Fsanitize_for_pdf.sh \u002Ftmp\u002Fdocument_source.md \u002Ftmp\u002Fdocument_source_sanitized.md\n```\n\n**Note**: Keep the original unsanitized file for DOCX\u002FHTML conversion (these formats handle Unicode better).\n\n### Step 3: Convert to Target Formats with run_shell\n\nUse appropriate commands for each format. **Use sanitized source for PDF, original for others**.\n\n**DOCX (from original):**\n```\nrun_shell\ncommand: pandoc \u002Ftmp\u002Fdocument_source.md -o output.docx\n```\n\n**PDF (from sanitized, with engine priority):**\n```\nrun_shell\ncommand: pandoc \u002Ftmp\u002Fdocument_source_sanitized.md -o output.pdf --pdf-engine=xelatex\n```\n\n**If xelatex fails, try pdflatex:**\n```\nrun_shell\ncommand: pandoc \u002Ftmp\u002Fdocument_source_sanitized.md -o output.pdf --pdf-engine=pdflatex\n```\n\n**If LaTeX engines fail, try wkhtmltopdf:**\n```\nrun_shell\ncommand: pandoc \u002Ftmp\u002Fdocument_source_sanitized.md -o output.pdf --pdf-engine=wkhtmltopdf\n```\n\n**HTML (from original):**\n```\nrun_shell\ncommand: pandoc \u002Ftmp\u002Fdocument_source.md -o output.html\n```\n\n### Step 4: Verify Outputs\n\nCheck that files were created and have content:\n\n```\nrun_shell\ncommand: ls -lh output.* && file output.*\n```\n\n```\nrun_shell\ncommand: test -s output.pdf && echo \"PDF has content\" || echo \"PDF is empty\"\n```\n\n## PDF Engine Decision Tree\n\n```\nIs pandoc available?\n├─ NO → Use Python fallback (fpdf2 or reportlab)\n└─ YES → Is LaTeX available?\n    ├─ YES (xelatex) → Use: pandoc --pdf-engine=xelatex (best Unicode)\n    ├─ YES (pdflatex) → Use: pandoc --pdf-engine=pdflatex + sanitization\n    ├─ YES (wkhtmltopdf) → Use: pandoc --pdf-engine=wkhtmltopdf\n    └─ NO → Install LaTeX or use Python fallback\n```\n\n## Alternative PDF Generation (Python Fallback)\n\nWhen pandoc or LaTeX is unavailable, use Python libraries directly:\n\n### Option A: fpdf2 (Simple, fast)\n\n```\nrun_shell\ncommand: python3 \u003C\u003C 'EOF'\nfrom fpdf import FPDF\npdf = FPDF()\npdf.add_page()\npdf.set_font(\"Arial\", size=12)\n# Note: fpdf2 has limited Unicode support - use Latin-1 or embed fonts\npdf.cell(200, 10, txt=\"Document Title\", ln=True, align='C')\npdf.output(\"output.pdf\")\nEOF\n```\n\n### Option B: reportlab (More control, better Unicode)\n\n```\nrun_shell\ncommand: python3 \u003C\u003C 'EOF'\nfrom reportlab.lib.pagesizes import letter\nfrom reportlab.pdfgen import canvas\nfrom reportlab.pdfbase import pdfmetrics\nfrom reportlab.pdfbase.ttfonts import TTFont\n\n# Register a Unicode font if needed\n# pdfmetrics.registerFont(TTFont('UnicodeFont', 'path\u002Fto\u002Ffont.ttf'))\n\nc = canvas.Canvas(\"output.pdf\", pagesize=letter)\nc.drawString(100, 750, \"Document Title\")\nc.save()\nEOF\n```\n\n### Option C: Markdown to PDF with Markdown2 + ReportLab\n\n```\nrun_shell\ncommand: python3 \u003C\u003C 'EOF'\nimport markdown\nfrom reportlab.lib.pagesizes import letter\nfrom reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer\nfrom reportlab.lib.styles import getSampleStyleSheet\n\n# Read markdown\nwith open('\u002Ftmp\u002Fdocument_source.md', 'r', encoding='utf-8') as f:\n    md_content = f.read()\n\n# Convert to HTML\nhtml_content = markdown.markdown(md_content)\n\n# Create PDF\ndoc = SimpleDocTemplate(\"output.pdf\", pagesize=letter)\nstyles = getSampleStyleSheet()\nstory = []\n\n# Parse HTML and add to story (simplified - use html2text for production)\nstory.append(Paragraph(\"Document Content\", styles['Normal']))\n\ndoc.build(story)\nprint(\"PDF created successfully\")\nEOF\n```\n\n## Complete Example\n\n```markdown\n# Generate Multi-Format Report\n\n## Step 0: Check environment\nrun_shell\ncommand: pandoc --version >\u002Fdev\u002Fnull 2>&1 && echo \"PANDOC_OK\" || echo \"PANDOC_MISSING\"\n\n## Step 1: Write Markdown source\nwrite_file\npath: \u002Ftmp\u002Freport.md\ncontent: |\n  # Quarterly Report\n  \n  ## Executive Summary\n  Performance metrics and analysis...\n  \n  ## Key Findings\n  — Major finding with em-dash\n  \"Quote\" with curly quotes\n  ✓ Completed items\n\n## Step 2: Create sanitized version (for PDF only)\nwrite_file\npath: \u002Ftmp\u002Freport_sanitized.md\ncontent: |\n  # Quarterly Report\n  \n  ## Executive Summary\n  Performance metrics and analysis...\n  \n  ## Key Findings\n  -- Major finding with em-dash\n  \"Quote\" with straight quotes\n  [x] Completed items\n\n## Step 3: Convert to DOCX (from original)\nrun_shell\ncommand: pandoc \u002Ftmp\u002Freport.md -o report.docx\n\n## Step 4: Convert to PDF (from sanitized, with xelatex)\nrun_shell\ncommand: pandoc \u002Ftmp\u002Freport_sanitized.md -o report.pdf --pdf-engine=xelatex\n\n## Step 5: Convert to HTML (from original)\nrun_shell\ncommand: pandoc \u002Ftmp\u002Freport.md -o report.html\n\n## Step 6: Verify all outputs\nrun_shell\ncommand: ls -lh report.* && echo \"All files created\"\n```\n\n## Error Handling & Recovery\n\n| Error | Likely Cause | Recovery Action |\n|-------|-------------|-----------------|\n| `pandoc: command not found` | Pandoc not installed | Install pandoc or use Python fallback |\n| `pdflatex not found` | LaTeX missing | Use `--pdf-engine=xelatex` or `wkhtmltopdf` |\n| `! LaTeX Error: File X.sty not found` | Missing LaTeX package | Install package or use xelatex\u002Fwkhtmltopdf |\n| `Encoding error` | Unicode in PDF | Use sanitized file + xelatex engine |\n| `wkhtmltopdf: command not found` | wkhtmltopdf missing | Install or use xelatex\u002Fpdflatex |\n| `PDF is empty (0 bytes)` | Conversion silently failed | Check pandoc stderr, try alternative engine |\n| `fpdf2 Unicode error` | Non-Latin characters | Use reportlab with Unicode font or sanitize |\n\n### Recovery Workflow\n\n1. **Check error message** for specific tool\u002Fengine failure\n2. **Try next engine in priority**: xelatex → pdflatex → wkhtmltopdf → fpdf2\u002Freportlab\n3. **If all pandoc attempts fail**: Switch to Python fallback (fpdf2\u002Freportlab)\n4. **If Unicode issues persist**: Apply stricter sanitization or use xelatex with Unicode font\n5. **Document which approach succeeded** for future reference\n\n## Unicode Sanitization Script (Reusable)\n\nSave as `sanitize_for_pdf.sh`:\n\n```bash\n#!\u002Fbin\u002Fbash\n# sanitize_for_pdf.sh - Replace problematic unicode chars for LaTeX\u002FPDF\nif [ -z \"$1\" ]; then\n  echo \"Usage: $0 \u003Cinput.md> [output.md]\"\n  exit 1\nfi\nINPUT=\"$1\"\nOUTPUT=\"${2:-${1%.md}_sanitized.md}\"\n\nsed -e 's\u002F—\u002F--\u002Fg' \\\n    -e 's\u002F–\u002F-\u002Fg' \\\n    -e 's\u002F\"([^\"]*)\"\u002F\"\\1\"\u002Fg' \\\n    -e \"s\u002F'([^']*)\u002F'\\1'\u002Fg\" \\\n    -e 's\u002F…\u002F...\u002Fg' \\\n    -e 's\u002F→\u002F->\u002Fg' \\\n    -e 's\u002F←\u002F\u003C-\u002Fg' \\\n    -e 's\u002F✓\u002F[x]\u002Fg' \\\n    -e 's\u002F✗\u002F[ ]\u002Fg' \\\n    -e 's\u002F©\u002F(c)\u002Fg' \\\n    -e 's\u002F®\u002F(r)\u002Fg' \\\n    -e 's\u002F™\u002F(tm)\u002Fg' \\\n    \"$INPUT\" > \"$OUTPUT\"\n\necho \"Sanitized: $INPUT -> $OUTPUT\"\n```\n\nMake executable: `chmod +x sanitize_for_pdf.sh`\n\nUsage:\n```\nrun_shell\ncommand: .\u002Fsanitize_for_pdf.sh \u002Ftmp\u002Fdocument_source.md \u002Ftmp\u002Fdocument_source_sanitized.md\n```\n\n## Common pandoc Commands Reference\n\n```bash\n# Markdown to Word\npandoc input.md -o output.docx\n\n# Markdown to PDF (LaTeX - default pdflatex)\npandoc input.md -o output.pdf\n\n# Markdown to PDF with xelatex (best Unicode support)\npandoc input.md -o output.pdf --pdf-engine=xelatex\n\n# Markdown to PDF with wkhtmltopdf (HTML-based, no LaTeX)\npandoc input.md -o output.pdf --pdf-engine=wkhtmltopdf\n\n# Markdown to HTML\npandoc input.md -o output.html\n\n# With metadata\npandoc input.md -o output.pdf --metadata title=\"Document Title\"\n\n# With custom reference doc (DOCX)\npandoc input.md -o output.docx --reference-doc=template.docx\n\n# With custom template (HTML\u002FPDF)\npandoc input.md --template=template.html -o output.html\n\n# Force UTF-8 input\npandoc -f markdown+utf8 input.md -o output.pdf\n```\n\n## Troubleshooting Quick Reference\n\n**PDF generation fails with encoding error:**\n- Use sanitized markdown file\n- Try `--pdf-engine=xelatex` for better Unicode support\n- Add `-f markdown+utf8` to pandoc command\n\n**PDF generation fails: LaTeX not found:**\n- Install: `apt-get install texlive-latex-recommended texlive-fonts-recommended`\n- Or use: `--pdf-engine=wkhtmltopdf`\n- Or use: Python fallback (fpdf2\u002Freportlab)\n\n**DOCX formatting issues:**\n- Add `--reference-doc=template.docx` for custom styles\n- Check markdown structure (headings, lists)\n\n**Unicode\u002Fencoding errors in any format:**\n- Ensure source file is UTF-8: `file -i source.md`\n- Add `-f markdown+utf8` to pandoc command\n- Use xelatex for PDF\n\n**Special characters not rendering in PDF:**\n- Use the character replacement table\n- Create sanitized version before PDF conversion\n- Try xelatex with Unicode font\n\n**Missing pandoc:**\n- Ubuntu\u002FDebian: `apt-get install pandoc`\n- macOS: `brew install pandoc`\n- Fallback: Use Python libraries directly\n\n## When to Use shell_agent vs Manual Workflow\n\n| Scenario | Recommended Approach |\n|----------|---------------------|\n| Simple DOCX\u002FHTML, no Unicode | `shell_agent` is fine |\n| PDF generation required | Manual workflow (this skill) |\n| Multiple formats from one source | Manual workflow (this skill) |\n| Heavy Unicode\u002Fspecial characters | Manual workflow with sanitization |\n| `shell_agent` failed with unknown error | Manual workflow (this skill) |\n| Need explicit error visibility | Manual workflow (this skill) |\n| Environment constraints (no pandoc) | Python fallback (this skill) |\n\n**After successful manual workflow**: You can attempt `shell_agent` for similar future tasks, but keep this workflow as your known-working fallback.\n\n## Related Skills\n\n- `document-gen-fallback`: Original fallback workflow (less Unicode guidance)\n- `write-file-fallback-report`: For when multiple tools fail simultaneously\n- `spreadsheet-direct-python`: For Excel\u002FCSV generation with Python\n\n## Skill Health & Metrics\n\n**Expected success rate**: 85%+ with proper environment setup\n**Fallback activation**: Use Python fallback if pandoc\u002FLaTeX unavailable\n**Verification**: Always verify output files exist AND have content (>0 bytes)\n*** End Files\n*** Begin Files\n","# Resilient Document Generation Workflow (Multi-Format + Unicode-Safe)\n\n## When to Use\n\nUse this skill when generating documents in multiple formats (`.docx`, `.pdf`, `.html`) and you need:\n- **Reliable execution** with pre-flight environment verification\n- **Automatic Unicode handling** based on target format\n- **Fallback options** when primary tools (pandoc\u002FLaTeX) are unavailable\n- **Clear error isolation** through discrete, observable steps\n\n**Trigger this workflow when:**\n- `shell_agent` returns unknown\u002Funclear errors on document generation\n- You need multiple output formats from one source\n- Documents contain special characters, symbols, or non-ASCII text\n- Previous PDF generation attempts failed due to encoding or missing dependencies\n\n## Pre-Flight Environment Check\n\n**Before starting**, verify your environment has the required tools:\n\n```\nrun_shell\ncommand: which pandoc && pandoc --version | head -1\n```\n\n```\nrun_shell\ncommand: which pdflatex || which xelatex || which wkhtmltopdf || echo \"No PDF engine found\"\n```\n\n```\nrun_shell\ncommand: python3 -c \"import fpdf; print('fpdf2 available')\" 2>\u002Fdev\u002Fnull || echo \"fpdf2 not available\"\n```\n\n```\nrun_shell\ncommand: python3 -c \"import reportlab; print('reportlab available')\" 2>\u002Fdev\u002Fnull || echo \"reportlab not available\"\n```\n\n**If pandoc is missing:** Install via `apt-get install pandoc` or `brew install pandoc`\n\n**If no PDF engine found:** Choose fallback approach:\n- Install LaTeX: `apt-get install texlive-latex-recommended texlive-fonts-recommended`\n- Or use wkhtmltopdf: `apt-get install wkhtmltopdf`\n- Or use Python fallback (fpdf2\u002Freportlab) - see Alternative PDF Generation section\n\n## Core Technique\n\nSplit the workflow into discrete, observable steps with automatic format detection:\n1. **Environment check** → Verify tools are available\n2. **Content creation** → Use `write_file` to create source Markdown\n3. **Auto-sanitization** → Conditionally sanitize based on target format (PDF needs it, DOCX\u002FHTML don't)\n4. **Format conversion** → Use appropriate tool for each format with fallback options\n5. **Verification** → Check output files exist and validate content\n\n## ⚠️ Unicode & Format Compatibility Matrix\n\n| Format | Unicode Support | Sanitization Needed | Recommended Engine |\n|--------|-----------------|---------------------|-------------------|\n| `.docx` | Excellent | No | pandoc (default) |\n| `.html` | Excellent | No | pandoc (default) |\n| `.pdf` | Limited (LaTeX) | **Yes** | xelatex > pdflatex > wkhtmltopdf > fpdf2 |\n| `.pptx` | Good | No | pandoc (if available) or python-pptx |\n\n### Critical Unicode Characters for PDF\n\n| Character | Issue | Safe Replacement |\n|-----------|-------|------------------|\n| `—` (em dash) | May not render | `--` or `-` |\n| `–` (en dash) | May not render | `-` |\n| `\" \"` (curly quotes) | Encoding errors | `\" \"` (straight quotes) |\n| `' '` (curly apostrophe) | Encoding errors | `'` (straight apostrophe) |\n| `…` (ellipsis) | May not render | `...` |\n| `→` `←` `↑` `↓` (arrows) | LaTeX incompatibility | `->` `\u003C-` `^` `v` |\n| `✓` `✗` (checkmarks) | May not render | `[x]` `[ ]` |\n| `★` `●` (symbols) | May not render | `*` `-` |\n| `©` `®` `™` | May require packages | `(c)` `(r)` `(tm)` |\n| Non-ASCII letters (é, ñ, ü) | Font-dependent | Use xeLaTeX or replace |\n\n## Step-by-Step Workflow\n\n### Step 0: Pre-Flight Check\n\nVerify environment before proceeding:\n\n```\nrun_shell\ncommand: pandoc --version >\u002Fdev\u002Fnull 2>&1 && echo \"PANDOC_OK\" || echo \"PANDOC_MISSING\"\n```\n\n**If PANDOC_MISSING**: Either install pandoc or use Alternative PDF Generation (Python-based)\n\n### Step 1: Create Source Content with write_file\n\nWrite your document content as Markdown to a source file:\n\n```\nwrite_file\npath: \u002Ftmp\u002Fdocument_source.md\ncontent: |\n  # Document Title\n  \n  ## Section 1\n  Content with original unicode characters...\n  \n  ## Section 2\n  More content...\n```\n\n### Step 2: Conditional Unicode Sanitization\n\n**Only sanitize if generating PDF**. Create sanitized version for PDF conversion:\n\n```\nwrite_file\npath: \u002Ftmp\u002Fdocument_source_sanitized.md\ncontent: |\n  # Document Title\n  \n  ## Section 1\n  Content with unicode replaced (em-dash -> --, curly quotes -> straight, etc.)\n  \n  ## Section 2\n  More content...\n```\n\n**Optional: Use sanitization script** (see Unicode Sanitization Script section below):\n\n```\nrun_shell\ncommand: .\u002Fsanitize_for_pdf.sh \u002Ftmp\u002Fdocument_source.md \u002Ftmp\u002Fdocument_source_sanitized.md\n```\n\n**Note**: Keep the original unsanitized file for DOCX\u002FHTML conversion (these formats handle Unicode better).\n\n### Step 3: Convert to Target Formats with run_shell\n\nUse appropriate commands for each format. **Use sanitized source for PDF, original for others**.\n\n**DOCX (from original):**\n```\nrun_shell\ncommand: pandoc \u002Ftmp\u002Fdocument_source.md -o output.docx\n```\n\n**PDF (from sanitized, with engine priority):**\n```\nrun_shell\ncommand: pandoc \u002Ftmp\u002Fdocument_source_sanitized.md -o output.pdf --pdf-engine=xelatex\n```\n\n**If xelatex fails, try pdflatex:**\n```\nrun_shell\ncommand: pandoc \u002Ftmp\u002Fdocument_source_sanitized.md -o output.pdf --pdf-engine=pdflatex\n```\n\n**If LaTeX engines fail, try wkhtmltopdf:**\n```\nrun_shell\ncommand: pandoc \u002Ftmp\u002Fdocument_source_sanitized.md -o output.pdf --pdf-engine=wkhtmltopdf\n```\n\n**HTML (from original):**\n```\nrun_shell\ncommand: pandoc \u002Ftmp\u002Fdocument_source.md -o output.html\n```\n\n### Step 4: Verify Outputs\n\nCheck that files were created and have content:\n\n```\nrun_shell\ncommand: ls -lh output.* && file output.*\n```\n\n```\nrun_shell\ncommand: test -s output.pdf && echo \"PDF has content\" || echo \"PDF is empty\"\n```\n\n## PDF Engine Decision Tree\n\n```\nIs pandoc available?\n├─ NO → Use Python fallback (fpdf2 or reportlab)\n└─ YES → Is LaTeX available?\n    ├─ YES (xelatex) → Use: pandoc --pdf-engine=xelatex (best Unicode)\n    ├─ YES (pdflatex) → Use: pandoc --pdf-engine=pdflatex + sanitization\n    ├─ YES (wkhtmltopdf) → Use: pandoc --pdf-engine=wkhtmltopdf\n    └─ NO → Install LaTeX or use Python fallback\n```\n\n## Alternative PDF Generation (Python Fallback)\n\nWhen pandoc or LaTeX is unavailable, use Python libraries directly:\n\n### Option A: fpdf2 (Simple, fast)\n\n```\nrun_shell\ncommand: python3 \u003C\u003C 'EOF'\nfrom fpdf import FPDF\npdf = FPDF()\npdf.add_page()\npdf.set_font(\"Arial\", size=12)\n# Note: fpdf2 has limited Unicode support - use Latin-1 or embed fonts\npdf.cell(200, 10, txt=\"Document Title\", ln=True, align='C')\npdf.output(\"output.pdf\")\nEOF\n```\n\n### Option B: reportlab (More control, better Unicode)\n\n```\nrun_shell\ncommand: python3 \u003C\u003C 'EOF'\nfrom reportlab.lib.pagesizes import letter\nfrom reportlab.pdfgen import canvas\nfrom reportlab.pdfbase import pdfmetrics\nfrom reportlab.pdfbase.ttfonts import TTFont\n\n# Register a Unicode font if needed\n# pdfmetrics.registerFont(TTFont('UnicodeFont', 'path\u002Fto\u002Ffont.ttf'))\n\nc = canvas.Canvas(\"output.pdf\", pagesize=letter)\nc.drawString(100, 750, \"Document Title\")\nc.save()\nEOF\n```\n\n### Option C: Markdown to PDF with Markdown2 + ReportLab\n\n```\nrun_shell\ncommand: python3 \u003C\u003C 'EOF'\nimport markdown\nfrom reportlab.lib.pagesizes import letter\nfrom reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer\nfrom reportlab.lib.styles import getSampleStyleSheet\n\n# Read markdown\nwith open('\u002Ftmp\u002Fdocument_source.md', 'r', encoding='utf-8') as f:\n    md_content = f.read()\n\n# Convert to HTML\nhtml_content = markdown.markdown(md_content)\n\n# Create PDF\ndoc = SimpleDocTemplate(\"output.pdf\", pagesize=letter)\nstyles = getSampleStyleSheet()\nstory = []\n\n# Parse HTML and add to story (simplified - use html2text for production)\nstory.append(Paragraph(\"Document Content\", styles['Normal']))\n\ndoc.build(story)\nprint(\"PDF created successfully\")\nEOF\n```\n\n## Complete Example\n\n```markdown\n# Generate Multi-Format Report\n\n## Step 0: Check environment\nrun_shell\ncommand: pandoc --version >\u002Fdev\u002Fnull 2>&1 && echo \"PANDOC_OK\" || echo \"PANDOC_MISSING\"\n\n## Step 1: Write Markdown source\nwrite_file\npath: \u002Ftmp\u002Freport.md\ncontent: |\n  # Quarterly Report\n  \n  ## Executive Summary\n  Performance metrics and analysis...\n  \n  ## Key Findings\n  — Major finding with em-dash\n  \"Quote\" with curly quotes\n  ✓ Completed items\n\n## Step 2: Create sanitized version (for PDF only)\nwrite_file\npath: \u002Ftmp\u002Freport_sanitized.md\ncontent: |\n  # Quarterly Report\n  \n  ## Executive Summary\n  Performance metrics and analysis...\n  \n  ## Key Findings\n  -- Major finding with em-dash\n  \"Quote\" with straight quotes\n  [x] Completed items\n\n## Step 3: Convert to DOCX (from original)\nrun_shell\ncommand: pandoc \u002Ftmp\u002Freport.md -o report.docx\n\n## Step 4: Convert to PDF (from sanitized, with xelatex)\nrun_shell\ncommand: pandoc \u002Ftmp\u002Freport_sanitized.md -o report.pdf --pdf-engine=xelatex\n\n## Step 5: Convert to HTML (from original)\nrun_shell\ncommand: pandoc \u002Ftmp\u002Freport.md -o report.html\n\n## Step 6: Verify all outputs\nrun_shell\ncommand: ls -lh report.* && echo \"All files created\"\n```\n\n## Error Handling & Recovery\n\n| Error | Likely Cause | Recovery Action |\n|-------|-------------|-----------------|\n| `pandoc: command not found` | Pandoc not installed | Install pandoc or use Python fallback |\n| `pdflatex not found` | LaTeX missing | Use `--pdf-engine=xelatex` or `wkhtmltopdf` |\n| `! LaTeX Error: File X.sty not found` | Missing LaTeX package | Install package or use xelatex\u002Fwkhtmltopdf |\n| `Encoding error` | Unicode in PDF | Use sanitized file + xelatex engine |\n| `wkhtmltopdf: command not found` | wkhtmltopdf missing | Install or use xelatex\u002Fpdflatex |\n| `PDF is empty (0 bytes)` | Conversion silently failed | Check pandoc stderr, try alternative engine |\n| `fpdf2 Unicode error` | Non-Latin characters | Use reportlab with Unicode font or sanitize |\n\n### Recovery Workflow\n\n1. **Check error message** for specific tool\u002Fengine failure\n2. **Try next engine in priority**: xelatex → pdflatex → wkhtmltopdf → fpdf2\u002Freportlab\n3. **If all pandoc attempts fail**: Switch to Python fallback (fpdf2\u002Freportlab)\n4. **If Unicode issues persist**: Apply stricter sanitization or use xelatex with Unicode font\n5. **Document which approach succeeded** for future reference\n\n## Unicode Sanitization Script (Reusable)\n\nSave as `sanitize_for_pdf.sh`:\n\n```bash\n#!\u002Fbin\u002Fbash\n# sanitize_for_pdf.sh - Replace problematic unicode chars for LaTeX\u002FPDF\nif [ -z \"$1\" ]; then\n  echo \"Usage: $0 \u003Cinput.md> [output.md]\"\n  exit 1\nfi\nINPUT=\"$1\"\nOUTPUT=\"${2:-${1%.md}_sanitized.md}\"\n\nsed -e 's\u002F—\u002F--\u002Fg' \\\n    -e 's\u002F–\u002F-\u002Fg' \\\n    -e 's\u002F\"([^\"]*)\"\u002F\"\\1\"\u002Fg' \\\n    -e \"s\u002F'([^']*)\u002F'\\1'\u002Fg\" \\\n    -e 's\u002F…\u002F...\u002Fg' \\\n    -e 's\u002F→\u002F->\u002Fg' \\\n    -e 's\u002F←\u002F\u003C-\u002Fg' \\\n    -e 's\u002F✓\u002F[x]\u002Fg' \\\n    -e 's\u002F✗\u002F[ ]\u002Fg' \\\n    -e 's\u002F©\u002F(c)\u002Fg' \\\n    -e 's\u002F®\u002F(r)\u002Fg' \\\n    -e 's\u002F™\u002F(tm)\u002Fg' \\\n    \"$INPUT\" > \"$OUTPUT\"\n\necho \"Sanitized: $INPUT -> $OUTPUT\"\n```\n\nMake executable: `chmod +x sanitize_for_pdf.sh`\n\nUsage:\n```\nrun_shell\ncommand: .\u002Fsanitize_for_pdf.sh \u002Ftmp\u002Fdocument_source.md \u002Ftmp\u002Fdocument_source_sanitized.md\n```\n\n## Common pandoc Commands Reference\n\n```bash\n# Markdown to Word\npandoc input.md -o output.docx\n\n# Markdown to PDF (LaTeX - default pdflatex)\npandoc input.md -o output.pdf\n\n# Markdown to PDF with xelatex (best Unicode support)\npandoc input.md -o output.pdf --pdf-engine=xelatex\n\n# Markdown to PDF with wkhtmltopdf (HTML-based, no LaTeX)\npandoc input.md -o output.pdf --pdf-engine=wkhtmltopdf\n\n# Markdown to HTML\npandoc input.md -o output.html\n\n# With metadata\npandoc input.md -o output.pdf --metadata title=\"Document Title\"\n\n# With custom reference doc (DOCX)\npandoc input.md -o output.docx --reference-doc=template.docx\n\n# With custom template (HTML\u002FPDF)\npandoc input.md --template=template.html -o output.html\n\n# Force UTF-8 input\npandoc -f markdown+utf8 input.md -o output.pdf\n```\n\n## Troubleshooting Quick Reference\n\n**PDF generation fails with encoding error:**\n- Use sanitized markdown file\n- Try `--pdf-engine=xelatex` for better Unicode support\n- Add `-f markdown+utf8` to pandoc command\n\n**PDF generation fails: LaTeX not found:**\n- Install: `apt-get install texlive-latex-recommended texlive-fonts-recommended`\n- Or use: `--pdf-engine=wkhtmltopdf`\n- Or use: Python fallback (fpdf2\u002Freportlab)\n\n**DOCX formatting issues:**\n- Add `--reference-doc=template.docx` for custom styles\n- Check markdown structure (headings, lists)\n\n**Unicode\u002Fencoding errors in any format:**\n- Ensure source file is UTF-8: `file -i source.md`\n- Add `-f markdown+utf8` to pandoc command\n- Use xelatex for PDF\n\n**Special characters not rendering in PDF:**\n- Use the character replacement table\n- Create sanitized version before PDF conversion\n- Try xelatex with Unicode font\n\n**Missing pandoc:**\n- Ubuntu\u002FDebian: `apt-get install pandoc`\n- macOS: `brew install pandoc`\n- Fallback: Use Python libraries directly\n\n## When to Use shell_agent vs Manual Workflow\n\n| Scenario | Recommended Approach |\n|----------|---------------------|\n| Simple DOCX\u002FHTML, no Unicode | `shell_agent` is fine |\n| PDF generation required | Manual workflow (this skill) |\n| Multiple formats from one source | Manual workflow (this skill) |\n| Heavy Unicode\u002Fspecial characters | Manual workflow with sanitization |\n| `shell_agent` failed with unknown error | Manual workflow (this skill) |\n| Need explicit error visibility | Manual workflow (this skill) |\n| Environment constraints (no pandoc) | Python fallback (this skill) |\n\n**After successful manual workflow**: You can attempt `shell_agent` for similar future tasks, but keep this workflow as your known-working fallback.\n\n## Related Skills\n\n- `document-gen-fallback`: Original fallback workflow (less Unicode guidance)\n- `write-file-fallback-report`: For when multiple tools fail simultaneously\n- `spreadsheet-direct-python`: For Excel\u002FCSV generation with Python\n\n## Skill Health & Metrics\n\n**Expected success rate**: 85%+ with proper environment setup\n**Fallback activation**: Use Python fallback if pandoc\u002FLaTeX unavailable\n**Verification**: Always verify output files exist AND have content (>0 bytes)\n*** End Files\n*** Begin Files\n",{"name":5,"description":7},"main","6b84b0689ca0d9e7b1e4061188ff6b60758e0f8a","openspace\u002Flegacy\u002Fv1\u002Fgdpval_bench\u002Fskills\u002Fdocument-gen-fallback-enhanced-enhanced-618c9b",944,"https:\u002F\u002Fgithub.com\u002FHKUDS\u002FAgentPilot","https:\u002F\u002Fgithub.com\u002FHKUDS","https:\u002F\u002Fsites.google.com\u002Fview\u002Fchaoh","2026-11-12 22:26:39",{"source":8,"skillName":5,"commands":53,"prompt":63,"zipAvailable":64},[54,57,60],{"tool":55,"command":56},"npx","npx skills add HKUDS\u002FAgentPilot --skill document-gen-resilient-multiformat",{"tool":58,"command":59},"bunx","bunx skills add HKUDS\u002FAgentPilot --skill document-gen-resilient-multiformat",{"tool":61,"command":62},"pnpm","pnpm dlx skills add HKUDS\u002FAgentPilot --skill document-gen-resilient-multiformat","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FHKUDS\u002FAgentPilot\u002Fblob\u002Fmain\u002Fopenspace\u002Flegacy\u002Fv1\u002Fgdpval_bench\u002Fskills\u002Fdocument-gen-fallback-enhanced-enhanced-618c9b\u002FSKILL.md",true,[66,72],{"path":67,"resourceType":68,"resourceTypeDesc":69,"sizeBytes":70,"sourceHtmlUrl":71},".skill_id","OTHER","其他",60,"https:\u002F\u002Fgithub.com\u002FHKUDS\u002FAgentPilot\u002Fblob\u002Fmain\u002Fopenspace\u002Flegacy\u002Fv1\u002Fgdpval_bench\u002Fskills\u002Fdocument-gen-fallback-enhanced-enhanced-618c9b\u002F.skill_id",{"path":73,"resourceType":74,"resourceTypeDesc":75,"sizeBytes":76,"sourceHtmlUrl":77},"sanitize_for_pdf.sh","SCRIPT","脚本",1215,"https:\u002F\u002Fgithub.com\u002FHKUDS\u002FAgentPilot\u002Fblob\u002Fmain\u002Fopenspace\u002Flegacy\u002Fv1\u002Fgdpval_bench\u002Fskills\u002Fdocument-gen-fallback-enhanced-enhanced-618c9b\u002Fsanitize_for_pdf.sh",[79,98,116,137,161,184],{"skillNo":80,"name":81,"nameZh":6,"description":82,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":83,"categories":84,"keywords":85,"publishedAt":39},"01M6HYB297NDABRERJRVG0K8R0","agentpilot","Set up AgentPilot and use its single entry to prepare missing inputs and run configured RSI experiments. Use when the user requests AgentPilot installation or work with AgentPilot.","https:\u002F\u002Fgithub.com\u002FHKUDS\u002FAgentPilot\u002Fblob\u002Fmain\u002Fplugins\u002Fagentpilot\u002Fskills\u002Fagentpilot\u002FSKILL.md",[],[81,86,87,37,88,89,90,91,92,93,94,95,96,97],"prepare","requests","missing","installation","rsi","up","use","user","work","SET","run","experiments",{"skillNo":99,"name":100,"nameZh":6,"description":101,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":102,"categories":103,"keywords":104,"publishedAt":39},"01M6HYAYWXTTE1J7DJM0MFNQ4H","remember","Review auto-memory entries and propose promotions to OPENSPACE.md, OPENSPACE.local.md, or retained auto-memory topics; detect duplicates, stale facts, conflicts, and ambiguous entries before making changes.","https:\u002F\u002Fgithub.com\u002FHKUDS\u002FAgentPilot\u002Fblob\u002Fmain\u002Fopenspace\u002Fopenspace\u002Fskills\u002Fremember\u002FSKILL.md",[],[100,105,106,32,107,108,109,110,111,112,113,114,115],"memory","review","openspace","changes","facts","detect","entries","local","conflicts","stale","duplicates",{"skillNo":117,"name":118,"nameZh":6,"description":119,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":120,"categories":121,"keywords":123,"publishedAt":39},"01M6HYAVMPM4SBDV60R2B5HPV8","skill-discovery","Search reusable OpenSpace skills locally, and browse cloud packages step by step when a cloud skill may help. Reusing proven skills saves tokens, improves reliability, and extends your capabilities beyond built-in tools.","https:\u002F\u002Fgithub.com\u002FHKUDS\u002FAgentPilot\u002Fblob\u002Fmain\u002Fopenspace\u002Fopenspace\u002Fhost_skills\u002Fskill-discovery\u002FSKILL.md",[122],{"categoryNo":24,"categoryName":25,"taxonomyType":21,"taxonomyTypeDesc":22},[124,125,126,107,127,128,129,130,131,132,133,134,135,136],"skill discovery","discovery","reusable","step by step","tokens","packages","help","cloud","reliability","capabilities","browse","search","Tools",{"skillNo":138,"name":139,"nameZh":6,"description":140,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":141,"categories":142,"keywords":144,"publishedAt":39},"01M6HYAR811B3RB0M50RBEDGN6","delegate-task","Delegate tasks to OpenSpace — a full-stack autonomous worker for coding, DevOps, web research, and desktop automation, backed by an extensive MCP tool and skill library. Skills auto-improve through use, reducing token consumption over time. A cloud community lets agents share and collectively evolve reusable skills.","https:\u002F\u002Fgithub.com\u002FHKUDS\u002FAgentPilot\u002Fblob\u002Fmain\u002Fopenspace\u002Fopenspace\u002Fhost_skills\u002Fdelegate-task\u002FSKILL.md",[143],{"categoryNo":24,"categoryName":25,"taxonomyType":21,"taxonomyTypeDesc":22},[145,146,147,107,148,149,150,151,152,126,32,92,153,154,155,156,157,158,159,160],"delegate","task","delegate task","time","improve","desktop automation","worker","community","autonomous","tool","stack","for","share","tasks","automation","MCP",{"skillNo":162,"name":163,"nameZh":6,"description":164,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":165,"categories":166,"keywords":167,"publishedAt":39},"01M6HYAM9FSGV6E52AYENDQXYH","write-special-chars-ts-check","Workaround for write_file failures caused by special characters (apostrophes, backticks, template literals) using a Python heredoc script, plus a reliable TypeScript type-checking step that filters output to only the newly-written files to avoid being misled by pre-existing errors.","https:\u002F\u002Fgithub.com\u002FHKUDS\u002FAgentPilot\u002Fblob\u002Fmain\u002Fopenspace\u002Flegacy\u002Fv1\u002Fshowcase\u002Fskills\u002Fwrite-special-chars-ts-check\u002FSKILL.md",[],[168,169,170,171,172,173,174,175,176,177,178,179,180,181,156,182,183],"write special chars ts check","write","check","type","files","filters","only","template","file","python","typescript","output","Existing","type-checking","errors","script",{"skillNo":185,"name":186,"nameZh":6,"description":187,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":188,"categories":189,"keywords":190,"publishedAt":39},"01M6HYAH05HGV7SVWSVR8PJRQD","write-special-chars-readback","Workaround for write_file failures caused by special characters (apostrophes, backticks, template literals) using a Python heredoc script, with mandatory post-write verification via read_file and cleanup of \u002Ftmp helper scripts.","https:\u002F\u002Fgithub.com\u002FHKUDS\u002FAgentPilot\u002Fblob\u002Fmain\u002Fopenspace\u002Flegacy\u002Fv1\u002Fshowcase\u002Fskills\u002Fwrite-special-chars-readback\u002FSKILL.md",[],[191,192,169,37,156,183,193,194,195,196,197,175,176,198,199,177],"write special chars readback","readback","helper","post","via","scripts","read","verification","cleanup"]