@stratametriq/id-card-designer 1.5.0 → 1.6.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 +127 -569
  2. package/dist/index.es.js +8729 -8582
  3. package/dist/index.js +117 -112
  4. package/package.json +28 -11
package/README.md CHANGED
@@ -4,35 +4,30 @@
4
4
  ![NPM Downloads](https://img.shields.io/npm/dm/@stratametriq/id-card-designer?style=for-the-badge&color=success)
5
5
  ![License](https://img.shields.io/npm/l/@stratametriq/id-card-designer?style=for-the-badge&color=orange)
6
6
 
7
- A universal, dynamic, and highly customizable ID Card Designer, Turnkey Dashboard & A4 Multi-Page PDF Rendering Engine for React, Vue, Angular, and Vanilla JS.
7
+ A universal, dynamic, and highly customizable **ID Card Designer & Batch Print Dashboard** for React, Vue, Angular, and Vanilla JS.
8
8
 
9
- 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.
10
-
11
- ## 🚀 What's New in v1.5.0
12
-
13
- - **Dedicated Bulk CSV Import Workspace**: Uploading a `.csv` file now creates a pristine "Imported Data" workspace tab in your dashboard, automatically extracting CSV headers as dynamic text fields for the studio property inspector!
14
- - **Expanded Printing Dimensions**: The A4 Engine is no longer just A4! The dashboard and the underlying PDF generator now natively support mathematical layout matrices for **A3, A4, A5, US Letter, and US Legal** paper sheets.
15
- - **Flawless Landscape PDF Scaling**: Rewrote core engine logic to flawlessly handle and rotate hardware crop marks during multi-page landscape batch PDF generation.
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.
16
10
 
17
11
  ---
18
12
 
19
- ## 🌟 Features
13
+ ## 📑 Table of Contents
20
14
 
21
- - **🎨 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.
22
- - **📁 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*).
23
- - **🔳 QR Code & Barcode Generation:** Built-in deterministic, high-resolution vector 1D Barcode (`<Barcode />`) and 2D QR Code (`<QrCode />`) generation with live database key binding.
24
- - **🏷️ Variable Placeholders (`{{name}}`, `{{employeeId}}`):** Seamless handlebar/mustache syntax interpolation across text labels, custom formulas, prefixes, and suffixes (`e.g., ID: {{admissionNo}} - {{studentName}}`).
25
- - **📥 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.
26
- - **🖼️ 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**.
27
- - **🔄 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).
28
- - **📏 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`).
29
- - **🖼️ 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**.
30
- - **🔤 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**.
31
- - **🔍 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)
32
25
 
33
26
  ---
34
27
 
35
- ## 📦 Installation
28
+ ## 💻 Installation
29
+
30
+ Install the package using NPM or Yarn:
36
31
 
37
32
  ```bash
38
33
  npm install @stratametriq/id-card-designer
@@ -40,630 +35,193 @@ npm install @stratametriq/id-card-designer
40
35
  yarn add @stratametriq/id-card-designer
41
36
  ```
42
37
 
43
- Include the stylesheet in your project root (`main.jsx` or `App.jsx`):
44
-
45
- ```javascript
46
- import "@stratametriq/id-card-designer/dist/index.css";
47
- ```
48
-
49
- ---
50
-
51
- ## 💼 Commercial & Enterprise Licensing
52
-
53
- `@stratametriq/id-card-designer` is dual-licensed to support both open-source developers and commercial enterprises:
54
-
55
- 1. **Community / Open Source Tier (MIT License):**
56
- Free for non-commercial evaluation, personal open-source projects, and rendering standalone static preview widgets (`<IdCardPreview />`).
57
- 2. **Commercial / Enterprise Tier (Commercial License):**
58
- 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.
59
-
60
- 👉 **[Purchase a Commercial Enterprise License ($49 - $499) to Unlock Production Usage, White-Labeling & Priority Support](https://waniabid.gumroad.com/l/id-card-designer-pro)**
61
-
62
38
  ---
63
39
 
64
- ## 🚀 Sweet & Simple Guide: How to Use with Real Data & Features
65
-
66
- 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!
40
+ ## ⚡ Quick Start
67
41
 
68
- ### Option 1: Turnkey All-In-One Dashboard (`<IdCardManager />`)
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)
69
43
 
70
- 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!
71
45
 
72
46
  ```jsx
