# React ID Card Generator

A React library for creating customizable ID cards with a visual drag-and-drop designer. Design card templates once, then generate ID cards for multiple users with their data.

## What Does It Do?

This library helps you build ID card systems for schools, companies, events, or any organization. It provides:

1. **Designer Component** - A visual editor to create ID card templates by dragging fields (name, photo, QR code, etc.) and positioning them
2. **Generator Component** - Renders actual ID cards by filling your template with user data
3. **Export Tools** - Download ID cards as PDF or PNG images

## Installation

```bash
npm install react-id-card-generator
```

## Quick Start

### Step 1: Design Your Template

Use the designer to create your ID card layout. Add fields, upload a background, and style everything.

```tsx
import { IDCardDesigner } from 'react-id-card-generator';
import 'react-id-card-generator/dist/styles.css';

function TemplateDesigner() {
  const handleSave = (template) => {
    // Save your template (to database, localStorage, etc.)
    localStorage.setItem('id-template', JSON.stringify(template));
  };

  return <IDCardDesigner onSave={handleSave} />;
}
```

### Step 2: Generate ID Cards

Use your template to create ID cards for individual users.

```tsx
import { IDCardGenerator } from 'react-id-card-generator';

function UserIDCard() {
  const template = JSON.parse(localStorage.getItem('id-template'));
  
  const userData = {
    name: 'John Doe',
    idno: 'EMP-001',
    department: 'Engineering',
    photo: 'https://example.com/photo.jpg'
  };

  return <IDCardGenerator template={template} data={userData} side="front" />;
}
```

### Step 3: Export as PDF

```tsx
import { useIDCardExport } from 'react-id-card-generator';

function ExportCard() {
  const { exportAsPDF, isExporting } = useIDCardExport();

  return (
    <button onClick={() => exportAsPDF({ filename: 'john-doe-id.pdf' })}>
      {isExporting ? 'Generating...' : 'Download PDF'}
    </button>
  );
}
```

## Features

- **Visual Designer** - Drag fields to position them, resize with handles
- **Field Types** - Text, labels, images/photos, and QR codes
- **QR Codes** - Select which card fields to encode in the QR code
- **Double-Sided** - Create cards with front and back sides
- **Backgrounds** - Upload custom background images
- **Styling** - Customize fonts, colors, alignment, border radius, and more
- **Export** - Generate PDFs or PNG images of completed cards

## Components

### IDCardDesigner

The visual template builder. Users drag fields onto the card, position them, and configure styles.

```tsx
<IDCardDesigner 
  onSave={(template) => console.log(template)}
  onCancel={() => console.log('cancelled')}
/>
```

**Props:**
- `onSave(template)` - Called when user saves the template
- `onCancel()` - Optional callback when user cancels
- `initialTemplate` - Optional existing template to edit
- `className`, `style` - Optional styling props

### IDCardGenerator

Renders a filled ID card using a template and user data.

```tsx
<IDCardGenerator 
  template={myTemplate}
  data={userData}
  side="front"
  scale={1.5}
/>
```

**Props:**
- `template` - The ID card template (from designer)
- `data` - Object with user data matching field keys
- `side` - Which side to show: `'front'` or `'back'`
- `scale` - Optional size multiplier (default: 1)

## Hooks

### useIDCardTemplate

Manages template state with helper methods.

```tsx
const {
  template,
  updateField,
  addField,
  removeField,
  setBackground,
  isValid,
  validationErrors
} = useIDCardTemplate();
```

### useIDCardExport

Handles exporting cards to PDF or images.

```tsx
const { exportAsPDF, exportAsImage, isExporting } = useIDCardExport();

// Export as PDF
await exportAsPDF({ 
  filename: 'id-card.pdf',
  pages: ['front', 'back']
});

// Export as PNG
await exportAsImage({ 
  format: 'png',
  filename: 'id-card.png'
});
```

## Field Types

1. **Text Field** - Displays text data (name, ID number, etc.)
2. **Label** - Static text that doesn't change (e.g., "EMPLOYEE ID")
3. **Image** - Shows photos or logos (supports border radius for circular photos)
4. **QR Code** - Generates scannable QR codes from selected card fields
5. **Table** - Displays array-backed row data with configurable headers, columns, and styles

### Table Data

Table fields use the table field key as the data source, and each column field key maps to a property in every row object.

```tsx
const data = {
  name: 'John Doe',
  results: [
    { subject: 'Math', marks: 95, grade: 'A' },
    { subject: 'Science', marks: 91, grade: 'A' }
  ]
};
```

In the designer, set the table data source key to `results`, then set column field keys such as `subject`, `marks`, and `grade`. A new table starts with 5 body rows, 5 columns, and a visible header row.

## Template Storage

Save and load templates:

```tsx
import { 
  saveTemplateToLocal, 
  loadTemplateFromLocal,
  exportTemplateAsJSON
} from 'react-id-card-generator';

// Save to localStorage
saveTemplateToLocal('my-template', template);

// Load from localStorage
const template = loadTemplateFromLocal('my-template');

// Export as JSON file
exportTemplateAsJSON(template, 'template.json');
```

## TypeScript Support

Full TypeScript definitions included. Key types:

```typescript
// Your template structure
interface IDCardTemplate {
  id: string;
  name: string;
  orientation: 'portrait' | 'landscape';
  sides: 'single' | 'double';
  cardSize: { width: number; height: number; unit: 'px' | 'mm' | 'in' };
  backgrounds: { front?: string; back?: string };
  fields: FieldMapping[];
}

// User data for generating cards
interface IDCardData {
  [key: string]: string | number | boolean | string[] | TableRowData[] | undefined;
}

interface TableRowData {
  [key: string]: string | number | boolean | null | undefined;
}
```

## License

MIT
