# PDF Generation

## CRITICAL: Work in /tmp, Copy Final to /workspace

**Always generate/convert in `/tmp` first**, then copy the final PDF to `/workspace`. Intermediate files aren't useful to the user.

```python
# Generate in /tmp
pdf.output('/tmp/report.pdf')

# Copy final result to /workspace
import shutil
shutil.copy('/tmp/report.pdf', '/workspace/report.pdf')
```

---

## CRITICAL: Build Incrementally

**DO NOT** write a single massive script. If it fails on page 15, you lose everything.

**Build iteratively** - generate a few pages, save to `/tmp`, verify, then add more.

---

## Approaches

### 1. Direct Generation (fpdf/fpdf2, reportlab)

Generate in `/tmp`, copy final to `/workspace`:

```python
pdf = FPDF()
# ... build PDF ...
pdf.output('/tmp/report.pdf')
shutil.copy('/tmp/report.pdf', '/workspace/report.pdf')
```

### 2. HTML to PDF (Playwright)

Write to `/tmp`, copy final to `/workspace`:

```python
pdf_bytes = await page.pdf(format="A4")
with open('/tmp/report.pdf', 'wb') as f:
    f.write(pdf_bytes)
shutil.copy('/tmp/report.pdf', '/workspace/report.pdf')
```

### 3. Office File Conversion (LibreOffice)

LibreOffice **cannot** write directly to `/workspace` in GCS:

```
Error: SfxBaseModel::impl_store failed: 0x507(Error Area:Io Class:Access Code:7)
```

**Must** write to `/tmp`, then copy:

```bash
libreoffice --headless --convert-to pdf --outdir /tmp /workspace/file.pptx && cp /tmp/file.pdf /workspace/
```

The Java warning (`failed to launch javaldx`) is harmless.

---

## fpdf/fpdf2 Gotchas

### Error: "Not enough horizontal space to render a single character"

`cell()` moves cursor right; `multi_cell()` needs room.

**Fix:** Reset X position before `multi_cell()`:

```python
pdf.set_x(pdf.l_margin)
pdf.multi_cell(0, 6, text)
```

### Page breaks mid-content

**Fix:** Check remaining space before adding content:

```python
if pdf.get_y() > 250:  # Near bottom of A4
    pdf.add_page()
```