73
- import React, { useState, useEffect } from 'react';
74
47
  import { IdCardManager } from '@stratametriq/id-card-designer';
75
48
  import '@stratametriq/id-card-designer/dist/index.css';
76
49
 
77
- export default function SchoolPortal() {
78
- const [dbRecords, setDbRecords] = useState({ student: [], staff: [] });
79
-
80
- // 1. Fetch real students/employees from your backend (Node.js, Laravel, Supabase, etc.)
81
- useEffect(() => {
82
- fetch('https://api.yourschool.com/students')
83
- .then(res => res.json())
84
- .then(data => setDbRecords({ student: data }));
85
- }, []);
86
-
87
- // 2. Pass your live data right into <IdCardManager />!
88
- return (
89
- <IdCardManager
90
- sampleRecords={dbRecords}
91
-
92
- // Save customized card designs back to your database
93
- onSaveCategoryTemplate={(category, templateSchema) => {
94
- console.log(`Saving ${category} template to DB:`, templateSchema);
95
- }}
96
-
97
- // Listen when batch PDF export completes
98
- onBatchExportComplete={(category, exportedRecords) => {
99
- console.log(`Generated A4 PDF for ${exportedRecords.length} records!`);
100
- }}
101
- />
102
- );
50
+ export default function App() {
51
+ // This will render the complete turnkey dashboard with demo data!
52
+ return <IdCardManager />;
103
53
  }
104
54
  ```
105
55
 
106
56
  ---
107
57
 
108
- ### Option 2: Building Custom Screens (Using Modular Features)
109
-
110
- 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**:
111
-
112
- #### A. Show a Live ID Card on a Student Profile Page (`<IdCardPreview />`)
113
- ```jsx
114
- import { IdCardPreview } from '@stratametriq/id-card-designer';
115
-
116
- function StudentProfilePage({ realStudentData, savedTemplateJson }) {
117
- return (
118
- <div className="profile-card-widget">
119
- <h3>Student ID Card</h3>
120
-
121
- {/* Automatically binds realStudentData fields into the template */}
122
- <IdCardPreview
123
- templateSchema={savedTemplateJson}
124
- data={realStudentData} // e.g. { studentName: 'Aarav Patel', admissionNo: 'ADM-101', profilePhoto: '...' }
125
- orientation="vertical"
126
- zoom={1.2}
127
- />
128
- </div>
129
- );
130
- }
131
- ```
132
-
133
- #### B. Trigger Batch A4 PDF Export from Your Own Custom Button (`generateIdCardsPdf`)
134
- ```jsx
135
- import { generateIdCardsPdf } from '@stratametriq/id-card-designer';
136
-
137
- function CustomRosterTable({ selectedStudents, activeTemplate }) {
138
- const handlePrint = async () => {
139
- // Generate high-resolution A4 multi-page PDF directly from your data array
140
- await generateIdCardsPdf({
141
- records: selectedStudents,
142
- templateSchema: activeTemplate,
143
- orientation: 'vertical',
144
- fileName: `Student_Cards_Batch_${new Date().toISOString().slice(0,10)}.pdf`,
145
- pageOptions: { format: 'a4', showCropMarks: true }
146
- });
147
- };
148
-
149
- return <button onClick={handlePrint}>Download A4 Print Sheet ({selectedStudents.length} Cards)</button>;
150
- }
151
- ```
152
-
153
- #### C. Open the Drag-and-Drop Studio inside Your Own Modal (`<IdCardDesignerModal />`)
154
- ```jsx
155
- import { IdCardDesignerModal } from '@stratametriq/id-card-designer';
156
-
157
- function DesignButton({ currentTemplate, onSaveToDatabase }) {
158
- const [isOpen, setIsOpen] = useState(false);
58
+ ## 🌟 Features
159
59
 
160
- return (
161
- <>
162
- <button onClick={() => setIsOpen(true)}>✨ Design Card Layout</button>
163
-
164
- <IdCardDesignerModal
165
- show={isOpen}
166
- onHide={() => setIsOpen(false)}
167
- initialTemplate={currentTemplate}
168
- sampleData={[{ studentName: 'Sample Student', admissionNo: '101' }]}
169
- onSaveTemplate={(newTemplate) => {
170
- onSaveToDatabase(newTemplate);
171
- setIsOpen(false);
172
- }}
173
- />
174
- </>
175
- );
176
- }
177
- ```
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.
178
66
 
179
67
  ---
180
68
 
181
- ## 🌐 Multi-Framework & Vanilla JS Support (`Vue`, `Angular`, `Svelte`, `Next.js` & `HTML`)
182
-
183
- 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**:
184
-
185
- ### 1. Using in React & Next.js (`React 18 / Vite / Remix / Next.js`)
186
- Simply import our components directly into your React JSX/TSX tree:
187
- ```jsx
188
- import { IdCardManager } from "@stratametriq/id-card-designer";
189
- ```
190
-
191
- ### 2. Using in Vue, Angular, Svelte, or Vanilla HTML (`Micro-Frontend Mounting`)
192
- 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:
193
-
194
- ```html
195
- <!-- Inside index.html or your Vue/Angular/Svelte component template -->
196
- <div id="id-card-manager-root"></div>
69
+ ## ⚙️ Props
197
70
 
198
- <script type="module">
199
- import React from 'react';
200
- import { createRoot } from 'react-dom/client';
201
- import { IdCardManager } from '@stratametriq/id-card-designer';
202
- import '@stratametriq/id-card-designer/dist/index.css';
71
+ The main `<IdCardManager />` component accepts the following props:
203
72
 
204
- // Mount the visual ID Card Dashboard cleanly inside any HTML div
205
- const rootElement = document.getElementById('id-card-manager-root');
206
- const root = createRoot(rootElement);
207
-
208
- root.render(React.createElement(IdCardManager, {
209
- onBatchExportComplete: (category, records) => {
210
- console.log(`Exported ${records.length} cards in ${category}`);
211
- }
212
- }));
213
- </script>
214
- ```
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. |
215
78
 
216
- ### 3. Framework-Agnostic Pure JS Batch Print Engine (`generateIdCardsPdf`)
217
- 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
218
80
 
219
- ```javascript
220
- 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:
221
82
 
222
- // Works natively across Vue, Angular, Svelte, and Vanilla JS!
223
- await generateIdCardsPdf({
224
- records: myDatabaseArray,
225
- templateSchema: myLoadedJsonSchema,
226
- orientation: "vertical",
227
- fileName: "Batch_Job_Output.pdf"
228
- });
83
+ ```jsx
84
+ <IdCardDesigner
85
+ width={350}
86
+ height={200}
87
+ template={template}
88
+ onSave={handleSave}
89
+ onExport={handleExport}
90
+ />
229
91
  ```
230
92
 
231
93
  ---
232
94
 
233
- ## 📖 Public API & Turnkey Dashboard Reference
234
-
235
- When developers install `@stratametriq/id-card-designer` via npm, they can choose between two usage modes:
236
- 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).
237
- 2. **Custom Building Blocks Mode (`<IdCardDesignerModal />` + `<IdCardPreview />`)**: Import atomic components to embed only the popup studio or live card preview into custom-built interfaces.
238
-
239
- ---
240
-
241
- ### 1. `<IdCardManager />` (Turnkey All-in-One Dashboard & 4-Step Master Workflow)
95
+ ## 🧩 Templates
242
96
 
