/**
* QR Code Generator Usage Examples
*
* This file demonstrates how to use the QR generator module
* for various QR code generation scenarios.
*/
const API_BASE_URL = 'https://mcp.profullstack.com'; // Live MCP server URL
/**
* Example 1: Basic QR Code Generation
*/
async function basicQRExample() {
console.log('π± Example 1: Basic QR Code Generation');
try {
const response = await fetch(`${API_BASE_URL}/tools/qr-generator`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
text: 'Hello, World!',
}),
});
const result = await response.json();
if (result.result) {
const qr = result.result;
console.log('β
QR code generated successfully!');
console.log(`π Text: "${qr.input.text}"`);
console.log(`π Size: ${qr.qrCode.size.pixels}x${qr.qrCode.size.pixels} pixels`);
console.log(`π§ Format: ${qr.metadata.format.toUpperCase()}`);
console.log(`π Modules: ${qr.qrCode.size.modules}x${qr.qrCode.size.modules}`);
console.log(`πΎ Data length: ${qr.qrCode.data.length} characters`);
console.log(`π Capacity utilization: ${qr.statistics.capacity.utilization}%`);
} else {
console.error('β Failed to generate QR code:', result.error);
}
} catch (error) {
console.error('β Error:', error.message);
}
}
/**
* Example 2: URL QR Code
*/
async function urlQRExample() {
console.log('\nπ Example 2: URL QR Code Generation');
try {
const response = await fetch(`${API_BASE_URL}/tools/qr-generator`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
text: 'https://github.com/profullstack/mcp-server',
size: 250,
errorCorrectionLevel: 'M',
}),
});
const result = await response.json();
if (result.result) {
const qr = result.result;
console.log('β
URL QR code generated!');
console.log(`π URL: ${qr.input.text}`);
console.log(`π Size: ${qr.qrCode.size.pixels}px`);
console.log(`π‘οΈ Error Correction: ${qr.metadata.errorCorrectionLevel}`);
console.log('π± Usage: Scan with any QR code reader to open URL');
console.log(`π‘ Tip: ${qr.usage.description}`);
} else {
console.error('β Failed to generate URL QR code:', result.error);
}
} catch (error) {
console.error('β Error:', error.message);
}
}
/**
* Example 2.5: Browser-Opening QR Code with Live MCP Server
*/
async function browserOpeningQRExample() {
console.log('\nπ Example 2.5: Browser-Opening QR Code with Live MCP Server');
try {
const response = await fetch(`${API_BASE_URL}/tools/qr-generator`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
text: 'https://mcp.profullstack.com',
size: 250,
errorCorrectionLevel: 'M',
format: 'png',
}),
});
const result = await response.json();
if (result.result) {
const qr = result.result;
console.log('β
Browser-opening QR code generated!');
console.log(`π URL: ${qr.input.text}`);
console.log(`π Size: ${qr.qrCode.size.pixels}px`);
console.log(`π‘οΈ Error Correction: ${qr.metadata.errorCorrectionLevel}`);
console.log(`π± Format: ${qr.metadata.format.toUpperCase()}`);
console.log('π± Usage: Scan with smartphone camera to open website');
console.log(`πΎ Data size: ${qr.qrCode.data.length} characters`);
console.log('\nπ Implementation Examples:');
console.log('HTML:');
console.log(
` <img src="data:${qr.qrCode.mimeType};base64,${qr.qrCode.data.substring(0, 50)}..." alt="QR Code" />`
);
console.log('\nJavaScript:');
console.log(' const img = document.createElement("img");');
console.log(` img.src = "data:${qr.qrCode.mimeType};base64," + qrCodeData;`);
console.log(' document.body.appendChild(img);');
console.log('\nπ― Perfect for:');
console.log(' β’ Business cards with website links');
console.log(' β’ Marketing materials');
console.log(' β’ Event flyers');
console.log(' β’ Product packaging');
console.log(' β’ Digital displays');
console.log(`\nπ‘ Tip: ${qr.usage.description}`);
} else {
console.error('β Failed to generate browser-opening QR code:', result.error);
}
} catch (error) {
console.error('β Error:', error.message);
}
}
/**
* Example 3: High-Quality Print QR Code (SVG)
*/
async function printQRExample() {
console.log('\nπ¨οΈ Example 3: High-Quality Print QR Code (SVG)');
try {
const response = await fetch(`${API_BASE_URL}/tools/qr-generator`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
text: 'Print-quality QR code for business cards and flyers',
size: 400,
format: 'svg',
errorCorrectionLevel: 'H',
margin: 6,
}),
});
const result = await response.json();
if (result.result) {
const qr = result.result;
console.log('β
Print-quality QR code generated!');
console.log(`π Format: ${qr.metadata.format.toUpperCase()} (vector graphics)`);
console.log(`π Size: ${qr.qrCode.size.pixels}px (scalable)`);
console.log(`π‘οΈ Error Correction: ${qr.metadata.errorCorrectionLevel} (High - 30%)`);
console.log(`π Margin: ${qr.metadata.margin} modules`);
console.log('π¨οΈ Perfect for: Business cards, flyers, posters');
console.log(`πΎ SVG data length: ${qr.qrCode.data.length} characters`);
// Show how to decode SVG
console.log('\nπ To use SVG data:');
console.log(' const svgMarkup = Buffer.from(qrCode.data, "base64").toString();');
} else {
console.error('β Failed to generate print QR code:', result.error);
}
} catch (error) {
console.error('β Error:', error.message);
}
}
/**
* Example 4: Contact vCard QR Code
*/
async function contactQRExample() {
console.log('\nπ€ Example 4: Contact vCard QR Code');
const vcard = `BEGIN:VCARD
VERSION:3.0
FN:John Doe
ORG:Profullstack, Inc.
TITLE:Software Engineer
TEL:+1-555-123-4567
EMAIL:john.doe@profullstack.com
URL:https://profullstack.com
ADR:;;123 Tech Street;San Francisco;CA;94105;USA
NOTE:Scan to add contact information
END:VCARD`;
try {
const response = await fetch(`${API_BASE_URL}/tools/qr-generator`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
text: vcard,
size: 300,
errorCorrectionLevel: 'Q',
}),
});
const result = await response.json();
if (result.result) {
const qr = result.result;
console.log('β
Contact vCard QR code generated!');
console.log('π€ Contact: John Doe');
console.log('π’ Organization: Profullstack, Inc.');
console.log(`π Size: ${qr.qrCode.size.pixels}px`);
console.log(`π Text length: ${qr.input.textLength} characters`);
console.log(`π‘οΈ Error Correction: ${qr.metadata.errorCorrectionLevel} (Quartile - 25%)`);
console.log('π± Usage: Scan to add contact to phone');
console.log(`π Encoding: ${qr.statistics.input.encoding} mode`);
} else {
console.error('β Failed to generate contact QR code:', result.error);
}
} catch (error) {
console.error('β Error:', error.message);
}
}
/**
* Example 5: WiFi Network QR Code
*/
async function wifiQRExample() {
console.log('\nπΆ Example 5: WiFi Network QR Code');
const wifiConfig = 'WIFI:T:WPA;S:MyHomeNetwork;P:supersecurepassword123;H:false;;';
try {
const response = await fetch(`${API_BASE_URL}/tools/qr-generator`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
text: wifiConfig,
size: 250,
errorCorrectionLevel: 'H',
}),
});
const result = await response.json();
if (result.result) {
const qr = result.result;
console.log('β
WiFi QR code generated!');
console.log('πΆ Network: MyHomeNetwork');
console.log('π Security: WPA');
console.log(`π Size: ${qr.qrCode.size.pixels}px`);
console.log(
`π‘οΈ Error Correction: ${qr.metadata.errorCorrectionLevel} (High - passwords are critical)`
);
console.log('π± Usage: Scan to connect to WiFi network');
console.log('β οΈ Note: Contains sensitive password information');
} else {
console.error('β Failed to generate WiFi QR code:', result.error);
}
} catch (error) {
console.error('β Error:', error.message);
}
}
/**
* Example 6: Base64 Data URL QR Code (Ready for HTML)
*/
async function base64QRExample() {
console.log('\nπΌοΈ Example 6: Base64 Data URL QR Code');
try {
const response = await fetch(`${API_BASE_URL}/tools/qr-generator`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
text: 'Ready-to-use data URL format',
format: 'base64',
}),
});
const result = await response.json();
if (result.result) {
const qr = result.result;
console.log('β
Base64 data URL QR code generated!');
console.log(`π§ Format: ${qr.metadata.format.toUpperCase()}`);
console.log(`π Encoding: ${qr.qrCode.encoding}`);
console.log('π Ready for HTML: Yes');
console.log(`πΎ Data URL length: ${qr.qrCode.data.length} characters`);
console.log('π Usage example:');
console.log(` <img src="${qr.qrCode.data.substring(0, 50)}..." alt="QR Code" />`);
console.log(`π‘ Tip: ${qr.usage.description}`);
} else {
console.error('β Failed to generate base64 QR code:', result.error);
}
} catch (error) {
console.error('β Error:', error.message);
}
}
/**
* Example 7: Different Error Correction Levels Comparison
*/
async function errorCorrectionComparisonExample() {
console.log('\nπ‘οΈ Example 7: Error Correction Levels Comparison');
const testText = 'Error correction comparison test';
const levels = ['L', 'M', 'Q', 'H'];
const descriptions = {
L: 'Low (~7% correction)',
M: 'Medium (~15% correction)',
Q: 'Quartile (~25% correction)',
H: 'High (~30% correction)',
};
try {
console.log('π Generating QR codes with different error correction levels...\n');
for (const level of levels) {
const response = await fetch(`${API_BASE_URL}/tools/qr-generator`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
text: testText,
errorCorrectionLevel: level,
size: 200,
}),
});
const result = await response.json();
if (result.result) {
const qr = result.result;
console.log(`π‘οΈ Level ${level}: ${descriptions[level]}`);
console.log(` π Modules: ${qr.qrCode.size.modules}x${qr.qrCode.size.modules}`);
console.log(` πΎ Data size: ${qr.qrCode.data.length} chars`);
console.log(` π Capacity used: ${qr.statistics.capacity.utilization}%`);
console.log(` π― Best for: ${getBestUseCase(level)}\n`);
}
}
console.log('π‘ Key takeaways:');
console.log(' β’ Higher error correction = larger QR codes');
console.log(' β’ Higher error correction = better damage resistance');
console.log(' β’ Choose based on your use case and environment');
} catch (error) {
console.error('β Error:', error.message);
}
}
/**
* Example 8: Size Optimization Example
*/
async function sizeOptimizationExample() {
console.log('\nπ Example 8: Size Optimization');
const testCases = [
{ text: '1234567890', description: 'Numeric (most efficient)' },
{ text: 'HELLO123', description: 'Alphanumeric (efficient)' },
{ text: 'Hello, World!', description: 'Mixed case (standard)' },
{ text: 'Hello, δΈη! π', description: 'Unicode (least efficient)' },
];
try {
console.log('π Testing encoding efficiency with different text types...\n');
for (const testCase of testCases) {
const response = await fetch(`${API_BASE_URL}/tools/qr-generator`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
text: testCase.text,
size: 200,
}),
});
const result = await response.json();
if (result.result) {
const qr = result.result;
console.log(`π ${testCase.description}:`);
console.log(` Text: "${testCase.text}"`);
console.log(` π Encoding: ${qr.statistics.input.encoding}`);
console.log(` π Modules: ${qr.qrCode.size.modules}x${qr.qrCode.size.modules}`);
console.log(` β‘ Efficiency: ${qr.statistics.input.efficiency}`);
console.log(` π Utilization: ${qr.statistics.capacity.utilization}%\n`);
}
}
console.log('π‘ Optimization tips:');
console.log(' β’ Use numbers only when possible (numeric mode)');
console.log(' β’ Use uppercase letters for alphanumeric mode');
console.log(' β’ Avoid special characters and Unicode when possible');
console.log(' β’ Consider text length vs. QR code size trade-offs');
} catch (error) {
console.error('β Error:', error.message);
}
}
/**
* Example 9: Batch QR Code Generation
*/
async function batchQRExample() {
console.log('\nπ¦ Example 9: Batch QR Code Generation');
const batchData = [
{ id: 'product-001', text: 'https://store.example.com/product/001', type: 'Product URL' },
{ id: 'contact-john', text: 'mailto:john@example.com', type: 'Email' },
{ id: 'phone-support', text: 'tel:+1-555-123-4567', type: 'Phone' },
{ id: 'location-hq', text: 'geo:37.7749,-122.4194', type: 'Location' },
];
try {
console.log(`π Generating ${batchData.length} QR codes...\n`);
const results = [];
for (const item of batchData) {
const response = await fetch(`${API_BASE_URL}/tools/qr-generator`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
text: item.text,
size: 150,
}),
});
const result = await response.json();
if (result.result) {
results.push({
id: item.id,
type: item.type,
success: true,
size: result.result.qrCode.size.modules,
dataLength: result.result.qrCode.data.length,
});
console.log(`β
${item.id}: ${item.type}`);
console.log(` π Text: ${item.text}`);
console.log(
` π Size: ${result.result.qrCode.size.modules}x${result.result.qrCode.size.modules} modules`
);
} else {
results.push({
id: item.id,
type: item.type,
success: false,
error: result.error,
});
console.log(`β ${item.id}: Failed - ${result.error}`);
}
}
console.log('\nπ Batch Generation Summary:');
const successful = results.filter(r => r.success).length;
console.log(`β
Successful: ${successful}/${results.length}`);
console.log(`β Failed: ${results.length - successful}/${results.length}`);
if (successful > 0) {
const avgSize =
results.filter(r => r.success).reduce((sum, r) => sum + r.size, 0) / successful;
console.log(`π Average size: ${Math.round(avgSize)}x${Math.round(avgSize)} modules`);
}
} catch (error) {
console.error('β Error:', error.message);
}
}
/**
* Example 10: QR Code Information and Validation
*/
async function qrInfoExample() {
console.log('\nπ Example 10: QR Code Information and Validation');
const testTexts = [
'Short text',
'This is a longer text that will require more space in the QR code',
'a'.repeat(1000), // Long text
'a'.repeat(5000), // Too long text
];
try {
for (let i = 0; i < testTexts.length; i++) {
const text = testTexts[i];
console.log(`\nπ Test ${i + 1}: ${text.length} characters`);
try {
const response = await fetch(
`${API_BASE_URL}/qr-generator/info?text=${encodeURIComponent(text)}&errorCorrectionLevel=M`
);
const info = await response.json();
if (info.canEncode) {
console.log('β
Can encode: Yes');
console.log(`π Text length: ${info.info.textLength}/${info.info.maxLength}`);
console.log(`π Estimated size: ${info.info.estimatedSize.description}`);
console.log(`π‘οΈ Error correction: ${info.info.errorCorrectionLevel}`);
} else {
console.log('β Can encode: No');
console.log(`π Text length: ${text.length} (too long)`);
}
} catch (error) {
console.log(`β Validation failed: ${error.message}`);
}
}
console.log('\nπ‘ Validation tips:');
console.log(' β’ Check text length before generation');
console.log(' β’ Use info endpoint to estimate QR code size');
console.log(' β’ Consider error correction level impact on capacity');
} catch (error) {
console.error('β Error:', error.message);
}
}
/**
* Helper function to get best use case for error correction level
*/
function getBestUseCase(level) {
const useCases = {
L: 'Clean environments, digital displays',
M: 'General use, web, mobile apps',
Q: 'Print materials, business cards',
H: 'Outdoor use, damaged surfaces',
};
return useCases[level] || 'General use';
}
/**
* Main function to run all examples
*/
async function runExamples() {
console.log('π QR Code Generator Usage Examples\n');
console.log('π Setup Instructions:');
console.log('1. Ensure the MCP server is running on the correct port');
console.log('2. The QR generator module uses the qrcode library');
console.log('3. No external API dependencies - fully self-contained');
console.log('4. Supports PNG, SVG, and Base64 output formats');
console.log('5. Run: node examples/usage-example.js\n');
// Run examples with delays to avoid overwhelming the console
await basicQRExample();
await new Promise(resolve => setTimeout(resolve, 500));
await urlQRExample();
await new Promise(resolve => setTimeout(resolve, 500));
await browserOpeningQRExample();
await new Promise(resolve => setTimeout(resolve, 500));
await printQRExample();
await new Promise(resolve => setTimeout(resolve, 500));
await contactQRExample();
await new Promise(resolve => setTimeout(resolve, 500));
await wifiQRExample();
await new Promise(resolve => setTimeout(resolve, 500));
await base64QRExample();
await new Promise(resolve => setTimeout(resolve, 500));
await errorCorrectionComparisonExample();
await new Promise(resolve => setTimeout(resolve, 500));
await sizeOptimizationExample();
await new Promise(resolve => setTimeout(resolve, 500));
await batchQRExample();
await new Promise(resolve => setTimeout(resolve, 500));
await qrInfoExample();
console.log('\n⨠All QR generator examples completed!');
console.log('\nπ‘ Key Features:');
console.log('β’ Multiple output formats (PNG, SVG, Base64)');
console.log('β’ Customizable size, error correction, and margin');
console.log('β’ Support for up to 4,296 characters');
console.log('β’ Optimized presets for different use cases');
console.log('β’ Comprehensive validation and error handling');
console.log('β’ No data storage - stateless operation');
console.log('β’ Binary image data ready for immediate use');
}
// Run examples if this script is executed directly
if (import.meta.url === `file://${process.argv[1]}`) {
runExamples().catch(console.error);
}
export {
basicQRExample,
urlQRExample,
browserOpeningQRExample,
printQRExample,
contactQRExample,
wifiQRExample,
base64QRExample,
errorCorrectionComparisonExample,
sizeOptimizationExample,
batchQRExample,
qrInfoExample,
};