> ## Documentation Index
> Fetch the complete documentation index at: https://docs.peedief.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Best Practices

> Optimize your template design, API usage, and security for best results

# Best Practices

## Template Design Best Practices

### Template Structure

Design templates with clear structure and proper data fields:

**Template Data Fields**:

* Use descriptive field names (`recipientName` not `name`)
* Group related data in objects (`customerInfo.name`, `customerInfo.email`)
* Use arrays for repeating data (`items[]` for invoice line items)
* Include validation rules for required fields

**Template Layout**:

* Design for consistent branding across all documents
* Use responsive layouts that work with varying data amounts
* Include conditional sections for optional data
* Test with both minimal and maximum data scenarios

## HTML Optimization for PDFs

### Document Structure

Always use proper HTML5 structure for consistent results:

```html theme={null}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Document Title</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <style>
        /* CSS here */
    </style>
</head>
<body>
    <!-- Content here -->
</body>
</html>
```

### CSS Best Practices

**Typography for PDFs:**

```css theme={null}
body {
    font-family: 'Arial', 'Helvetica', sans-serif;
    font-size: 12pt;
    line-height: 1.4;
    color: #333333;
    margin: 0;
    padding: 20px;
}

h1 { 
    font-size: 18pt; 
    margin-bottom: 12pt;
    page-break-after: avoid;
}

h2 { 
    font-size: 16pt; 
    margin-bottom: 10pt;
    page-break-after: avoid;
}

p { 
    margin-bottom: 8pt; 
    text-align: justify;
}
```

**Page Break Control:**

```css theme={null}
/* Keep content together */
.page-break { 
    page-break-before: always; 
}

.avoid-break { 
    page-break-inside: avoid; 
}

/* Prevent awkward breaks */
h1, h2, h3, h4, h5, h6 {
    page-break-after: avoid;
}

/* Table handling */
table {
    page-break-inside: auto;
}

tr {
    page-break-inside: avoid;
    page-break-after: auto;
}
```

**Responsive Tables:**

```css theme={null}
table {
    width: 100%;
    border-collapse: collapse;
    page-break-inside: avoid;
    margin-bottom: 20px;
}

th, td {
    padding: 8px 12px;
    border: 1px solid #ddd;
    text-align: left;
    vertical-align: top;
}

thead {
    background-color: #f5f5f5;
    font-weight: bold;
}

/* Ensure table headers repeat on new pages */
thead {
    display: table-header-group;
}

tbody {
    display: table-row-group;
}
```

### Image Optimization

**Responsive Images:**

```css theme={null}
img {
    max-width: 100%;
    height: auto;
    image-rendering: optimizeQuality;
    display: block;
    margin: 10px 0;
}

/* High-DPI optimization */
@media (-webkit-min-device-pixel-ratio: 2) {
    img {
        image-rendering: -webkit-optimize-contrast;
    }
}
```

**Image Guidelines:**

* Use compressed images (PNG for graphics, JPEG for photos)
* Keep images under 2MB each
* Embed small images as base64 data URLs
* Use appropriate resolution (300 DPI for print quality)

## MCP Integration Best Practices

### Template Organization

**Template Naming**:

* Use descriptive, memorable template names
* Follow consistent naming conventions (`company-certificate`, `monthly-invoice`)
* Avoid special characters and spaces in template names
* Document template purposes and required data fields

**AI Conversation Flow**:

* Train users on how to request documents clearly
* Provide examples of good prompts for different document types
* Set up template descriptions that help AI agents understand usage
* Test conversation flows with different AI assistants

### Data Collection Strategies

**Structured Prompts**:

```
Good: "Create a certificate using template 'course-completion' for John Smith who completed 'Python Programming' on January 30, 2024"

Better: "Use the course-completion template to generate a certificate with these details:
- Student: John Smith  
- Course: Python Programming
- Completion Date: January 30, 2024
- Grade: A+"
```

## API Usage Best Practices

### Error Handling

Implement robust error handling with retry logic:

```javascript theme={null}
async function generatePDFWithRetry(templateName, contextData, maxRetries = 3) {
  for (let attempt = 1; attempt <= maxRetries; attempt++) {
    try {
      const response = await fetch(`https://peedief.com/api/templates/by-name/${templateName}/pdf`, {
        method: 'POST',
        headers: {
          'x-api-key': 'YOUR_API_KEY',
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({ 
          contextJson: contextData,
          fileName: `${templateName}-${Date.now()}.pdf`
        })
      });

      if (!response.ok) {
        const errorText = await response.text();
        throw new Error(`HTTP ${response.status}: ${errorText}`);
      }

      const result = await response.json();
      
      if (result.success) {
        return result;
      } else {
        throw new Error(result.error || 'Unknown error');
      }
    } catch (error) {
      console.error(`Attempt ${attempt} failed:`, error.message);
      
      if (attempt === maxRetries) {
        throw new Error(`PDF generation failed after ${maxRetries} attempts: ${error.message}`);
      }
      
      // Exponential backoff
      const delay = Math.pow(2, attempt) * 1000;
      await new Promise(resolve => setTimeout(resolve, delay));
    }
  }
}
```

## Security Best Practices

### API Key Management

<CardGroup cols={2}>
  <Card title="DO" icon="check">
    * Store keys in environment variables
    * Use different keys per environment
    * Rotate keys periodically
    * Monitor key usage patterns
    * Use server-side API calls only
  </Card>

  <Card title="DON'T" icon="x">
    * Commit keys to version control
    * Share keys via email/chat
    * Use same key across projects
    * Embed keys in client-side code
    * Store keys in plain text files
  </Card>
</CardGroup>

**Environment Configuration:**

```bash theme={null}
# .env file (never commit this!)
PEEDIEF_API_KEY=pk_live_your_secret_key_here
PEEDIEF_API_URL=https://peedief.com/api
```

```javascript theme={null}
// Proper server-side usage
const apiKey = process.env.PEEDIEF_API_KEY;
if (!apiKey) {
  throw new Error('PEEDIEF_API_KEY environment variable is required');
}

// NEVER do this in client-side code:
// const apiKey = 'pk_live_1234567890'; // ❌ NEVER!
```
