# Font System - Quick Reference & Action Plan

## 🎯 Executive Summary for Developers

### Current Status: ⚠️ PARTIAL FUNCTIONALITY
- ✅ System works and generates PDFs
- ✅ Some fonts render correctly (Gotham fonts)
- ❌ Several referenced fonts are missing (Century Gothic, kabelM, Profile Pro)
- ⚠️ Reports render with incorrect fonts as fallbacks

### Business Impact:
- **Visual Quality**: Reports display with "wrong" fonts (less professional)
- **Brand Consistency**: Inconsistent appearance across report types
- **User Experience**: Reports don't match design specifications
- **Performance**: Minimal impact (font fallback resolution adds <1ms)

---

## 📋 Quick Checklist for Developers

### Before Making Changes
```
☐ Read FONT_ANALYSIS_REPORT.md (full technical analysis)
☐ Read FONT_ARCHITECTURE_GUIDE.md (system architecture)
☐ Backup /var/www/html/wnapi/pdf-files-app/pdf_footer.php
☐ Backup /var/www/html/wnapi/pdf-files-app/pdf.css
☐ Document current PDF appearance (take screenshots)
```

### Common Development Tasks

#### Task: Generate a test report
```bash
# SSH into server
ssh user@server

# Navigate to project
cd /var/www/html/wnapi

# Run API endpoint (example: Personality Profile)
curl -X POST http://localhost/wnapi/generate_personality_profile.php \
  -d "first_name=John&last_name=Doe&dob=1990-01-15"

# Check output PDF
ls -lah /var/www/html/wnapi/pdf-uploads/ | head -5
```

#### Task: Find PDF generation errors
```php
// Add to pdf_footer.php after line 13
error_log("DOMPDF initialized with options: " . print_r($dompdf->getOptions(), true));

// Check log file
tail -100 /var/log/php-errors.log
```

#### Task: Test a specific font
```php
// Create test file: /var/www/html/wnapi/test-font.php
<?php
require_once("vendor/autoload.php");
use Dompdf\Dompdf;

$dompdf = new Dompdf();
$html = '<html><body>';
$html .= '<h1 style="font-family: Century Gothic;">Testing Century Gothic</h1>';
$html .= '<p style="font-family: DejaVuSans;">Testing DejaVuSans</p>';
$html .= '</body></html>';

$dompdf->load_html($html);
$dompdf->render();
$dompdf->stream('test-fonts.pdf');
?>
```

---

## 🔧 Quick Fix Instructions

### Fix 1: Add Missing Font Fallbacks (Quick Win - 5 minutes)

**File**: `/var/www/html/wnapi/pdf-files-app/pdf.css`

**Current** (Line 1-5):
```css
.header_start{
    text-transform:uppercase;
    font-family: Century Gothic;
    font-size: 12pt;
}
```

**Change to**:
```css
.header_start{
    text-transform:uppercase;
    font-family: 'Century Gothic', 'DejaVuSans', sans-serif;
    font-size: 12pt;
}
```

**Apply to ALL occurrences** of font-family declarations without fallbacks:
- Line 1: `.header_start`
- Line 5: `.header_text`
- Line 9: `.subheader_start`
- Line 14: `.subheader_text`
- Line 31: `.pdf_chapter`
- Line 49: `.summary_start`
- Line 54: `.summary`

---

### Fix 2: Update PDF Footer Configuration (Medium - 10 minutes)

**File**: `/var/www/html/wnapi/pdf-files-app/pdf_footer.php`

**Current** (Lines 7-13):
```php
require_once(dirname(__DIR__)."/vendor/autoload.php");
require_once dirname(__DIR__).'/dompdf/lib/html5lib/Parser.php';
require_once dirname(__DIR__).'/dompdf/src/Autoloader.php';

Dompdf\Autoloader::register();
use Dompdf\Dompdf;

$dompdf = new DOMPDF(array('enable_remote' => true,'isPhpEnabled' => true,'isHtml5Parser' => true));
```

**Change to**:
```php
require_once(dirname(__DIR__)."/vendor/autoload.php");
require_once dirname(__DIR__).'/dompdf/lib/html5lib/Parser.php';
require_once dirname(__DIR__).'/dompdf/src/Autoloader.php';

Dompdf\Autoloader::register();
use Dompdf\Dompdf;

$fontDir = dirname(__DIR__) . '/dompdf/lib/fonts/';
$dompdf = new DOMPDF(array(
    'enable_remote' => true,
    'isPhpEnabled' => true,
    'isHtml5Parser' => true,
    'fontDir' => $fontDir,
    'defaultFont' => 'DejaVuSans',
    'isFontSubsettingEnabled' => true,
    'fontHeightRatio' => 1.0
));
```

---

### Fix 3: Add Font Fallbacks in PDF Header (Medium - 10 minutes)

**File**: `/var/www/html/wnapi/pdf-files-app/pdf_header.php`

**Find and Replace** (multiple locations):

**Current**:
```php
font-family:\'Gotham\', sans-serif !important;
```

