diff --git a/src/api/labelSetting/label_setting.js b/src/api/labelSetting/label_setting.js
index 2348f83..921c06c 100644
--- a/src/api/labelSetting/label_setting.js
+++ b/src/api/labelSetting/label_setting.js
@@ -16,13 +16,13 @@ export const getZplElements = data => createAPI('/label/setting/getZplElements',
export const getUserLabelPrinters = data => createAPI('/label/setting/getUserLabelPrinters','post',data)
// 打印标签
-export const printLabel = data => createAPI('/label/setting/printLabel','post',data)
+export const printLabel = data => printWithSelectedEngine(data, false)
// 打印标签
export const printLabelTest = data => createAPI('/label/setting/printLabelTest','post',data)
// 通用打印标签
-export const printLabelCommon = data => createAPI('/label/setting/printLabelCommon', 'post', data)
+export const printLabelCommon = data => printWithSelectedEngine(data, true)
// 使用真实数据预览标签
export const previewLabelWithRealData = data => createAPI('/label/setting/previewLabelWithRealData','post',data)
@@ -47,3 +47,22 @@ export const getParentSerialElements = data => createAPI('/label/setting/getPare
// 复制标签(包括基本信息和绘制内容)
export const copyLabelSetting = data => createAPI('/label/setting/copyLabelSetting','post',data)
+
+// C-Lodop receives structured, server-resolved data; no generated JavaScript is evaluated.
+export const prepareLabelDocument = data => createAPI('/label/setting/prepareLabelDocument', 'post', data)
+
+async function printWithSelectedEngine(data, common) {
+ const request = Object.assign({}, data, {common})
+ const resolved = await createAPI('/label/setting/resolveClientPrintEngine', 'post', request)
+ if (!resolved.data || resolved.data.code !== 200) return resolved
+ if (resolved.data.data.printEngine !== 'CLODOP') {
+ return createAPI(common ? '/label/setting/printLabelCommon' : '/label/setting/printLabel', 'post', data)
+ }
+ const client = await import('@/utils/clodopClient')
+ const lodop = await client.loadClodop()
+ const printer = await client.chooseClodopPrinter(lodop)
+ const prepared = await createAPI('/label/setting/prepareClientPrint', 'post', request)
+ if (!prepared.data || prepared.data.code !== 200) return prepared
+ await client.runClodopDocuments(lodop, prepared.data.data, printer)
+ return {data: {code: 200, printEngine: 'CLODOP', msg: '打印任务已提交到本机驱动,请核对实物标签。'}}
+}
diff --git a/src/i18n/locales/labelSetting/cnLabelSetting.js b/src/i18n/locales/labelSetting/cnLabelSetting.js
index 8c0c56f..7024b7a 100644
--- a/src/i18n/locales/labelSetting/cnLabelSetting.js
+++ b/src/i18n/locales/labelSetting/cnLabelSetting.js
@@ -28,6 +28,7 @@ export default {
noData: '暂无数据'
},
fields: {
+ printEngine: '打印方式',
labelNo: '标签编号',
labelNoColon: '标签编号:',
labelId: '标签ID',
@@ -110,6 +111,7 @@ export default {
,copyRetry: '复制标签失败,请重试'
},
form: {
+ rfidZplOnly: 'RFID 标签仅支持 ZPL 打印,已自动切换为 ZPL。',
customTitle: '标签自定义维护',
defaultTitle: '默认标签定义维护',
customerTitle: '客户标签定义维护',
diff --git a/src/i18n/locales/labelSetting/enLabelSetting.js b/src/i18n/locales/labelSetting/enLabelSetting.js
index 1b7d3c8..5e79002 100644
--- a/src/i18n/locales/labelSetting/enLabelSetting.js
+++ b/src/i18n/locales/labelSetting/enLabelSetting.js
@@ -7,6 +7,7 @@ export default {
success: 'Operation succeeded', failed: 'Operation failed', networkError: 'Network error', noData: 'No data'
},
fields: {
+ printEngine: 'Print method',
labelNo: 'Label No.', labelNoColon: 'Label No.:', labelId: 'Label ID', labelIdColon: 'Label ID:',
labelName: 'Label name', labelNameColon: 'Label name:', labelType: 'Label type', labelTypeColon: 'Label type:',
labelClass: 'Label category', labelClassColon: 'Label category:', reportFileName: 'Report file name',
@@ -35,6 +36,7 @@ export default {
queryFailed: 'Query failed', deleteFailed: 'Delete failed', copyFailed: 'Copy failed', copyRetry: 'Failed to copy label. Please retry.'
},
form: {
+ rfidZplOnly: 'RFID labels only support ZPL printing. Switched to ZPL.',
customTitle: 'Custom label maintenance', defaultTitle: 'Default label maintenance', customerTitle: 'Customer label maintenance',
printerTitle: 'Label printer maintenance', parameterTitle: 'Label print parameter maintenance',
contentTitle: 'Label content maintenance', serialTitle: 'Serial information maintenance', copyContentTitle: 'Copy report content',
diff --git a/src/utils/clodopClient.js b/src/utils/clodopClient.js
new file mode 100644
index 0000000..48563c7
--- /dev/null
+++ b/src/utils/clodopClient.js
@@ -0,0 +1,116 @@
+import {buildClodopCommands} from './clodopRenderer'
+
+let loading
+let operation = Promise.resolve()
+
+export function waitForClodopReady (lodop, timeout = 5000) {
+ if (!lodop.SocketEnable) return Promise.resolve(lodop)
+ return new Promise((resolve, reject) => {
+ const started = Date.now()
+ const check = () => {
+ if (lodop.SocketOpened && (!lodop.webskt || lodop.webskt.readyState === 1)) return resolve(lodop)
+ if (Date.now() - started >= timeout) return reject(new Error('C-Lodop 通信通道未就绪,请检查本机服务和浏览器本地网络权限。'))
+ setTimeout(check, 50)
+ }
+ check()
+ })
+}
+
+export async function loadClodop () {
+ if (typeof window === 'undefined') throw new Error('C-Lodop 只能在安装了打印服务的客户端浏览器中运行。')
+ if (typeof window.getCLodop === 'function') {
+ const lodop = window.getCLodop()
+ if (lodop && lodop.CVERSION) return waitForClodopReady(lodop)
+ }
+ if (!loading) {
+ loading = (async () => {
+ const urls = window.location.protocol === 'https:'
+ ? ['https://localhost:8443/CLodopfuncs.js']
+ : ['http://localhost:8000/CLodopfuncs.js', 'http://localhost:18000/CLodopfuncs.js']
+ for (const url of urls) {
+ try {
+ await new Promise((resolve, reject) => {
+ const script = document.createElement('script')
+ const timer = setTimeout(() => { script.remove(); reject(new Error('连接超时')) }, 5000)
+ script.src = url
+ script.onload = () => { clearTimeout(timer); resolve() }
+ script.onerror = () => { clearTimeout(timer); script.remove(); reject(new Error('连接失败')) }
+ document.head.appendChild(script)
+ })
+ const lodop = window.getCLodop && window.getCLodop()
+ if (lodop && lodop.CVERSION) return waitForClodopReady(lodop)
+ } catch (error) { /* Try the official fallback local port. */ }
+ }
+ throw new Error('未连接 C-Lodop。请安装并启动本机 C-Lodop 服务,允许浏览器访问本地网络后重试。')
+ })().catch(error => { loading = null; throw error })
+ }
+ return loading
+}
+
+export function getClodopPrinters (lodop) {
+ const printers = []
+ const count = Number(lodop.GET_PRINTER_COUNT())
+ for (let i = 0; i < count; i++) printers.push({name: lodop.GET_PRINTER_NAME(i), index: i})
+ if (!printers.length) throw new Error('本机未安装打印机驱动。')
+ return printers
+}
+
+// C-Lodop returns a task ID immediately. Only On_Return carries the actual result.
+export function callClodopAsync (lodop, method, args = [], timeout = 120000) {
+ return new Promise((resolve, reject) => {
+ const previous = lodop.On_Return
+ let taskId
+ const cleanup = () => { clearTimeout(timer); if (lodop.On_Return === handler) lodop.On_Return = previous }
+ const handler = (id, result) => {
+ if (taskId != null && String(id) !== String(taskId)) { if (typeof previous === 'function') previous(id, result); return }
+ cleanup()
+ resolve(result)
+ }
+ const timer = setTimeout(() => { cleanup(); reject(new Error('C-Lodop 等待结果超时;任务状态未知,请先检查打印队列,不要直接重复提交。')) }, timeout)
+ lodop.On_Return = handler
+ try {
+ taskId = lodop[method](...args)
+ if (lodop.CVERSION && (taskId == null || taskId === false || taskId === '')) {
+ cleanup()
+ reject(new Error('C-Lodop 未创建任务,请检查服务连接或是否已有打印窗口未关闭。'))
+ return
+ }
+ if (!lodop.CVERSION) { cleanup(); resolve(taskId) }
+ } catch (error) { cleanup(); reject(error) }
+ })
+}
+
+export async function chooseClodopPrinter (lodop) {
+ // Ask before the backend reserves serial numbers; cancelling never prepares a print document.
+ const index = await callClodopAsync(lodop, 'SELECT_PRINTER')
+ if (index === '' || index == null || Number(index) < 0) throw new Error('已取消选择打印机。')
+ const printer = getClodopPrinters(lodop).find(item => item.index === Number(index))
+ if (!printer) throw new Error('所选打印机无效。')
+ return printer.name
+}
+
+export function runClodopDocuments (lodop, documents, printerName, action = 'print') {
+ // Validate the whole batch before any output; serialize operations because On_Return is global.
+ const batches = documents.map(buildClodopCommands)
+ const execute = async () => {
+ if (action === 'print' && !getClodopPrinters(lodop).some(printer => printer.name === printerName)) throw new Error('打印机不存在,请重新选择。')
+ const results = []
+ for (const commands of batches) {
+ commands.forEach(command => {
+ lodop[command.method](...command.args)
+ // Selecting a driver may reset its paper defaults. Select BEFORE applying page dimensions.
+ if (command.method === 'PRINT_INIT' && printerName) lodop.SET_PRINTER_INDEXA(printerName)
+ })
+ if (action === 'preview') lodop.SET_SHOW_MODE('HIDE_PBUTTIN_PREVIEW', true)
+ const value = await callClodopAsync(lodop, action === 'preview' ? 'PREVIEW' : 'PRINT')
+ if (action === 'print' && value !== true && value !== 1 && value !== 'true' && value !== '1') {
+ throw new Error(`C-Lodop 未接受打印任务(已提交 ${results.length} 个任务,返回 ${String(value)})。请检查队列,勿重复提交已成功的任务。`)
+ }
+ results.push({submitted: action === 'print', result: value})
+ }
+ return results
+ }
+ const pending = operation.then(execute, execute)
+ operation = pending.catch(() => {})
+ return pending
+}
diff --git a/src/utils/clodopRenderer.js b/src/utils/clodopRenderer.js
new file mode 100644
index 0000000..61ba835
--- /dev/null
+++ b/src/utils/clodopRenderer.js
@@ -0,0 +1,137 @@
+// Pure renderer: values must already be resolved by the backend. No eval, database calls or serial allocation.
+const BARCODE_TYPES = {CODE128: '128Auto', CODE39: 'Code39', CODE93: 'Code93', EAN13: 'EAN13', EAN8: 'EAN8', UPCA: 'UPC_A', UPCE: 'UPC_E0'}
+const enabled = value => value === true || value === 'true' || value === 'Y' || value === 1
+const number = (value, fallback) => value == null || value === '' ? fallback : Number(value)
+const mm = value => `${Math.round(value * 10000) / 10000}mm`
+
+export function gfaImageDataUrl (value) {
+ if (/^data:image\/(png|jpeg|gif|bmp);base64,[a-z0-9+/=\s]+$/i.test(value)) return value
+ const data = String(value || '').replace(/^.*?\^GFA,/, '').replace(/\^FS.*$/, '')
+ const match = /^(\d+),(\d+),(\d+),([0-9a-f\s]+)$/i.exec(data)
+ if (!match) throw new Error('图片不是可识别的未压缩 GFA 或 base64 图片,请重新上传图片。')
+ const total = Number(match[2])
+ const rowBytes = Number(match[3])
+ const hex = match[4].replace(/\s/g, '')
+ if (!rowBytes || total % rowBytes || total > 4000000 || hex.length !== total * 2) throw new Error('图片数据长度无效。')
+ const height = total / rowBytes
+ const stride = Math.ceil(rowBytes / 4) * 4
+ const bytes = new Uint8Array(62 + stride * height)
+ const view = new DataView(bytes.buffer)
+ bytes[0] = 66; bytes[1] = 77
+ view.setUint32(2, bytes.length, true); view.setUint32(10, 62, true)
+ view.setUint32(14, 40, true); view.setInt32(18, rowBytes * 8, true); view.setInt32(22, height, true)
+ view.setUint16(26, 1, true); view.setUint16(28, 1, true)
+ view.setUint32(34, stride * height, true); view.setUint32(46, 2, true)
+ bytes[54] = 255; bytes[55] = 255; bytes[56] = 255 // ZPL 0=white, 1=black
+ for (let y = 0; y < height; y++) {
+ for (let x = 0; x < rowBytes; x++) bytes[62 + (height - y - 1) * stride + x] = parseInt(hex.substr((y * rowBytes + x) * 2, 2), 16)
+ }
+ let binary = ''
+ for (let i = 0; i < bytes.length; i += 8192) binary += String.fromCharCode.apply(null, bytes.subarray(i, i + 8192))
+ return 'data:image/bmp;base64,' + btoa(binary)
+}
+
+export function buildClodopCommands (document) {
+ if (!document || !document.settings || !Array.isArray(document.pages) || !document.pages.length) throw new Error('没有可打印的标签数据。')
+ const settings = document.settings
+ if (String(settings.rfidFlag).toUpperCase() === 'Y') throw new Error('RFID 标签必须使用 ZPL。')
+ const dpi = number(settings.dpi, 203)
+ const width = number(settings.physicalWidthMm, number(settings.canvasWidth, 0) * 25.4 / dpi)
+ const height = number(settings.physicalHeightMm, number(settings.canvasHeight, 0) * 25.4 / dpi)
+ if (![dpi, width, height].every(n => Number.isFinite(n) && n > 0)) throw new Error('标签 DPI 或纸张尺寸无效。')
+ const copies = number(document.copies, 1)
+ if (!Number.isInteger(copies) || copies < 1 || copies > 1000) throw new Error('打印份数必须在 1 到 1000 之间。')
+ const xScale = width / number(settings.canvasWidth, width * dpi / 25.4)
+ const yScale = height / number(settings.canvasHeight, height * dpi / 25.4)
+ const commands = []
+ const add = (method, ...args) => commands.push({method, args})
+ const style = (name, value) => add('SET_PRINT_STYLEA', 0, name, value)
+ add('PRINT_INIT', `WMS-${settings.labelNo || '标签'}`)
+ // Physical dimensions already reflect designer orientation. Do not rotate them a second time.
+ add('SET_PRINT_PAGESIZE', 1, Math.round(width * 10), Math.round(height * 10), '')
+ // Start at the driver's printable-area origin, not the physical paper corner.
+ // Paper-relative (true) places x/y=0 inside hard margins on ordinary printers,
+ // clipping the first characters and the top row. Keep element sizes/spacing unchanged.
+ add('SET_PRINT_MODE', 'POS_BASEON_PAPER', false)
+ add('SET_PRINT_COPIES', copies)
+ document.pages.forEach((elements, pageIndex) => {
+ if (pageIndex) add('NEWPAGEA')
+ elements.forEach(element => {
+ const value = element.data == null ? '' : String(element.data)
+ const x = number(element.x, 0) * xScale
+ const y = number(element.y, 0) * yScale
+ if (!Number.isFinite(x) || !Number.isFinite(y)) throw new Error('元素坐标无效。')
+ if (element.type === 'serialNumber' && (element.showSerialNumber === false || element.showSerialNumber === 'false')) return
+ if (!value && !['hLine', 'vLine'].includes(element.type)) return
+ const fontDots = number(element.fontSize, 30)
+ const addText = (text, top = y, left = x, textWidth = width - x, textHeight = fontDots * 25.4 / dpi * 1.4) => {
+ add('ADD_PRINT_TEXT', mm(top), mm(left), mm(Math.max(1, textWidth)), mm(Math.max(1, textHeight)), text)
+ style('FontSize', Math.max(1, fontDots * 72 / dpi))
+ style('FontName', !element.fontFamily || /^default$/i.test(element.fontFamily) ? '宋体' : element.fontFamily)
+ style('Bold', enabled(element.bold) || element.fontWeight === 'bold' ? 1 : 0)
+ style('Italic', enabled(element.fontItalic) || element.fontStyle === 'italic' ? 1 : 0)
+ style('Underline', enabled(element.fontUnderline) ? 1 : 0)
+ style('Alignment', {left: 1, center: 2, right: 3}[element.textAlign] || 1)
+ }
+ switch (element.type) {
+ case 'text':
+ case 'serialNumber': {
+ const textWidth = enabled(element.newline) ? number(element.lineWidth, width - x) : width - x
+ const rows = enabled(element.newline) ? number(element.lineRows, 2) : 1
+ addText(value, y, x, textWidth, rows * fontDots * 25.4 / dpi * 1.4)
+ if (enabled(element.isChecked)) addText('☑', y, Math.max(0, x - 60 * 25.4 / dpi), 50 * 25.4 / dpi)
+ break
+ }
+ case 'onecode': {
+ const barcodeType = BARCODE_TYPES[element.barcodeType || 'CODE128']
+ if (!barcodeType) throw new Error('不支持的条码类型: ' + element.barcodeType)
+ // width is the narrow bar width in mm, NOT the total barcode width.
+ const modules = /^\d+$/.test(value) && value.length % 2 === 0 ? (value.length / 2 + 3) * 11 + 22 : (value.length + 3) * 11 + 22
+ const barWidth = number(element.barcodeWidthMm, modules * number(element.width, 0.33))
+ if (element.barcodeImageData) {
+ const image = gfaImageDataUrl(element.barcodeImageData)
+ add('ADD_PRINT_IMAGE', mm(y), mm(x), mm(barWidth), mm(number(element.height, 15)), ``)
+ style('Stretch', 2)
+ if (element.showContent !== false) addText(value, y + number(element.height, 15), x, barWidth)
+ } else {
+ // Draft-script fallback; prepared documents carry a validated, DPI-aligned barcode bitmap.
+ add('ADD_PRINT_BARCODE', mm(y), mm(x), mm(barWidth), mm(number(element.height, 15)), barcodeType, value)
+ style('ShowBarText', element.showContent === false ? 0 : 1)
+ }
+ break
+ }
+ case 'qrcode': {
+ const size = number(element.height, 10)
+ add('ADD_PRINT_BARCODE', mm(y), mm(x), mm(size), mm(size), 'QRCode', value)
+ style('ShowBarText', 0)
+ if (enabled(element.showContent)) addText(value, y + size + 1, x, Math.max(size, width - x))
+ break
+ }
+ case 'pic': {
+ const image = gfaImageDataUrl(value)
+ add('ADD_PRINT_IMAGE', mm(y), mm(x), mm(number(element.width, 100) * xScale), mm(number(element.height, 30) * yScale), `
`)
+ style('Stretch', 2)
+ break
+ }
+ case 'hLine':
+ case 'vLine': {
+ const horizontal = element.type === 'hLine'
+ const length = number(horizontal ? element.width : element.height, 100) * 25.4 / dpi
+ const thickness = number(horizontal ? element.height : element.width, 3) * 96 / dpi
+ add('ADD_PRINT_LINE', mm(y), mm(x), mm(horizontal ? y : y + length), mm(horizontal ? x + length : x), 0, Math.max(1, Math.round(thickness)))
+ break
+ }
+ default:
+ throw new Error('不支持的标签元素: ' + element.type)
+ }
+ })
+ })
+ return commands
+}
+
+export function generateClodopScript (document) {
+ // Export for inspection only. Runtime executes validated commands directly, never this string.
+ return ["const LODOP = typeof getCLodop === 'function' ? getCLodop() : getLodop();"].concat(buildClodopCommands(document).map(command =>
+ `LODOP.${command.method}(${command.args.map(value => JSON.stringify(value)).join(', ')});`
+ ), 'LODOP.SET_SHOW_MODE("HIDE_PBUTTIN_PREVIEW", true);', 'LODOP.PREVIEW();').join('\n')
+}
diff --git a/src/views/modules/labelSetting/LabelDesigner.vue b/src/views/modules/labelSetting/LabelDesigner.vue
index 8f72a03..1ba45ab 100644
--- a/src/views/modules/labelSetting/LabelDesigner.vue
+++ b/src/views/modules/labelSetting/LabelDesigner.vue
@@ -120,6 +120,9 @@