243
- 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:
97
+ Designs are saved and loaded as clean JSON schemas.
244
98
 
245
- ```jsx
246
- import React from "react";
247
- import { IdCardManager } from "@stratametriq/id-card-designer";
248
- import "@stratametriq/id-card-designer/dist/index.css";
249
-
250
- export function MyOrganizationPortal() {
251
- return (
252
- <IdCardManager
253
- onSaveCategoryTemplate={(categoryKey, newTemplate) => {
254
- console.log(`Saved template for ${categoryKey}:`, newTemplate);
255
- }}
256
- onBatchExportComplete={(categoryKey, exportedRecords) => {
257
- console.log(`Exported ${exportedRecords.length} cards for ${categoryKey}`);
258
- }}
259
- />
260
- );
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
+ ]
261
114
  }
262
115
  ```
263
116
 
264
- #### 🧩 The Clean 4-Step Master Workflow Architecture
265
-
266
- When users open `<IdCardManager />`, they interact with a unified, professional full-width screen broken into four logical steps:
267
-
268
- | Workflow Step | Section Title & Purpose | Detailed Functionality & Mathematical Features |
269
- | :--- | :--- | :--- |
270
- | **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. |
271
- | **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. |
272
- | **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. |
273
- | **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. |
274
-
275
- ---
276
-
277
- #### ⚡ Zero-Configuration Automatic Field Discovery (`Auto-Detecting User Database Columns`)
278
-
279
- 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:
280
- 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.
281
- 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`)"**).
282
- 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!
283
-
284
117
  ---
285
118
 
286
- ### 2. Customizing Categories & Dynamic Fields (`categories` & `sampleRecords` Props)
119
+ ## 🎨 Customization
287
120
 
288
- By default, `<IdCardManager />` includes four global starter categories: **Student ID Cards (Education)**, **Faculty & Administration**, **Corporate Employee Badges**, and **Healthcare & Medical Pass**.
289
-
290
- 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.
291
122
 
292
123
  ```jsx
