Implement professional PDF-based label printing for boxes and locations
- Replace ZPL/image-based printing with ReportLab PDF generation - Box labels: 8cm x 5cm landscape with 'BOX Nr:' header and CODE128 barcode - Location labels: 8cm x 5cm landscape with 'Location nr:' header and CODE128 barcode - Add /generate_box_label_pdf endpoint using same approach as print_module - Update FG scan quick box creation to use PDF printing with default printer - Switch from CDN QZ Tray to local patched version for pairing-key auth - Improve error handling and logging throughout printing workflow - Fix import issues (add mm unit to warehouse.py) - Optimize barcode size and spacing for better readability
This commit is contained in:
@@ -510,11 +510,13 @@ async function printLocationBarcode() {
|
||||
|
||||
printStatus.textContent = 'Sending to printer...';
|
||||
|
||||
// Configure QZ Tray for PDF printing with 4x8cm size
|
||||
// Configure QZ Tray for PDF printing with 8x5cm size in landscape
|
||||
const config = qzTray.configs.create(selectedPrinter, {
|
||||
size: { width: 4, height: 8, units: 'cm' },
|
||||
margins: { top: 0, right: 0, bottom: 0, left: 0 },
|
||||
orientation: 'portrait'
|
||||
scaleContent: false,
|
||||
rasterize: false,
|
||||
size: { width: 80, height: 50 },
|
||||
units: 'mm',
|
||||
margins: { top: 0, right: 0, bottom: 0, left: 0 }
|
||||
});
|
||||
|
||||
const data = [{
|
||||
|
||||
@@ -3,8 +3,8 @@
|
||||
{% block title %}Finish Good Scan{% endblock %}
|
||||
{% block head %}
|
||||
<link rel="stylesheet" href="{{ url_for('static', filename='css/scan.css') }}">
|
||||
<!-- QZ Tray for printing -->
|
||||
<script src="https://cdn.jsdelivr.net/npm/qz-tray@2.2.0/qz-tray.min.js"></script>
|
||||
<!-- QZ Tray for printing - using local patched version for pairing-key authentication -->
|
||||
<script src="{{ url_for('static', filename='qz-tray.js') }}"></script>
|
||||
<style>
|
||||
.error-message {
|
||||
color: #ff4444;
|
||||
@@ -714,11 +714,12 @@ document.addEventListener('DOMContentLoaded', function() {
|
||||
if (result.success && result.box_number) {
|
||||
const boxNumber = result.box_number;
|
||||
|
||||
// Step 2: Print the box label using QZ Tray
|
||||
// Step 2: Generate PDF label and print using QZ Tray
|
||||
try {
|
||||
// Check QZ Tray connection
|
||||
if (!window.qz || !window.qz.websocket.isActive()) {
|
||||
throw new Error('QZ Tray not connected. Please ensure QZ Tray is running.');
|
||||
console.log('QZ Tray not connected, attempting to connect...');
|
||||
await window.qz.websocket.connect();
|
||||
}
|
||||
|
||||
// Get available printers
|
||||
@@ -727,17 +728,59 @@ document.addEventListener('DOMContentLoaded', function() {
|
||||
throw new Error('No printers found');
|
||||
}
|
||||
|
||||
// Use first available printer
|
||||
const printer = printers[0];
|
||||
// Try to get default printer, fallback to first available
|
||||
let printer;
|
||||
try {
|
||||
printer = await window.qz.printers.getDefault();
|
||||
console.log('Using default printer:', printer);
|
||||
} catch (e) {
|
||||
printer = printers[0];
|
||||
console.log('Default printer not found, using first available:', printer);
|
||||
}
|
||||
|
||||
// Create ZPL code for box label
|
||||
const zpl = `^XA
|
||||
^FO50,50^A0N,40,40^FDBox: ${boxNumber}^FS
|
||||
^FO50,120^BY2,3,80^BCN,80,Y,N,N^FD${boxNumber}^FS
|
||||
^XZ`;
|
||||
// Generate PDF from backend
|
||||
const formData = new FormData();
|
||||
formData.append('box_number', boxNumber);
|
||||
|
||||
const config = window.qz.configs.create(printer);
|
||||
await window.qz.print(config, [zpl]);
|
||||
const pdfResponse = await fetch('/generate_box_label_pdf', {
|
||||
method: 'POST',
|
||||
body: formData
|
||||
});
|
||||
|
||||
if (!pdfResponse.ok) {
|
||||
throw new Error('Failed to generate PDF label');
|
||||
}
|
||||
|
||||
// Get PDF as blob and convert to base64
|
||||
const pdfBlob = await pdfResponse.blob();
|
||||
const pdfBase64 = await new Promise((resolve, reject) => {
|
||||
const reader = new FileReader();
|
||||
reader.onloadend = () => {
|
||||
const base64 = reader.result.split(',')[1];
|
||||
resolve(base64);
|
||||
};
|
||||
reader.onerror = reject;
|
||||
reader.readAsDataURL(pdfBlob);
|
||||
});
|
||||
|
||||
console.log('PDF generated, sending to printer...');
|
||||
|
||||
// Configure QZ Tray for PDF printing
|
||||
const config = window.qz.configs.create(printer, {
|
||||
scaleContent: false,
|
||||
rasterize: false,
|
||||
size: { width: 80, height: 50 },
|
||||
units: 'mm',
|
||||
margins: { top: 0, right: 0, bottom: 0, left: 0 }
|
||||
});
|
||||
|
||||
const printData = [{
|
||||
type: 'pdf',
|
||||
format: 'base64',
|
||||
data: pdfBase64
|
||||
}];
|
||||
|
||||
await window.qz.print(config, printData);
|
||||
|
||||
showNotification(`✅ Box ${boxNumber} created and label printed!`, 'success');
|
||||
|
||||
@@ -748,8 +791,9 @@ document.addEventListener('DOMContentLoaded', function() {
|
||||
|
||||
} catch (printError) {
|
||||
console.error('Print error:', printError);
|
||||
showNotification(`⚠️ Box ${boxNumber} created but print failed: ${printError.message}`, 'warning');
|
||||
showNotification(`⚠️ Box ${boxNumber} created but print failed: ${printError.message}\n\nPlease ensure QZ Tray is running and a printer is available.`, 'warning');
|
||||
// Still keep modal open for manual entry
|
||||
document.getElementById('scan-box-input').value = boxNumber;
|
||||
document.getElementById('scan-box-input').focus();
|
||||
}
|
||||
|
||||
@@ -757,11 +801,12 @@ document.addEventListener('DOMContentLoaded', function() {
|
||||
throw new Error(result.error || 'Failed to create box');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error creating box:', error);
|
||||
showNotification('❌ Error creating box: ' + error.message, 'error');
|
||||
} finally {
|
||||
// Re-enable button
|
||||
this.disabled = false;
|
||||
this.textContent = 'Quick Box Label Creation';
|
||||
this.textContent = '📦 Quick Box Label Creation';
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
@@ -472,6 +472,7 @@ function updateBoxPreview() {
|
||||
|
||||
// QZ Tray functionality
|
||||
async function initQZTray() {
|
||||
console.log('=== Initializing QZ Tray ===');
|
||||
try {
|
||||
if (!window.qz) {
|
||||
console.error('QZ Tray library not loaded');
|
||||
@@ -479,23 +480,42 @@ async function initQZTray() {
|
||||
return;
|
||||
}
|
||||
|
||||
console.log('QZ Tray library loaded');
|
||||
console.log('Current connection status:', window.qz.websocket.isActive());
|
||||
|
||||
if (!window.qz.websocket.isActive()) {
|
||||
console.log('Connecting to QZ Tray...');
|
||||
await window.qz.websocket.connect();
|
||||
console.log('Connected to QZ Tray successfully');
|
||||
} else {
|
||||
console.log('Already connected to QZ Tray');
|
||||
}
|
||||
|
||||
await loadPrinters();
|
||||
document.getElementById('print-status').innerHTML = '<span style="color: green;">✓ QZ Tray connected</span>';
|
||||
|
||||
setTimeout(() => {
|
||||
document.getElementById('print-status').innerHTML = '';
|
||||
}, 2000);
|
||||
} catch (e) {
|
||||
console.error('QZ Tray initialization failed:', e);
|
||||
document.getElementById('print-status').innerHTML = '<span style="color: red;">QZ Tray not connected</span>';
|
||||
console.error('=== QZ Tray initialization failed ===');
|
||||
console.error('Error:', e);
|
||||
console.error('Error message:', e.message);
|
||||
document.getElementById('print-status').innerHTML = '<span style="color: red;">QZ Tray not connected - ' + e.message + '</span>';
|
||||
}
|
||||
}
|
||||
|
||||
async function loadPrinters() {
|
||||
console.log('Loading printers...');
|
||||
try {
|
||||
const printers = await window.qz.printers.find();
|
||||
console.log('Printers found:', printers);
|
||||
|
||||
const printerSelect = document.getElementById('printer-select');
|
||||
printerSelect.innerHTML = '';
|
||||
|
||||
if (printers.length === 0) {
|
||||
console.warn('No printers found');
|
||||
printerSelect.innerHTML = '<option value="">No printers found</option>';
|
||||
return;
|
||||
}
|
||||
@@ -510,6 +530,7 @@ async function loadPrinters() {
|
||||
// Select first printer by default
|
||||
if (printers.length > 0) {
|
||||
printerSelect.value = printers[0];
|
||||
console.log('Default printer selected:', printers[0]);
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('Error loading printers:', e);
|
||||
@@ -563,6 +584,9 @@ function selectAndShowLabel(boxId, boxNumber, buttonElement) {
|
||||
}
|
||||
|
||||
document.getElementById('print-box-btn').addEventListener('click', async function() {
|
||||
console.log('=== PRINT BUTTON CLICKED ===');
|
||||
console.log('Selected box number:', selectedBoxNumber);
|
||||
|
||||
if (!selectedBoxNumber) {
|
||||
showNotification('Please select a box from the table', 'warning');
|
||||
return;
|
||||
@@ -571,33 +595,97 @@ document.getElementById('print-box-btn').addEventListener('click', async functio
|
||||
const printerSelect = document.getElementById('printer-select');
|
||||
const selectedPrinter = printerSelect.value;
|
||||
|
||||
console.log('Selected printer:', selectedPrinter);
|
||||
|
||||
if (!selectedPrinter) {
|
||||
showNotification('Please select a printer', 'warning');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
document.getElementById('print-status').innerHTML = '<span style="color: blue;">Printing...</span>';
|
||||
// Check QZ Tray connection status
|
||||
console.log('Checking QZ Tray connection...');
|
||||
if (!window.qz.websocket.isActive()) {
|
||||
console.log('QZ Tray not connected, attempting to reconnect...');
|
||||
document.getElementById('print-status').innerHTML = '<span style="color: blue;">Reconnecting to QZ Tray...</span>';
|
||||
await window.qz.websocket.connect();
|
||||
await loadPrinters();
|
||||
console.log('Reconnected to QZ Tray');
|
||||
} else {
|
||||
console.log('QZ Tray already connected');
|
||||
}
|
||||
|
||||
// Create ZPL code for box label
|
||||
const zpl = `^XA
|
||||
^FO50,50^A0N,40,40^FDBox: ${selectedBoxNumber}^FS
|
||||
^FO50,120^BY2,3,80^BCN,80,Y,N,N^FD${selectedBoxNumber}^FS
|
||||
^XZ`;
|
||||
document.getElementById('print-status').innerHTML = '<span style="color: blue;">Generating PDF...</span>';
|
||||
|
||||
const config = window.qz.configs.create(selectedPrinter);
|
||||
await window.qz.print(config, [zpl]);
|
||||
// Create FormData to send to backend
|
||||
const formData = new FormData();
|
||||
formData.append('box_number', selectedBoxNumber);
|
||||
|
||||
showNotification('Box label printed successfully!', 'success');
|
||||
document.getElementById('print-status').innerHTML = '<span style="color: green;">✓ Printed successfully</span>';
|
||||
// Send to backend to generate PDF
|
||||
const response = await fetch('/generate_box_label_pdf', {
|
||||
method: 'POST',
|
||||
body: formData
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const errorData = await response.json();
|
||||
throw new Error(errorData.error || 'Failed to generate PDF');
|
||||
}
|
||||
|
||||
// Get PDF as blob
|
||||
const pdfBlob = await response.blob();
|
||||
console.log('PDF generated successfully');
|
||||
|
||||
document.getElementById('print-status').innerHTML = '<span style="color: blue;">Sending to printer...</span>';
|
||||
|
||||
// Convert blob to base64 for QZ Tray
|
||||
const pdfBase64 = await new Promise((resolve, reject) => {
|
||||
const reader = new FileReader();
|
||||
reader.onloadend = () => {
|
||||
const base64 = reader.result.split(',')[1];
|
||||
resolve(base64);
|
||||
};
|
||||
reader.onerror = reject;
|
||||
reader.readAsDataURL(pdfBlob);
|
||||
});
|
||||
|
||||
console.log('PDF converted to base64');
|
||||
|
||||
// Configure QZ Tray for PDF printing
|
||||
const config = window.qz.configs.create(selectedPrinter, {
|
||||
scaleContent: false,
|
||||
rasterize: false,
|
||||
size: { width: 80, height: 50 },
|
||||
units: 'mm',
|
||||
margins: { top: 0, right: 0, bottom: 0, left: 0 }
|
||||
});
|
||||
|
||||
console.log('Print config created:', config);
|
||||
|
||||
// Prepare PDF data for QZ Tray
|
||||
const printData = [{
|
||||
type: 'pdf',
|
||||
format: 'base64',
|
||||
data: pdfBase64
|
||||
}];
|
||||
|
||||
console.log('Sending print command...');
|
||||
const result = await window.qz.print(config, printData);
|
||||
console.log('Print command result:', result);
|
||||
|
||||
showNotification('Box label sent to printer successfully!', 'success');
|
||||
document.getElementById('print-status').innerHTML = '<span style="color: green;">✓ Sent to printer successfully</span>';
|
||||
|
||||
setTimeout(() => {
|
||||
document.getElementById('print-status').innerHTML = '';
|
||||
}, 3000);
|
||||
} catch (e) {
|
||||
console.error('Print error:', e);
|
||||
console.error('=== PRINT ERROR ===');
|
||||
console.error('Error details:', e);
|
||||
console.error('Error message:', e.message);
|
||||
console.error('Error stack:', e.stack);
|
||||
showNotification('Print failed: ' + e.message, 'error');
|
||||
document.getElementById('print-status').innerHTML = '<span style="color: red;">Print failed</span>';
|
||||
document.getElementById('print-status').innerHTML = '<span style="color: red;">Print failed: ' + e.message + '</span>';
|
||||
}
|
||||
});
|
||||
</script>
|
||||
|
||||
Reference in New Issue
Block a user