**Keep as-is** (already has fallback) ✅

**Current**:
```php
font-family:kabelM;
```

**Change to**:
```php
font-family: 'kabelM', 'DejaVuSans', sans-serif;
```

**Current**:
```php
font-family: \'Figtree Medium\', \'Futura\', \'GothamCondensed-Medium\', sans-serif;
```

**Keep as-is** (has good fallback chain) ✅

---

## 🎨 Font Priority & Alternatives

### Priority 1: MUST HAVE (Heavy usage in text content)

| Font | Current Usage | Alternatives | Action |
|------|---------------|--------------|--------|
| Century Gothic | Headers, body text, page numbers | Georgia, Garamond | **Find font file** |
| DejaVuSans | Fallback (exists) | Helvetica | ✅ Already available |

**Action**: Either:
1. Find Century Gothic font file (TTF/OTF) and add to `/dompdf/lib/fonts/`, OR
2. Replace all CSS references with available fonts (DejaVuSerif, Helvetica)

### Priority 2: SHOULD HAVE (Cover design)

| Font | Current Usage | Alternatives | Action |
|------|---------------|--------------|--------|
| kabelM | Cover decorations | GothamBook, Futura | Add fallback to CSS |
| Profile Pro | Report title | GothamBook, Helvetica Bold | Add fallback to CSS |
| Gotham | Cover & headers | GothamBook (exists) | ✅ Already available |

**Action**: Ensure proper CSS fallback chains

### Priority 3: NICE TO HAVE (Fallback options)

| Font | Current Usage | Alternatives | Action |
|------|---------------|--------------|--------|
| Futura | CSS fallback chain | Helvetica | Already has fallback |
| Figtree Medium | CSS fallback chain | DejaVuSans | Already has fallback |

---

## 📊 Current Font Mapping

```
┌─────────────────────────────────────────────────────────────────┐
│                    CURRENT FONT USAGE MAP                       │
└─────────────────────────────────────────────────────────────────┘

REQUESTED FONT          FILE FOUND?    RENDERS AS          STATUS
═══════════════════════════════════════════════════════════════════
Century Gothic          ❌ NO          DejaVuSans/Helvetica ⚠️ WRONG
kabelM                  ❌ NO          DejaVuSans/Helvetica ⚠️ WRONG  
Profile Pro             ❌ NO          DejaVuSans/Helvetica ⚠️ WRONG
Gotham / GothamBook     ✅ YES         GothamBook.ttf       ✅ OK
GothamLight             ✅ YES         GothamLight.ttf      ✅ OK
GothamCondensed-Medium  ✅ YES         GothamCondensed...   ✅ OK
DejaVuSans              ✅ YES         DejaVuSans.ttf       ✅ OK
Helvetica               ✅ YES (native) Helvetica           ✅ OK
Courier                 ✅ YES (native) Courier             ✅ OK
```

---

## 🔍 How to Verify Font Changes

### Method 1: Visual Inspection
```bash
# Generate a test PDF
curl -X POST http://localhost/wnapi/generate_personality_profile.php \
  -d "first_name=Test&last_name=User&dob=1990-01-15" > /tmp/test.pdf

# Open in PDF viewer
open /tmp/test.pdf  # macOS
xdg-open /tmp/test.pdf  # Linux
```

**Check for**:
- Headers look professional (serif-like) - Century Gothic intended
- Body text is consistent - should be sans-serif
- Page numbers are readable
- Cover page has proper styling

### Method 2: File Size Check
```bash
# Before optimization
ls -lh /var/www/html/wnapi/pdf-uploads/Test_*.pdf | awk '{print $5}'

# After enabling font subsetting
ls -lh /var/www/html/wnapi/pdf-uploads/Test_*.pdf | awk '{print $5}'

# Expected: 50% file size reduction when subsetting enabled
```

### Method 3: Font Debugging in Code
```php
// Add to pdf_footer.php after dompdf initialization
$availableFonts = array(
    'Century Gothic',
    'kabelM',
    'Profile Pro',
    'GothamBook',
    'DejaVuSans'
);

foreach ($availableFonts as $font) {
    try {
        $fontMetrics->get_font($font);
        error_log("Font found: $font ✅");
    } catch (Exception $e) {
        error_log("Font NOT found: $font ❌");
    }
}
```

---

## 💾 Configuration Files Reference

### Key Files to Modify

1. **pdf_footer.php** (PDF rendering engine)
   - Lines: 7-13 (dompdf initialization)
   - Lines: 14-55 (CSS styles)
   - Purpose: Main PDF generation and font setup

2. **pdf.css** (Stylesheet)
   - Lines: 1-60 (font-family declarations)
   - Purpose: CSS classes for report styling

3. **pdf_header.php** (Cover page)
   - Lines: 146-250 (inline font styles)
   - Purpose: Cover design and styling

4. **text-image.php** (Text-to-image rendering)
   - Lines: 1-50 (font path setup)
   - Purpose: Generate cover names as images

### Font Storage Location

