@stratametriq/id-card-designer 1.4.3 → 1.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (4) hide show
  1. package/README.md +131 -563
  2. package/dist/index.es.js +5225 -5105
  3. package/dist/index.js +107 -107
  4. package/package.json +28 -11
package/README.md CHANGED
@@ -1,28 +1,33 @@
1
1
  # 📦 @stratametriq/id-card-designer
2
2
 
3
- A universal, dynamic, and highly customizable ID Card Designer, Turnkey Dashboard & A4 Multi-Page PDF Rendering Engine for React, Vue, Angular, and Vanilla JS.
3
+ ![NPM Version](https://img.shields.io/npm/v/@stratametriq/id-card-designer?style=for-the-badge&color=blue)
4
+ ![NPM Downloads](https://img.shields.io/npm/dm/@stratametriq/id-card-designer?style=for-the-badge&color=success)
5
+ ![License](https://img.shields.io/npm/l/@stratametriq/id-card-designer?style=for-the-badge&color=orange)
4
6
 
5
- Whether you are building an **Educational ERP / Student Information System**, **Faculty & Staff Directory**, **Hospital / Medical Access Portal**, **Corporate Employee Directory**, or **Event Badge Generator**, `@stratametriq/id-card-designer` gives your users a professional visual canvas right inside your application to design, customize, preview, and batch export PVC ID cards.
7
+ A universal, dynamic, and highly customizable **ID Card Designer & Batch Print Dashboard** for React, Vue, Angular, and Vanilla JS.
8
+
9
+ Whether you are building a **Student Information System**, **HR Employee Directory**, or **Event Badge Generator**, this package gives your users a professional visual canvas to design, customize, preview, and batch export PVC ID cards directly inside your app.
6
10
 
7
11
  ---
8
12
 
9
- ## 🌟 Features
13
+ ## 📑 Table of Contents
10
14
 
11
- - **🎨 Turnkey All-In-One Dashboard (`<IdCardManager />`):** Drop in a complete, ready-to-use workspace containing department tabs, live vector stage, batch A4 print setup, and roster selection table.
12
- - **📁 Multiple Card Templates:** Full support for multiple pre-configured category layouts (*Student ID Cards*, *Faculty & Admin*, *Corporate HR*, *Hospital Portal*) and multi-orientation presets (*Vertical 54×86mm* and *Horizontal 86×54mm*).
13
- - **🔳 QR Code & Barcode Generation:** Built-in deterministic, high-resolution vector 1D Barcode (`<Barcode />`) and 2D QR Code (`<QrCode />`) generation with live database key binding.
14
- - **🏷️ Variable Placeholders (`{{name}}`, `{{employeeId}}`):** Seamless handlebar/mustache syntax interpolation across text labels, custom formulas, prefixes, and suffixes (`e.g., ID: {{admissionNo}} - {{studentName}}`).
15
- - **📥 Batch Generation from CSV or Excel (`.csv`):** One-click spreadsheet import instantly parses rows, maps headers, and populates hundreds of roster cards in real time.
16
- - **🖼️ High-Resolution PDF & PNG Export:** Dual production output options: Batch A4 multi-page PDF sheets (`html2canvas` + `jspdf` with hardware cut marks) alongside standalone high-resolution **300 DPI PNG export**.
17
- - **🔄 Undo & Redo History Control:** Full history stack tracking (`Ctrl+Z` / `Cmd+Z` to undo, `Ctrl+Y` / `Cmd+Shift+Z` to redo) alongside keyboard arrow key precision nudging (`1px` or `5px` with Shift).
18
- - **📏 Grid Snapping & Alignment Guides:** Toggleable millimeter measurement rulers (`0mm - 86mm`), radial grid overlay with snap-to-grid accuracy (`1mm / 5mm`), and multi-element alignment guides (`Align Left, Center, Right`).
19
- - **🖼️ Dedicated Image Property Inspector:** Fine-grained controls for image elements including **Replace Image / Data Binding**, **Crop / Object Fit** (`cover`, `contain`, `fill`, `none`, `scale-down`), **Corner Radius** (`Circle` avatars or custom px), **Border** styling, **Opacity**, and **Box Shadow**.
20
- - **🔤 Advanced Text & Typography Inspector:** Complete control over **Font Family**, **Font Size**, **Font Weight**, **Text Color**, **Letter Spacing**, **Line Height**, **Text Alignment** (`Left`, `Center`, `Right`), **Rotation (°)**, **Opacity**, **Padding**, **Border & Divider Lines**, and **Box Shadow**.
21
- - **🔍 Instant Roster Search & Status Filters:** Real-time search bar across names, ID numbers, departments, and phone numbers, plus quick status filter pill tabs (`All | Selected | Unselected`).
15
+ - [Installation](#installation)
16
+ - [Quick Start](#quick-start)
17
+ - [Features](#features)
18
+ - [Props](#props)
19
+ - [Templates](#templates)
20
+ - [Customization](#customization)
21
+ - [Events](#events)
22
+ - [Examples](#examples)
23
+ - [FAQ](#faq)
24
+ - [License](#license)
22
25
 
23
26
  ---
24
27
 
25
- ## 📦 Installation
28
+ ## 💻 Installation
29
+
30
+ Install the package using NPM or Yarn:
26
31
 
27
32
  ```bash
28
33
  npm install @stratametriq/id-card-designer
@@ -30,630 +35,193 @@ npm install @stratametriq/id-card-designer
30
35
  yarn add @stratametriq/id-card-designer
31
36
  ```
32
37
 
33
- Include the stylesheet in your project root (`main.jsx` or `App.jsx`):
34
-
35
- ```javascript
36
- import "@stratametriq/id-card-designer/dist/index.css";
37
- ```
38
-
39
- ---
40
-
41
- ## 💼 Commercial & Enterprise Licensing
42
-
43
- `@stratametriq/id-card-designer` is dual-licensed to support both open-source developers and commercial enterprises:
44
-
45
- 1. **Community / Open Source Tier (MIT License):**
46
- Free for non-commercial evaluation, personal open-source projects, and rendering standalone static preview widgets (`<IdCardPreview />`).
47
- 2. **Commercial / Enterprise Tier (Commercial License):**
48
- Required for commercial SaaS applications, School ERP platforms, HR suites, and institutions using the **Turnkey Dashboard (`<IdCardManager />`)**, **CSV/Excel Bulk Import Parser**, or **Batch A4/Letter Multi-Page Print Engine (`generateIdCardsPdf`)** in commercial production.
49
-
50
- 👉 **[Purchase a Commercial Enterprise License ($49 - $499) to Unlock Production Usage, White-Labeling & Priority Support](https://waniabid.gumroad.com/l/id-card-designer-pro)**
51
-
52
38
  ---
53
39
 
54
- ## 🚀 Sweet & Simple Guide: How to Use with Real Data & Features
40
+ ## ⚡ Quick Start
55
41
 
56
- Whether you want a **1-Minute Turnkey Dashboard** (`<IdCardManager />`) or want to build your own **Custom Portal** using individual modular features (`<IdCardPreview />`, `<IdCardDesignerModal />`, `generateIdCardsPdf`), connecting your real database or API data is effortless!
42
+ ### 🚀 [Try the Live Interactive Demo on StackBlitz](https://stackblitz.com/edit/vitejs-vite-nurmeilk?file=package.json,src%2FApp.tsx,src%2FApp.css,src%2Findex.css&terminal=dev)
57
43
 
58
- ### Option 1: Turnkey All-In-One Dashboard (`<IdCardManager />`)
59
-
60
- By default, rendering `<IdCardManager />` without props opens our full interactive demo screen. To connect your **real API or database records**, simply pass them into the `sampleRecords` prop:
44
+ You can launch a complete ID card design studio and batch print dashboard with just **two lines of code**. It comes with pre-built dummy data so you can test it immediately!
61
45
 
62
46
  ```jsx
63
- import React, { useState, useEffect } from 'react';
64
47
  import { IdCardManager } from '@stratametriq/id-card-designer';
65
48
  import '@stratametriq/id-card-designer/dist/index.css';
66
49
 
67
- export default function SchoolPortal() {
68
- const [dbRecords, setDbRecords] = useState({ student: [], staff: [] });
69
-
70
- // 1. Fetch real students/employees from your backend (Node.js, Laravel, Supabase, etc.)
71
- useEffect(() => {
72
- fetch('https://api.yourschool.com/students')
73
- .then(res => res.json())
74
- .then(data => setDbRecords({ student: data }));
75
- }, []);
76
-
77
- // 2. Pass your live data right into <IdCardManager />!
78
- return (
79
- <IdCardManager
80
- sampleRecords={dbRecords}
81
-
82
- // Save customized card designs back to your database
83
- onSaveCategoryTemplate={(category, templateSchema) => {
84
- console.log(`Saving ${category} template to DB:`, templateSchema);
85
- }}
86
-
87
- // Listen when batch PDF export completes
88
- onBatchExportComplete={(category, exportedRecords) => {
89
- console.log(`Generated A4 PDF for ${exportedRecords.length} records!`);
90
- }}
91
- />
92
- );
50
+ export default function App() {
51
+ // This will render the complete turnkey dashboard with demo data!
52
+ return <IdCardManager />;
93
53
  }
94
54
  ```
95
55
 
96
56
  ---
97
57
 
98
- ### Option 2: Building Custom Screens (Using Modular Features)
99
-
100
- If you don't want our full dashboard and instead want to embed specific ID card features directly into your own custom pages, tables, or profile screens, use our **standalone building blocks**:
101
-
102
- #### A. Show a Live ID Card on a Student Profile Page (`<IdCardPreview />`)
103
- ```jsx
104
- import { IdCardPreview } from '@stratametriq/id-card-designer';
105
-
106
- function StudentProfilePage({ realStudentData, savedTemplateJson }) {
107
- return (
108
- <div className="profile-card-widget">
109
- <h3>Student ID Card</h3>
110
-
111
- {/* Automatically binds realStudentData fields into the template */}
112
- <IdCardPreview
113
- templateSchema={savedTemplateJson}
114
- data={realStudentData} // e.g. { studentName: 'Aarav Patel', admissionNo: 'ADM-101', profilePhoto: '...' }
115
- orientation="vertical"
116
- zoom={1.2}
117
- />
118
- </div>
119
- );
120
- }
121
- ```
122
-
123
- #### B. Trigger Batch A4 PDF Export from Your Own Custom Button (`generateIdCardsPdf`)
124
- ```jsx
125
- import { generateIdCardsPdf } from '@stratametriq/id-card-designer';
126
-
127
- function CustomRosterTable({ selectedStudents, activeTemplate }) {
128
- const handlePrint = async () => {
129
- // Generate high-resolution A4 multi-page PDF directly from your data array
130
- await generateIdCardsPdf({
131
- records: selectedStudents,
132
- templateSchema: activeTemplate,
133
- orientation: 'vertical',
134
- fileName: `Student_Cards_Batch_${new Date().toISOString().slice(0,10)}.pdf`,
135
- pageOptions: { format: 'a4', showCropMarks: true }
136
- });
137
- };
138
-
139
- return <button onClick={handlePrint}>Download A4 Print Sheet ({selectedStudents.length} Cards)</button>;
140
- }
141
- ```
142
-
143
- #### C. Open the Drag-and-Drop Studio inside Your Own Modal (`<IdCardDesignerModal />`)
144
- ```jsx
145
- import { IdCardDesignerModal } from '@stratametriq/id-card-designer';
146
-
147
- function DesignButton({ currentTemplate, onSaveToDatabase }) {
148
- const [isOpen, setIsOpen] = useState(false);
58
+ ## 🌟 Features
149
59
 
150
- return (
151
- <>
152
- <button onClick={() => setIsOpen(true)}>✨ Design Card Layout</button>
153
-
154
- <IdCardDesignerModal
155
- show={isOpen}
156
- onHide={() => setIsOpen(false)}
157
- initialTemplate={currentTemplate}
158
- sampleData={[{ studentName: 'Sample Student', admissionNo: '101' }]}
159
- onSaveTemplate={(newTemplate) => {
160
- onSaveToDatabase(newTemplate);
161
- setIsOpen(false);
162
- }}
163
- />
164
- </>
165
- );
166
- }
167
- ```
60
+ - **🎨 Turnkey Dashboard:** A complete workspace with department tabs, vector stage, and batch printing ready out-of-the-box.
61
+ - **📥 Batch CSV Import:** Let users upload spreadsheets to instantly generate hundreds of cards.
62
+ - **🔳 QR & Barcodes:** Built-in dynamic 1D Barcode and 2D QR Code generation.
63
+ - **🏷️ Variable Placeholders:** Easily map database fields to card text (e.g., `ID: {{admissionNo}}`).
64
+ - **🖼️ High-Res PDF/PNG Export:** Batch export to A3/A4/A5/Letter size PDF sheets with hardware cut marks.
65
+ - **🌐 Framework Agnostic:** Works natively with React and Next.js, and easily mounts into Vue, Angular, and Vanilla HTML.
168
66
 
169
67
  ---
170
68
 
171
- ## 🌐 Multi-Framework & Vanilla JS Support (`Vue`, `Angular`, `Svelte`, `Next.js` & `HTML`)
172
-
173
- While the visual UI components (`<IdCardManager />` and `<IdCardDesignerModal />`) are built with React hooks and drag-and-drop vector canvas state (`react-draggable`), **this npm package can be used across any frontend framework or vanilla JavaScript project**:
174
-
175
- ### 1. Using in React & Next.js (`React 18 / Vite / Remix / Next.js`)
176
- Simply import our components directly into your React JSX/TSX tree:
177
- ```jsx
178
- import { IdCardManager } from "@stratametriq/id-card-designer";
179
- ```
180
-
181
- ### 2. Using in Vue, Angular, Svelte, or Vanilla HTML (`Micro-Frontend Mounting`)
182
- If your application is built with **Vue.js**, **Angular**, **Svelte**, or plain **HTML/JS**, you can easily mount the turnkey `<IdCardManager />` dashboard into any DOM element using `createRoot` in just a few lines of code:
183
-
184
- ```html
185
- <!-- Inside index.html or your Vue/Angular/Svelte component template -->
186
- <div id="id-card-manager-root"></div>
69
+ ## ⚙️ Props
187
70
 
188
- <script type="module">
189
- import React from 'react';
190
- import { createRoot } from 'react-dom/client';
191
- import { IdCardManager } from '@stratametriq/id-card-designer';
192
- import '@stratametriq/id-card-designer/dist/index.css';
71
+ The main `<IdCardManager />` component accepts the following props:
193
72
 
194
- // Mount the visual ID Card Dashboard cleanly inside any HTML div
195
- const rootElement = document.getElementById('id-card-manager-root');
196
- const root = createRoot(rootElement);
197
-
198
- root.render(React.createElement(IdCardManager, {
199
- onBatchExportComplete: (category, records) => {
200
- console.log(`Exported ${records.length} cards in ${category}`);
201
- }
202
- }));
203
- </script>
204
- ```
73
+ | Prop | Type | Default | Description |
74
+ |---|---|---|---|
75
+ | `sampleRecords` | `object` | `default data` | Pass your own database records to populate the dashboard. |
76
+ | `categories` | `object` | `default config` | Custom category definitions for different ID types. |
77
+ | `onBatchExportComplete` | `function` | `undefined` | Callback fired when PDF generation completes. |
205
78
 
206
- ### 3. Framework-Agnostic Pure JS Batch Print Engine (`generateIdCardsPdf`)
207
- The core multi-page A4 and US Letter PDF rendering engine (**`generateIdCardsPdf`**) is completely framework-agnostic! Whether you are writing pure TypeScript, Node/Express frontend scripts, Vue, or Angular, you can import and run `generateIdCardsPdf()` directly without mounting any React UI components:
79
+ ### Standalone `<IdCardDesigner />` Props
208
80
 
209
- ```javascript
210
- import { generateIdCardsPdf } from "@stratametriq/id-card-designer";
81
+ If you are using the standalone designer component directly, you can pass these props to configure the editor:
211
82
 
212
- // Works natively across Vue, Angular, Svelte, and Vanilla JS!
213
- await generateIdCardsPdf({
214
- records: myDatabaseArray,
215
- templateSchema: myLoadedJsonSchema,
216
- orientation: "vertical",
217
- fileName: "Batch_Job_Output.pdf"
218
- });
83
+ ```jsx
84
+ <IdCardDesigner
85
+ width={350}
86
+ height={200}
87
+ template={template}
88
+ onSave={handleSave}
89
+ onExport={handleExport}
90
+ />
219
91
  ```
220
92
 
221
93
  ---
222
94
 
223
- ## 📖 Public API & Turnkey Dashboard Reference
95
+ ## 🧩 Templates
224
96
 
225
- When developers install `@stratametriq/id-card-designer` via npm, they can choose between two usage modes:
226
- 1. **Turnkey Dashboard Mode (`<IdCardManager />`)**: Drop in a single component to instantly display the complete multi-department dashboard (navigation tabs, live card stage, roster directory table, and batch PDF export engine).
227
- 2. **Custom Building Blocks Mode (`<IdCardDesignerModal />` + `<IdCardPreview />`)**: Import atomic components to embed only the popup studio or live card preview into custom-built interfaces.
97
+ Designs are saved and loaded as clean JSON schemas.
228
98
 
229
- ---
230
-
231
- ### 1. `<IdCardManager />` (Turnkey All-in-One Dashboard & 4-Step Master Workflow)
232
-
233
- The `<IdCardManager />` is the complete, out-of-the-box management suite. We engineered a **clean, full-width unified layout** with zero redundant navigation tabs so operators and end-users get a sleek, ultra-fast 4-step workflow:
234
-
235
- ```jsx
236
- import React from "react";
237
- import { IdCardManager } from "@stratametriq/id-card-designer";
238
- import "@stratametriq/id-card-designer/dist/index.css";
239
-
240
- export function MyOrganizationPortal() {
241
- return (
242
- <IdCardManager
243
- onSaveCategoryTemplate={(categoryKey, newTemplate) => {
244
- console.log(`Saved template for ${categoryKey}:`, newTemplate);
245
- }}
246
- onBatchExportComplete={(categoryKey, exportedRecords) => {
247
- console.log(`Exported ${exportedRecords.length} cards for ${categoryKey}`);
248
- }}
249
- />
250
- );
99
+ ```json
100
+ {
101
+ "id": "tpl_school_vertical_01",
102
+ "orientation": "vertical",
103
+ "width": 54,
104
+ "height": 86,
105
+ "elements": [
106
+ {
107
+ "id": "el_student_name",
108
+ "type": "field",
109
+ "fieldKey": "studentName",
110
+ "label": "Student Name",
111
+ "x": 2, "y": 48, "width": 50, "height": 7
112
+ }
113
+ ]
251
114
  }
252
115
  ```
253
116
 
254
- #### 🧩 The Clean 4-Step Master Workflow Architecture
255
-
256
- When users open `<IdCardManager />`, they interact with a unified, professional full-width screen broken into four logical steps:
257
-
258
- | Workflow Step | Section Title & Purpose | Detailed Functionality & Mathematical Features |
259
- | :--- | :--- | :--- |
260
- | **Step 1** | **Select Department / Organization Category** | A clean 4-card header grid showing your configured organization categories (e.g., *Student IDs*, *Faculty & Admin*, *Corporate HR*, *Hospital Portal*). Each card displays the number of bound data fields (`{fieldDefinitions.length} fields`) and template layouts (`{templateCount} template`). Clicking any card instantly switches the active category, isolating state, templates, and roster tables cleanly. |
261
- | **Step 2** | **Live Stage Preview & Studio Launcher** | A high-resolution vector canvas preview displaying the currently selected person's ID card in real-time. Includes:<br>• **Interactive Zoom Controls (`80% - 150%`)** alongside instant reset buttons.<br>• **Toggleable Grid & Measurement Rulers (`0-80mm`)** for visual precision inspection.<br>• **Launch Studio Canvas Button:** Opens our popup drag-and-drop design studio modal where operators can add new text fields, upload background textures, bind database keys, and drag elements around with snap-to-grid accuracy. |
262
- | **Step 3** | **Batch A4 Print Engine (`⚡ Live Sheet Matrix`)** | A commercial print-engine sidebar that calculates and exports production-ready multi-page grid sheets:<br>• **⚡ Live Sheet Matrix Calculation Box:** Dynamically computes physical sheet mathematics in real-time right before your eyes! When you toggle **Paper Sheet Size (`A4` vs `US Letter`)**, **Orientation (`Portrait` vs `Landscape` Sheet)**, or **Card Cut Size (`86×54mm Standard ID-1`, `90×50mm Business Card`, `100×70mm Event Badge`)**, the matrix immediately recalculates the exact column × row capacity (`e.g., 3 Cols × 3 Rows = 9 cards/page`) and total job pages required.<br>• **Hardware Cut Guides Checkboxes:** Toggle corner crosshair cut marks (`0.35mm stroke`), card perimeter cut outline guides, and technical registration headers (`PRECISION CUT SHEET — JOB SPECIFICATIONS`) for print shop operators. |
263
- | **Step 4** | **Live Roster Directory Table & Instant Search** | Displays an interactive data table of all records in that department equipped with:<br>• **🔍 Instant Search Input:** Type any name, admission/employee number, department, or phone number to instantly filter records right before your eyes.<br>• **🏷️ Quick Status Filter Pills (`All \| Selected \| Unselected`):** Isolate checked vs unchecked records instantly before batch printing.<br>• **⚡ Smart Batch Selection:** Clicking **Select Shown / Unselect Shown** smartly checks or unchecks *only the records matching your current search or filter* without disrupting unrelated records outside your filter! Clicking any row previews their rendered card live on stage in Step 2. |
264
-
265
- ---
266
-
267
- #### ⚡ Zero-Configuration Automatic Field Discovery (`Auto-Detecting User Database Columns`)
268
-
269
- You **never have to worry about missing fields**. If your database or user records contain custom columns that are not explicitly defined in `fieldDefinitions`, `<IdCardManager />` and our Studio Canvas (`ElementPropertyEditor`) handle them automatically:
270
- 1. **Auto-Discovery Scan:** When you open the Studio Canvas, our property engine scans `Object.keys(sampleData[0])` directly from the live database records you passed in.
271
- 2. **Auto-Formatting:** Raw database keys like `bloodGroup`, `busRouteNo`, `emergencyPhone`, `allergyAlert`, or `parkingSlot` are automatically transformed into clean human-readable titles (e.g., **"Bus Route No (`busRouteNo`)"**).
272
- 3. **Instant Binding:** Every discovered key is automatically merged into the **`Data Field Key`** dropdown in the right sidebar under `4. ELEMENT PROPERTIES`. Any user can click `+ Add Element` ➡️ `Dynamic Field`, select their custom database key, and bind it immediately without writing a single line of code!
273
-
274
117
  ---
275
118
 
276
- ### 2. Customizing Categories & Dynamic Fields (`categories` & `sampleRecords` Props)
277
-
278
- By default, `<IdCardManager />` includes four global starter categories: **Student ID Cards (Education)**, **Faculty & Administration**, **Corporate Employee Badges**, and **Healthcare & Medical Pass**.
119
+ ## 🎨 Customization
279
120
 
280
- You can pass your own custom categories and live database records directly via props without editing the library:
121
+ You can define custom categories to control exactly what fields your ID cards should support.
281
122
 
282
123
  ```jsx
283
- const myCustomCategories = {
124
+ const myCategories = {
284
125
  university: {
285
126
  id: "university",
286
- label: "University Engineering Students",
287
- badge: "🎓 Higher Education",
288
- themeColor: "#0d6efd",
289
- defaultOrientation: "vertical",
290
- templateCount: 2,
291
- description: "Dynamic field binding tailored for enrollment numbers, engineering departments, and library barcodes.",
292
- fieldDefinitions: [
293
- { key: "studentName", label: "Student Full Name", defaultValue: "Aarav Sharma" },
294
- { key: "enrollmentNo", label: "Enrollment Number", defaultValue: "ENR-2026-991" },
295
- { key: "branch", label: "Engineering Branch", defaultValue: "Computer Science & Engineering" },
296
- { key: "year", label: "Academic Year", defaultValue: "B.Tech Year 3" },
297
- { key: "bloodGroup", label: "Blood Group", defaultValue: 'O+ POSITIVE' }
298
- ]
299
- },
300
- executives: {
301
- id: "executives",
302
- label: "Global Executive Badges",
303
- badge: "🏢 Corporate HQ",
304
- themeColor: "#6f42c1",
305
- defaultOrientation: "horizontal",
306
- templateCount: 1,
307
- description: "Dynamic field binding tailored for corporate executive designations, floor security clearance, and access barcodes.",
127
+ label: "University Students",
308
128
  fieldDefinitions: [
309
- { key: "execName", label: "Executive Full Name", defaultValue: "Elena Rostova" },
310
- { key: "designation", label: "Designation / Role", defaultValue: "VP of Cloud Engineering" },
311
- { key: "empCode", label: "Employee ID Code", defaultValue: "EMP-HQ-402" },
312
- { key: "clearance", label: "Security Clearance", defaultValue: "Level 5 (All Floors & Server Rooms)" }
129
+ { key: "studentName", label: "Student Full Name" },
130
+ { key: "enrollmentNo", label: "Enrollment Number" }
313
131
  ]
314
132
  }
315
133
  };
316
134
 
317
- const myLiveRecords = {
318
- university: [
319
- { studentName: "Aarav Sharma", enrollmentNo: "ENR-2026-991", branch: "Computer Science", year: "B.Tech Year 3", bloodGroup: "O+ POSITIVE" },
320
- { studentName: "Diya Patel", enrollmentNo: "ENR-2026-992", branch: "Electronics & Comm", year: "B.Tech Year 2", bloodGroup: "B+ POSITIVE" }
321
- ],
322
- executives: [
323
- { execName: "Elena Rostova", designation: "VP of Cloud Engineering", empCode: "EMP-HQ-402", clearance: "Level 5" }
324
- ]
325
- };
326
-
327
- export function CustomApp() {
328
- return (
329
- <IdCardManager
330
- categories={myCustomCategories}
331
- sampleRecords={myLiveRecords}
332
- />
333
- );
334
- }
135
+ <IdCardManager categories={myCategories} />
335
136
  ```
336
137
 
337
- ---
138
+ ### Modular Components
338
139
 
339
- ### 3. `<IdCardDesignerModal />` (Standalone Studio Modal)
140
+ If you don't want the full dashboard, you can use our modular components:
340
141
 
341
- The standalone interactive modal component for designing and modifying ID card templates. Use this when embedding only the popup studio inside your own custom interface without the turnkey dashboard.
342
-
343
- | Prop Name | Type | Default | Description |
344
- | :--- | :--- | :--- | :--- |
345
- | `show` | `boolean` | `false` | Controls visibility of the designer modal. |
346
- | `onHide` | `function` | `() => {}` | Callback triggered when closing the modal. |
347
- | `initialOrientation` | `string` | `"vertical"` | Default card orientation (`"vertical"` \| `"horizontal"`). |
348
- | `initialTemplate` | `object` | `null` | Existing JSON template schema to edit. If null, loads preset. |
349
- | `fieldDefinitions` | `array` | `[]` | Array of dynamic field options (`[{ key, label, defaultValue }]`). |
350
- | `sampleData` | `array` | `[]` | Array of data records to preview during designing. |
351
- | `themeColors` | `object` | `{ primary: "#424343", text: "#faf4f4" }` | Default primary header and text colors. |
352
- | `orgAssets` | `object` | `{ logoUrl, signatureUrl, defaultAvatarUrl }` | Default image URLs for logo, signature, and fallback photo. |
353
- | `onSaveTemplate` | `function` | `(templateSchema) => {}` | Callback returning the finalized JSON template object on save. |
142
+ * **`<IdCardPreview />`**: Embed a live ID card directly on a user profile page.
143
+ * **`<IdCardDesignerModal />`**: Open the drag-and-drop design studio inside your own popup.
144
+ * **`generateIdCardsPdf()`**: Trigger a high-resolution PDF export programmatically.
354
145
 
355
146
  ---
356
147
 
357
- ### 4. `<IdCardPreview />` (Atomic Card Renderer)
148
+ ## 📡 Events
149
+
150
+ You can hook into various lifecycle and user action events across the components:
358
151
 
359
- A lightweight component for rendering a single high-resolution vector ID card anywhere in your UI.
152
+ ### `<IdCardManager />` Events
153
+ - **`onBatchExportComplete(category, records)`**: Fired when a user successfully exports a batch of IDs to PDF.
360
154
 
361
- | Prop Name | Type | Default | Description |
362
- | :--- | :--- | :--- | :--- |
363
- | `templateSchema` | `object` | *Required* | The JSON template schema generated by the designer. |
364
- | `data` | `object` | `{}` | The record object containing dynamic field values to display. |
365
- | `orientation` | `string` | `"vertical"` | Orientation (`"vertical"` or `"horizontal"`). |
366
- | `zoom` | `number` | `1` | Scaling factor (`1` = exact physical dimensions, `1.5` = 150% size). |
367
- | `className` | `string` | `""` | Optional CSS class name for outer wrapper. |
155
+ ### `<IdCardDesigner />` Events
156
+ - **`onSave(templateData)`**: Fired when the user clicks the save button. Returns the full JSON schema of the current design.
157
+ - **`onExport(format, data)`**: Fired when an export action is triggered (e.g., exporting a single card to PNG or PDF).
158
+ - **`onChange(elementData)`**: Fired continuously as the user drags, resizes, or modifies elements on the canvas.
159
+ - **`onDelete(elementId)`**: Fired when a specific element is deleted from the canvas.
160
+ - **`onTemplateChange(templateId)`**: Fired when the user switches to a different template.
368
161
 
369
162
  ---
370
163
 
371
- ### 5. `generateIdCardsPdf(options)` (Programmatic Batch Print Utility)
372
-
373
- An asynchronous utility function to generate multi-page, high-resolution A4 or Letter PDFs for batch printing from anywhere in your application.
374
-
375
- ```javascript
376
- import { generateIdCardsPdf } from "@stratametriq/id-card-designer";
377
-
378
- await generateIdCardsPdf({
379
- records: [...], // Array of data records to render
380
- templateSchema: {...}, // JSON template schema object
381
- orientation: "vertical", // "vertical" | "horizontal"
382
- fileName: "ID_Cards_Sheet.pdf", // Name of the downloaded file
383
- pageOptions: {
384
- format: "a4", // Paper size ("a4" | "letter")
385
- scale: 2, // Resolution scale for html2canvas (2 = High DPI)
386
- marginMm: 10, // Top/side page margins in mm
387
- spacingMm: 10, // Gap between cards in mm
388
- showCropMarks: true, // Add corner crosshair cut guides
389
- showCutOutline: true, // Add faint card perimeter borders
390
- showHeader: true // Add technical registration header
391
- },
392
- onProgress: (current, total) => {
393
- console.log(`Rendered page ${current} of ${total}`);
394
- }
395
- });
396
- ```
164
+ ## 💡 Examples
397
165
 
398
- ---
166
+ ### Connect Your Own Data (React)
399
167
 
400
- ### 6. JSON Template Schema Structure (`templateSchema`)
168
+ ```jsx
169
+ import { IdCardManager } from '@stratametriq/id-card-designer';
170
+ import '@stratametriq/id-card-designer/dist/index.css';
401
171
 
402
- Every design created in `<IdCardDesignerModal />` is stored and exported as a clean, serializable JSON schema:
172
+ export default function MyPortal() {
173
+ const myRealStudents = [
174
+ { studentName: "Aarav Sharma", admissionNo: "101", bloodGroup: "O+" },
175
+ { studentName: "Diya Patel", admissionNo: "102", bloodGroup: "B+" }
176
+ ];
403
177
 
404
- ```json
405
- {
406
- "id": "tpl_school_vertical_01",
407
- "name": "Classic Vertical ID",
408
- "orientation": "vertical",
409
- "width": 54,
410
- "height": 86,
411
- "background": {
412
- "color": "#ffffff",
413
- "image": "https://myportal.com/assets/card-bg-watermark.png",
414
- "size": "cover"
415
- },
416
- "elements": [
417
- {
418
- "id": "el_header_box",
419
- "type": "shape",
420
- "label": "Top Header Box",
421
- "x": 0, "y": 0, "width": 54, "height": 14,
422
- "backgroundColor": "#0d6efd",
423
- "zIndex": 1
424
- },
425
- {
426
- "id": "el_photo_slot",
427
- "type": "image",
428
- "subtype": "photo",
429
- "fieldKey": "profilePhoto",
430
- "label": "Student Photo",
431
- "x": 14, "y": 18, "width": 26, "height": 28,
432
- "borderWidth": 1.5, "borderColor": "#0d6efd", "borderRadius": 4,
433
- "zIndex": 3
434
- },
435
- {
436
- "id": "el_student_name",
437
- "type": "field",
438
- "fieldKey": "studentName",
439
- "label": "Student Name",
440
- "x": 2, "y": 48, "width": 50, "height": 7,
441
- "fontFamily": "Inter, sans-serif",
442
- "fontSize": 11, "fontWeight": "bold", "color": "#111111",
443
- "textAlign": "center", "textTransform": "uppercase",
444
- "zIndex": 4
445
- }
446
- ]
178
+ return (
179
+ <IdCardManager sampleRecords={{ student: myRealStudents }} />
180
+ );
447
181
  }
448
182
  ```
449
183
 
450
- ---
451
-
452
- ## 🏢 Multi-Department Architecture (The Dictionary Pattern)
453
-
454
- If your software serves multiple organizational departments (e.g., **Students** vs. **Teachers** vs. **Hospital Doctors** vs. **Corporate HR**), you **do not need multiple modal components or hardcoded libraries**. Instead, use the **Dictionary Pattern** to silo category schemas while sharing a single universal `<IdCardDesignerModal />` or `<IdCardManager />` instance:
184
+ ### Mounting in Vue, Angular, or Vanilla HTML
455
185
 
456
- ```javascript
457
- const CATEGORY_CONFIGS = {
458
- student: {
459
- title: "Student ID Cards",
460
- defaultOrientation: "vertical",
461
- fieldDefinitions: [
462
- { key: "studentName", label: "Student Full Name", defaultValue: "Aarav Sharma" },
463
- { key: "admissionNo", label: "Admission Number", defaultValue: "ADM-2026-089" },
464
- { key: "classSec", label: "Class & Section", defaultValue: "Grade 10 [A]" }
465
- ]
466
- },
467
- staff: {
468
- title: "Faculty & Staff Directory",
469
- defaultOrientation: "horizontal",
470
- fieldDefinitions: [
471
- { key: "facultyName", label: "Faculty / Staff Name", defaultValue: "Dr. Ananya Iyer" },
472
- { key: "empCode", label: "Employee ID Code", defaultValue: "EMP-FAC-104" },
473
- { key: "designation", label: "Job Designation", defaultValue: "Senior Physics Lecturer" }
474
- ]
475
- }
476
- };
477
- ```
478
-
479
- ---
186
+ ```html
187
+ <div id="id-card-manager-root"></div>
188
+ <script type="module">
189
+ import React from 'react';
190
+ import { createRoot } from 'react-dom/client';
191
+ import { IdCardManager } from '@stratametriq/id-card-designer';
192
+ import '@stratametriq/id-card-designer/dist/index.css';
480
193
 
481
- ## 🏗️ Recommended Consumer App Architecture (`my-consumer-app/`)
482
-
483
- When integrating `@stratametriq/id-card-designer` into an enterprise or institutional web application (e.g., School Management System, Hospital Portal, or Corporate HR Suite), we recommend structuring your project with clean separation of concerns:
484
-
485
- ```text
486
- my-consumer-app/
487
- ├── src/
488
- │ ├── config/
489
- │ │ └── idCardFields.js # 1. Centralized field definitions & mappings across categories
490
- │ │
491
- │ ├── services/
492
- │ │ └── idCardApi.js # 2. API helper methods to load/save JSON templates & records from backend
493
- │ │
494
- │ ├── components/
495
- │ │ └── id-cards/
496
- │ │ ├── CardTemplateStudio.jsx # 3. Admin component wrapping <IdCardDesignerModal />
497
- │ │ ├── CardPreviewBadge.jsx # 4. Reusable UI component wrapping <IdCardPreview />
498
- │ │ └── BatchPrintActions.jsx # 5. Component managing high-DPI PDF generation & progress (`generateIdCardsPdf`)
499
- │ │
500
- │ ├── pages/
501
- │ │ ├── AdminSettingsPage.jsx # Uses <CardTemplateStudio /> for administrators to design ID cards
502
- │ │ └── StaffDirectoryPage.jsx # Uses <CardPreviewBadge /> and <BatchPrintActions /> for staff/student rosters
503
- │ └── main.jsx # Imports global "@stratametriq/id-card-designer/dist/index.css"
194
+ const root = createRoot(document.getElementById('id-card-manager-root'));
195
+ root.render(React.createElement(IdCardManager));
196
+ </script>
504
197
  ```
505
198
 
506
- ### 🗂️ Explanation of Key Architectural Components
507
-
508
- 1. **`src/config/idCardFields.js` (Centralized Configuration)**
509
- Maintains all available data fields for each department. By isolating fields in config, adding new custom fields (`bloodGroup`, `busRoute`, `rfidTag`) never requires modifying UI components:
510
- ```javascript
511
- export const ID_CARD_FIELDS = {
512
- student: [
513
- { key: "studentName", label: "Student Full Name" },
514
- { key: "admissionNo", label: "Admission Number" },
515
- { key: "bloodGroup", label: "Blood Group" }
516
- ],
517
- staff: [
518
- { key: "staffName", label: "Staff Member Name" },
519
- { key: "designation", label: "Job Title / Role" }
520
- ]
521
- };
522
- ```
523
-
524
- 2. **`src/services/idCardApi.js` (API & Storage Layer)**
525
- Handles communicating with your backend server or local storage to persist the JSON template schemas (`templateSchema`) saved by administrators:
526
- ```javascript
527
- export async function fetchCategoryTemplate(categoryKey) {
528
- const res = await fetch(`/api/id-cards/templates/${categoryKey}`);
529
- return res.json();
530
- }
531
-
532
- export async function saveCategoryTemplate(categoryKey, schema) {
533
- return fetch(`/api/id-cards/templates/${categoryKey}`, {
534
- method: "POST",
535
- headers: { "Content-Type": "application/json" },
536
- body: JSON.stringify(schema)
537
- });
538
- }
539
- ```
540
-
541
- 3. **`src/components/id-cards/CardTemplateStudio.jsx` (Admin Studio Wrapper)**
542
- Wraps `<IdCardDesignerModal />` with your application's custom saving logic and category switcher:
543
- ```jsx
544
- import React, { useState } from "react";
545
- import { IdCardDesignerModal } from "@stratametriq/id-card-designer";
546
- import { ID_CARD_FIELDS } from "../../config/idCardFields";
547
- import { saveCategoryTemplate } from "../../services/idCardApi";
548
-
549
- export function CardTemplateStudio({ categoryKey = "student", initialSchema }) {
550
- const [showModal, setShowModal] = useState(false);
551
-
552
- return (
553
- <div>
554
- <button onClick={() => setShowModal(true)}>Open ID Card Designer</button>
555
- <IdCardDesignerModal
556
- show={showModal}
557
- onHide={() => setShowModal(false)}
558
- initialTemplate={initialSchema}
559
- fieldDefinitions={ID_CARD_FIELDS[categoryKey]}
560
- onSaveTemplate={async (schema) => {
561
- await saveCategoryTemplate(categoryKey, schema);
562
- setShowModal(false);
563
- }}
564
- />
565
- </div>
566
- );
567
- }
568
- ```
569
-
570
- 4. **`src/components/id-cards/CardPreviewBadge.jsx` (Reusable Live Badge)**
571
- Wraps `<IdCardPreview />` to render clean vector ID cards in directory listings, profile popups, or student tables:
572
- ```jsx
573
- import React from "react";
574
- import { IdCardPreview } from "@stratametriq/id-card-designer";
575
-
576
- export function CardPreviewBadge({ recordData, templateSchema }) {
577
- return (
578
- <div className="card-preview-wrapper shadow-md rounded-lg overflow-hidden">
579
- <IdCardPreview
580
- templateSchema={templateSchema}
581
- data={recordData}
582
- zoom={1}
583
- />
584
- </div>
585
- );
586
- }
587
- ```
588
-
589
- 5. **`src/components/id-cards/BatchPrintActions.jsx` (Batch Print Utility Button)**
590
- Manages batch exporting checked staff or student records into multi-page A4 or Letter sheets:
591
- ```jsx
592
- import React, { useState } from "react";
593
- import { generateIdCardsPdf } from "@stratametriq/id-card-designer";
594
-
595
- export function BatchPrintActions({ selectedRecords, templateSchema }) {
596
- const [exporting, setExporting] = useState(false);
597
-
598
- const handleExport = async () => {
599
- setExporting(true);
600
- await generateIdCardsPdf({
601
- records: selectedRecords,
602
- templateSchema: templateSchema,
603
- orientation: templateSchema?.orientation || "vertical",
604
- fileName: "Batch_ID_Cards_Job.pdf",
605
- pageOptions: { format: "a4", showCropMarks: true, showCutOutline: true }
606
- });
607
- setExporting(false);
608
- };
609
-
610
- return (
611
- <button onClick={handleExport} disabled={exporting || selectedRecords.length === 0}>
612
- {exporting ? "Generating PDF Sheets..." : `Batch Print (${selectedRecords.length} Cards)`}
613
- </button>
614
- );
615
- }
616
- ```
617
-
618
- 6. **`src/main.jsx` (Global Stylesheet Import)**
619
- Always import the universal stylesheet right at the root entry point of your application:
620
- ```javascript
621
- import React from 'react';
622
- import ReactDOM from 'react-dom/client';
623
- import App from './App.jsx';
624
- import "@stratametriq/id-card-designer/dist/index.css";
625
-
626
- ReactDOM.createRoot(document.getElementById('root')).render(<App />);
627
- ```
628
-
629
199
  ---
630
200
 
631
- ## ❓ Frequently Asked Questions (FAQ)
632
-
633
- **Q: Why should my company use this instead of a design tool like Canva?**
634
- **A:** Canva is a manual design tool; our software is an **automation pipeline**. If a school has 1,000 students, using a consumer design app requires HR to manually type 1,000 names, crop 1,000 photos, generate 1,000 QR codes, and manually align them on A4 paper (80+ hours of work).
635
- By embedding `@stratametriq/id-card-designer` directly into your ERP, your users click one "Batch Print" button. Our engine pulls the data from your database, maps the variables, generates 1,000 QR codes, calculates the A4 cut-sheet math, and spits out a 112-page PDF in exactly 3 seconds.
201
+ ## ❓ FAQ & Comparisons
636
202
 
637
- **Q: Our non-technical HR team doesn't know how to code. How do they use this?**
638
- **A:** They will never see a single line of code! Your engineering team installs our NPM package into your codebase just once. From that point on, your non-technical users get a beautiful, intuitive visual dashboard inside your app to drag-and-drop elements and manage batches.
203
+ **Q: How is this different from Canva?**
204
+ **A:** Canva is fantastic for creating manual, one-off designs. However, if you need to generate 500 student ID cards with unique photos, barcodes, and names, Canva becomes tedious. This package is an **automation pipeline**—you design the template once, feed it an array of JSON data, and instantly generate thousands of unique cards.
639
205
 
640
- **Q: Is our sensitive employee data sent to your servers?**
641
- **A:** No. Our library runs 100% **Client-Side** in the browser. When your users generate ID cards, the data never leaves their local machine, ensuring full GDPR and data privacy compliance.
206
+ **Q: Why not just use standard HTML-to-Image libraries directly?**
207
+ **A:** Building a production-ready ID card designer from scratch using standard HTML-to-canvas libraries is incredibly frustrating. You have to handle exact hardware printing dimensions (like CR80 PVC card aspect ratios), perfect image scaling, drag-and-drop boundary logic, and multi-page A4 PDF rendering with precise cut-marks. We've solved all of that complex math for you out-of-the-box.
642
208
 
643
- **Q: Is it white-labeled?**
644
- **A:** Yes, the Commercial Enterprise license allows you to completely remove all Stratametriq branding. Your customers will assume you built this incredible feature from scratch!
209
+ **Q: How does this compare to enterprise desktop ID software?**
210
+ **A:** Traditional ID software usually requires heavy Windows installations and expensive per-seat licenses. This package allows you to bring that exact same enterprise-level design capability directly into your web app as a lightweight React component that works on Mac, Windows, and Linux.
645
211
 
646
- **Q: How do I know this NPM package isn't malware that will hack our ERP?**
647
- **A:** Our codebase is 100% unminified and transparent. Your security engineers can read every line of code. Furthermore, our engine makes **zero network requests** (no "phone home" APIs) and runs entirely client-side. It has no access to your backend servers, database, or environment variables, making data exfiltration impossible.
212
+ **Q: Does our sensitive data leave our servers?**
213
+ **A:** **Absolutely not.** Employee and student data (PII) is a massive security concern. That is why this engine runs **100% Client-Side** in the browser. Zero network requests are made to external servers. The PDFs and images are generated purely on the user's local machine.
648
214
 
649
- **Q: What does my engineering team need in order to install this?**
650
- **A:** The prerequisites are simple:
651
- 1. **Node.js** environment.
652
- 2. A modern package manager (**npm, yarn, or pnpm**).
653
- 3. A frontend application running **React 17/18** or **Next.js** (Vue/Angular require a React adapter).
215
+ **Q: Can I remove your branding? (White-labeling)**
216
+ **A:** Yes! The enterprise license is 100% white-label, allowing you to seamlessly integrate the designer into your own SaaS product without your users ever knowing you are using our software.
654
217
 
655
218
  ---
656
219
 
657
220
  ## 📜 License
658
221
 
659
- Dual-licensed under the [MIT License](./LICENSE) (for open-source/non-commercial) and a Commercial Enterprise License (for commercial usage). © Stratametriq
222
+ `@stratametriq/id-card-designer` is dual-licensed:
223
+
224
+ 1. **Community / Open Source Tier (MIT License):** Free for non-commercial evaluation and personal open-source projects. See [MIT License](./LICENSE).
225
+ 2. **Commercial / Enterprise Tier:** Required for commercial SaaS applications, School ERPs, HR suites, and production use.
226
+
227
+ 👉 **[Purchase a Commercial Enterprise License to Unlock Production Usage & Priority Support](https://waniabid.gumroad.com/l/id-card-designer-pro)**