293
- const myCustomCategories = {
124
+ const myCategories = {
294
125
  university: {
295
126
  id: "university",
296
- label: "University Engineering Students",
297
- badge: "🎓 Higher Education",
298
- themeColor: "#0d6efd",
299
- defaultOrientation: "vertical",
300
- templateCount: 2,
301
- description: "Dynamic field binding tailored for enrollment numbers, engineering departments, and library barcodes.",
127
+ label: "University Students",
302
128
  fieldDefinitions: [
303
- { key: "studentName", label: "Student Full Name", defaultValue: "Aarav Sharma" },
304
- { key: "enrollmentNo", label: "Enrollment Number", defaultValue: "ENR-2026-991" },
305
- { key: "branch", label: "Engineering Branch", defaultValue: "Computer Science & Engineering" },
306
- { key: "year", label: "Academic Year", defaultValue: "B.Tech Year 3" },
307
- { key: "bloodGroup", label: "Blood Group", defaultValue: 'O+ POSITIVE' }
308
- ]
309
- },
310
- executives: {
311
- id: "executives",
312
- label: "Global Executive Badges",
313
- badge: "🏢 Corporate HQ",
314
- themeColor: "#6f42c1",
315
- defaultOrientation: "horizontal",
316
- templateCount: 1,
317
- description: "Dynamic field binding tailored for corporate executive designations, floor security clearance, and access barcodes.",
318
- fieldDefinitions: [
319
- { key: "execName", label: "Executive Full Name", defaultValue: "Elena Rostova" },
320
- { key: "designation", label: "Designation / Role", defaultValue: "VP of Cloud Engineering" },
321
- { key: "empCode", label: "Employee ID Code", defaultValue: "EMP-HQ-402" },
322
- { 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" }
323
131
  ]
324
132
  }
325
133
  };
326
134
 
327
- const myLiveRecords = {
328
- university: [
329
- { studentName: "Aarav Sharma", enrollmentNo: "ENR-2026-991", branch: "Computer Science", year: "B.Tech Year 3", bloodGroup: "O+ POSITIVE" },
330
- { studentName: "Diya Patel", enrollmentNo: "ENR-2026-992", branch: "Electronics & Comm", year: "B.Tech Year 2", bloodGroup: "B+ POSITIVE" }
331
- ],
332
- executives: [
333
- { execName: "Elena Rostova", designation: "VP of Cloud Engineering", empCode: "EMP-HQ-402", clearance: "Level 5" }
334
- ]
335
- };
336
-
337
- export function CustomApp() {
338
- return (
339
- <IdCardManager
340
- categories={myCustomCategories}
341
- sampleRecords={myLiveRecords}
342
- />
343
- );
344
- }
135
+ <IdCardManager categories={myCategories} />
345
136
  ```
346
137
 
347
- ---
348
-
349
- ### 3. `<IdCardDesignerModal />` (Standalone Studio Modal)
138
+ ### Modular Components
350
139
 
351
- 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.
140
+ If you don't want the full dashboard, you can use our modular components:
352
141
 
353
- | Prop Name | Type | Default | Description |
354
- | :--- | :--- | :--- | :--- |
355
- | `show` | `boolean` | `false` | Controls visibility of the designer modal. |
356
- | `onHide` | `function` | `() => {}` | Callback triggered when closing the modal. |
357
- | `initialOrientation` | `string` | `"vertical"` | Default card orientation (`"vertical"` \| `"horizontal"`). |
358
- | `initialTemplate` | `object` | `null` | Existing JSON template schema to edit. If null, loads preset. |
359
- | `fieldDefinitions` | `array` | `[]` | Array of dynamic field options (`[{ key, label, defaultValue }]`). |
360
- | `sampleData` | `array` | `[]` | Array of data records to preview during designing. |
361
- | `themeColors` | `object` | `{ primary: "#424343", text: "#faf4f4" }` | Default primary header and text colors. |
362
- | `orgAssets` | `object` | `{ logoUrl, signatureUrl, defaultAvatarUrl }` | Default image URLs for logo, signature, and fallback photo. |
363
- | `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.
364
145
 
365
146
  ---
366
147
 
367
- ### 4. `<IdCardPreview />` (Atomic Card Renderer)
148
+ ## 📡 Events
368
149
 
369
- A lightweight component for rendering a single high-resolution vector ID card anywhere in your UI.
150
+ You can hook into various lifecycle and user action events across the components:
370
151
 
371
- | Prop Name | Type | Default | Description |
372
- | :--- | :--- | :--- | :--- |
373
- | `templateSchema` | `object` | *Required* | The JSON template schema generated by the designer. |
374
- | `data` | `object` | `{}` | The record object containing dynamic field values to display. |
375
- | `orientation` | `string` | `"vertical"` | Orientation (`"vertical"` or `"horizontal"`). |
376
- | `zoom` | `number` | `1` | Scaling factor (`1` = exact physical dimensions, `1.5` = 150% size). |
377
- | `className` | `string` | `""` | Optional CSS class name for outer wrapper. |
152
+ ### `<IdCardManager />` Events
153
+ - **`onBatchExportComplete(category, records)`**: Fired when a user successfully exports a batch of IDs to PDF.
154
+
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.
378
161
 
379
162
  ---
380
163
 
381
- ### 5. `generateIdCardsPdf(options)` (Programmatic Batch Print Utility)
382
-
383
- An asynchronous utility function to generate multi-page, high-resolution A4 or Letter PDFs for batch printing from anywhere in your application.
384
-
385
- ```javascript
386
- import { generateIdCardsPdf } from "@stratametriq/id-card-designer";
387
-
388
- await generateIdCardsPdf({
389
- records: [...], // Array of data records to render
390
- templateSchema: {...}, // JSON template schema object
391
- orientation: "vertical", // "vertical" | "horizontal"
392
- fileName: "ID_Cards_Sheet.pdf", // Name of the downloaded file
393
- pageOptions: {
394
- format: "a4", // Paper size ("a4" | "letter")
395
- scale: 2, // Resolution scale for html2canvas (2 = High DPI)
396
- marginMm: 10, // Top/side page margins in mm
397
- spacingMm: 10, // Gap between cards in mm
398
- showCropMarks: true, // Add corner crosshair cut guides
399
- showCutOutline: true, // Add faint card perimeter borders
400
- showHeader: true // Add technical registration header
401
- },
402
- onProgress: (current, total) => {
403
- console.log(`Rendered page ${current} of ${total}`);
404
- }
405
- });
406
- ```
164
+ ## 💡 Examples
407
165
 
408
- ---
166
+ ### Connect Your Own Data (React)
409
167
 
410
- ### 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';
411
171
 
412
- 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
+ ];
413
177
 
414
- ```json
415
- {
416
- "id": "tpl_school_vertical_01",
417
- "name": "Classic Vertical ID",
418
- "orientation": "vertical",
419
- "width": 54,
420
- "height": 86,
421
- "background": {
422
- "color": "#ffffff",
423
- "image": "https://myportal.com/assets/card-bg-watermark.png",
424
- "size": "cover"
425
- },
426
- "elements": [
427
- {
428
- "id": "el_header_box",
429
- "type": "shape",
430
- "label": "Top Header Box",
431
- "x": 0, "y": 0, "width": 54, "height": 14,
432
- "backgroundColor": "#0d6efd",
433
- "zIndex": 1
434
- },
435
- {
436
- "id": "el_photo_slot",
437
- "type": "image",
438
- "subtype": "photo",
439
- "fieldKey": "profilePhoto",
440
- "label": "Student Photo",
441
- "x": 14, "y": 18, "width": 26, "height": 28,
442
- "borderWidth": 1.5, "borderColor": "#0d6efd", "borderRadius": 4,
443
- "zIndex": 3
444
- },
445
- {
446
- "id": "el_student_name",
447
- "type": "field",
448
- "fieldKey": "studentName",
449
- "label": "Student Name",
450
- "x": 2, "y": 48, "width": 50, "height": 7,
451
- "fontFamily": "Inter, sans-serif",
452
- "fontSize": 11, "fontWeight": "bold", "color": "#111111",
453
- "textAlign": "center", "textTransform": "uppercase",
454
- "zIndex": 4
455
- }
456
- ]
178
+ return (
179
+ <IdCardManager sampleRecords={{ student: myRealStudents }} />
180
+ );
457
181
  }
458
182
  ```
459
183
 
460
- ---
461
-
462
- ## 🏢 Multi-Department Architecture (The Dictionary Pattern)
463
-
464
- 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:
465
-
466
- ```javascript
467
- const CATEGORY_CONFIGS = {
468
- student: {
469
- title: "Student ID Cards",
470
- defaultOrientation: "vertical",
471
- fieldDefinitions: [
472
- { key: "studentName", label: "Student Full Name", defaultValue: "Aarav Sharma" },
473
- { key: "admissionNo", label: "Admission Number", defaultValue: "ADM-2026-089" },
474
- { key: "classSec", label: "Class & Section", defaultValue: "Grade 10 [A]" }
475
- ]
476
- },
477
- staff: {
478
- title: "Faculty & Staff Directory",
479
- defaultOrientation: "horizontal",
480
- fieldDefinitions: [
481
- { key: "facultyName", label: "Faculty / Staff Name", defaultValue: "Dr. Ananya Iyer" },
482
- { key: "empCode", label: "Employee ID Code", defaultValue: "EMP-FAC-104" },
483
- { key: "designation", label: "Job Designation", defaultValue: "Senior Physics Lecturer" }
484
- ]
485
- }
486
- };
487
- ```
184
+ ### Mounting in Vue, Angular, or Vanilla HTML
488
185
 
489
- ---
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';
490
193
 
491
- ## 🏗️ Recommended Consumer App Architecture (`my-consumer-app/`)
492
-
493
- 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:
494
-
495
- ```text
496
- my-consumer-app/
497
- ├── src/
498
- │ ├── config/
499
- │ │ └── idCardFields.js # 1. Centralized field definitions & mappings across categories
500
- │ │
501
- │ ├── services/
502
- │ │ └── idCardApi.js # 2. API helper methods to load/save JSON templates & records from backend
503
- │ │
504
- │ ├── components/
505
- │ │ └── id-cards/
506
- │ │ ├── CardTemplateStudio.jsx # 3. Admin component wrapping <IdCardDesignerModal />
507
- │ │ ├── CardPreviewBadge.jsx # 4. Reusable UI component wrapping <IdCardPreview />
508
- │ │ └── BatchPrintActions.jsx # 5. Component managing high-DPI PDF generation & progress (`generateIdCardsPdf`)
509
- │ │
510
- │ ├── pages/
511
- │ │ ├── AdminSettingsPage.jsx # Uses <CardTemplateStudio /> for administrators to design ID cards
512
- │ │ └── StaffDirectoryPage.jsx # Uses <CardPreviewBadge /> and <BatchPrintActions /> for staff/student rosters
513
- │ └── 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>
514
197
  ```
515
198
 
516
- ### 🗂️ Explanation of Key Architectural Components
517
-
518
- 1. **`src/config/idCardFields.js` (Centralized Configuration)**
519
- 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:
520
- ```javascript
521
- export const ID_CARD_FIELDS = {
522
- student: [
523
- { key: "studentName", label: "Student Full Name" },
524
- { key: "admissionNo", label: "Admission Number" },
525
- { key: "bloodGroup", label: "Blood Group" }
526
- ],
527
- staff: [
528
- { key: "staffName", label: "Staff Member Name" },
529
- { key: "designation", label: "Job Title / Role" }
530
- ]
531
- };
532
- ```
533
-
534
- 2. **`src/services/idCardApi.js` (API & Storage Layer)**
535
- Handles communicating with your backend server or local storage to persist the JSON template schemas (`templateSchema`) saved by administrators:
536
- ```javascript
537
- export async function fetchCategoryTemplate(categoryKey) {
538
- const res = await fetch(`/api/id-cards/templates/${categoryKey}`);
539
- return res.json();
540
- }
541
-
542
- export async function saveCategoryTemplate(categoryKey, schema) {
543
- return fetch(`/api/id-cards/templates/${categoryKey}`, {
544
- method: "POST",
545
- headers: { "Content-Type": "application/json" },
546
- body: JSON.stringify(schema)
547
- });
548
- }
549
- ```
550
-
551
- 3. **`src/components/id-cards/CardTemplateStudio.jsx` (Admin Studio Wrapper)**
552
- Wraps `<IdCardDesignerModal />` with your application's custom saving logic and category switcher:
553
- ```jsx
554
- import React, { useState } from "react";
555
- import { IdCardDesignerModal } from "@stratametriq/id-card-designer";
556
- import { ID_CARD_FIELDS } from "../../config/idCardFields";
557
- import { saveCategoryTemplate } from "../../services/idCardApi";
558
-
559
- export function CardTemplateStudio({ categoryKey = "student", initialSchema }) {
560
- const [showModal, setShowModal] = useState(false);
561
-
562
- return (
563
- <div>
564
- <button onClick={() => setShowModal(true)}>Open ID Card Designer</button>
565
- <IdCardDesignerModal
566
- show={showModal}
567
- onHide={() => setShowModal(false)}
568
- initialTemplate={initialSchema}
569
- fieldDefinitions={ID_CARD_FIELDS[categoryKey]}
570
- onSaveTemplate={async (schema) => {
571
- await saveCategoryTemplate(categoryKey, schema);
572
- setShowModal(false);
573
- }}
574
- />
575
- </div>
576
- );
577
- }
578
- ```
579
-
580
- 4. **`src/components/id-cards/CardPreviewBadge.jsx` (Reusable Live Badge)**
581
- Wraps `<IdCardPreview />` to render clean vector ID cards in directory listings, profile popups, or student tables:
582
- ```jsx
583
- import React from "react";
584
- import { IdCardPreview } from "@stratametriq/id-card-designer";
585
-
586
- export function CardPreviewBadge({ recordData, templateSchema }) {
587
- return (
588
- <div className="card-preview-wrapper shadow-md rounded-lg overflow-hidden">
589
- <IdCardPreview
590
- templateSchema={templateSchema}
591
- data={recordData}
592
- zoom={1}
593
- />
594
- </div>
595
- );
596
- }
597
- ```
598
-
599
- 5. **`src/components/id-cards/BatchPrintActions.jsx` (Batch Print Utility Button)**
600
- Manages batch exporting checked staff or student records into multi-page A4 or Letter sheets:
601
- ```jsx
602
- import React, { useState } from "react";
603
- import { generateIdCardsPdf } from "@stratametriq/id-card-designer";
604
-
605
- export function BatchPrintActions({ selectedRecords, templateSchema }) {
606
- const [exporting, setExporting] = useState(false);
607
-
608
- const handleExport = async () => {
609
- setExporting(true);
610
- await generateIdCardsPdf({
611
- records: selectedRecords,
612
- templateSchema: templateSchema,
613
- orientation: templateSchema?.orientation || "vertical",
614
- fileName: "Batch_ID_Cards_Job.pdf",
615
- pageOptions: { format: "a4", showCropMarks: true, showCutOutline: true }
616
- });
617
- setExporting(false);
618
- };
619
-
620
- return (
621
- <button onClick={handleExport} disabled={exporting || selectedRecords.length === 0}>
622
- {exporting ? "Generating PDF Sheets..." : `Batch Print (${selectedRecords.length} Cards)`}
623
- </button>
624
- );
625
- }
626
- ```
627
-
628
- 6. **`src/main.jsx` (Global Stylesheet Import)**
629
- Always import the universal stylesheet right at the root entry point of your application:
630
- ```javascript
631
- import React from 'react';
632
- import ReactDOM from 'react-dom/client';
633
- import App from './App.jsx';
634
- import "@stratametriq/id-card-designer/dist/index.css";
635
-
636
- ReactDOM.createRoot(document.getElementById('root')).render(<App />);
637
- ```
638
-
639
199
  ---
640
200
 
641
- ## ❓ Frequently Asked Questions (FAQ)
642
-
643
- **Q: Why should my company use this instead of a design tool like Canva?**
644
- **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).
645
- 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
646
202
 
647
- **Q: Our non-technical HR team doesn't know how to code. How do they use this?**
648
- **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.
649
205
 
650
- **Q: Is our sensitive employee data sent to your servers?**
651
- **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.
652
208
 
653
- **Q: Is it white-labeled?**
654
- **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.
655
211
 
656
- **Q: How do I know this NPM package isn't malware that will hack our ERP?**
657
- **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.
658
214
 
659
- **Q: What does my engineering team need in order to install this?**
660
- **A:** The prerequisites are simple:
661
- 1. **Node.js** environment.
662
- 2. A modern package manager (**npm, yarn, or pnpm**).
663
- 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.
664
217
 
665
218
  ---
666
219
 
667
220
  ## 📜 License
668
221
 
669
- 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)**