```
/var/www/html/wnapi/dompdf/lib/fonts/
├── ✅ AVAILABLE
│   ├── GothamBook.ttf
│   ├── GothamLight.ttf
│   ├── GothamCondensed-Medium.otf
│   ├── DejaVuSans.ttf (and variants)
│   ├── DejaVuSerif.ttf (and variants)
│   └── [Core PDF fonts]
│
└── ❌ MISSING (Need to be added)
    ├── Century Gothic.ttf
    ├── kabelM.ttf
    ├── Profile Pro.ttf
    ├── Futura.ttf
    └── Figtree-Medium.ttf
```

---

## 🚀 Performance Impact Summary

| Change | Impact | Effort | Priority |
|--------|--------|--------|----------|
| Add font fallbacks | None (just fallback) | 5 min | HIGH |
| Enable font subsetting | +5-10% faster, -50% file size | 10 min | MEDIUM |
| Add missing fonts | +Visual quality | 30+ min | MEDIUM |
| Update dompdf config | None (better setup) | 5 min | HIGH |
| Create font config file | Easier maintenance | 15 min | LOW |

**Recommended Implementation Order**:
1. ✅ Add font fallbacks to CSS (5 min)
2. ✅ Update dompdf configuration (5 min)
3. ⏳ Procure missing font files (hours to days)
4. ⏳ Add fonts to dompdf directory (5 min)
5. ⏳ Create centralized font configuration (15 min)
6. ⏳ Run regression tests (2-4 hours)

---

## 🐛 Troubleshooting Guide

### Problem: PDF Shows Wrong Font

**Diagnosis**:
```php
// Add temporary debug code to pdf_footer.php
error_log("Rendering with font: " . $dompdf->getOptions()->getDefaultFont());
```

**Solution 1**: Check CSS font-family declaration
```css
/* BEFORE: No fallback */
font-family: Century Gothic;

/* AFTER: With fallback */
font-family: 'Century Gothic', 'DejaVuSans', sans-serif;
```

**Solution 2**: Verify font file exists
```bash
ls -la /var/www/html/wnapi/dompdf/lib/fonts/ | grep -i "century\|gotham"
```

### Problem: PDF Generation Fails

**Diagnosis**:
```bash
# Check error logs
tail -20 /var/log/php-errors.log
```

**Common Causes**:
1. Missing font file → Check `/dompdf/lib/fonts/` directory
2. Font encoding issue → Convert font to TTF format
3. Font path incorrect → Verify dirname(__DIR__) resolves correctly
4. Permission issue → Check `/tmp` directory permissions

### Problem: PDF File Size Too Large

**Solution**: Enable font subsetting
```php
'isFontSubsettingEnabled' => true
```

**Expected Result**: File size reduced by 40-50%

### Problem: Special Characters Don't Render

**Solution**: Ensure DejaVuSans fallback is available
```css
font-family: 'PrimaryFont', 'DejaVuSans', sans-serif;
```

DejaVuSans has excellent Unicode support for international characters.

---

## 📞 Support & Questions

### Common Questions

**Q: Do I need to add all missing fonts?**
A: No. At minimum, add Century Gothic (heavy usage). Others can use CSS fallbacks.

**Q: Will changing fonts break existing PDFs?**
A: No, only newly generated PDFs will be affected.

**Q: How do I test font changes?**
A: Use the test script in "How to Verify Font Changes" section above.

**Q: Can I use web fonts?**
A: Not directly with dompdf. Fonts must be in TTF/OTF format in the fonts directory.

**Q: What if I don't have the font files?**
A: Use open-source alternatives:
- Century Gothic → Georgia, Garamond, Palatino
- kabelM → Futura (if available), Gotham
- Profile Pro → Gotham Bold, Helvetica Bold

---

## 📚 Reference Documentation

| Document | Purpose | Read When |
|----------|---------|-----------|
| FONT_ANALYSIS_REPORT.md | Complete technical analysis | Need full details |
| FONT_ARCHITECTURE_GUIDE.md | System architecture & diagrams | Understanding flow |
| FONT_QUICK_REFERENCE.md | This file | Quick lookup |
| pdf_footer.php | Main rendering code | Implementing changes |
| dompdf README | Library documentation | Learning dompdf |

---

## ✅ Implementation Checklist

### Phase 1: Quick Fixes (30 minutes)
- [ ] Update pdf.css with font fallbacks
- [ ] Update pdf_footer.php dompdf config
- [ ] Test PDF generation
- [ ] Verify fonts render correctly

### Phase 2: Long-term (1-2 days)
- [ ] Procure missing font files
- [ ] Add fonts to `/dompdf/lib/fonts/`
- [ ] Update CSS with complete fallback chains
- [ ] Create centralized font configuration
- [ ] Run full regression test suite
- [ ] Deploy to production

### Phase 3: Maintenance (ongoing)
- [ ] Monitor PDF generation errors
- [ ] Track font usage statistics
- [ ] Update documentation as needed
- [ ] Review font rendering quality

---

**Last Updated**: January 27, 2026  
**Document Version**: 1.0  
**Status**: Ready for Implementation
