### Vue 2.x Integration Example Source: https://github.com/ccsimple/vue-plugin-hiprint/blob/main/_autodocs/MANIFEST.txt Example of integrating the hiPrintPlugin into a Vue 2.x application. Ensure the plugin is installed and imported correctly. ```javascript import Vue from 'vue'; import hiPrintPlugin from 'vue-plugin-hiprint'; Vue.use(hiPrintPlugin); new Vue({ // ... }); ``` -------------------------------- ### Clone and Install vue-plugin-hiprint Source: https://github.com/ccsimple/vue-plugin-hiprint/blob/main/README.md Clone the repository, install dependencies, and run development or build commands. ```bash git clone https://gitee.com/CcSimple/vue-plugin-hiprint.git // init cd vue-plugin-hiprint && npm i // 调试预览demo npm run serve // 打包demo (打包后生成在 demo 目录) npm run build-demo // 打包插件(vue-plugin-hiprint 插件资源) npm run build ``` -------------------------------- ### Vue 3.x Integration Example Source: https://github.com/ccsimple/vue-plugin-hiprint/blob/main/_autodocs/MANIFEST.txt Example of integrating the hiPrintPlugin into a Vue 3.x application using the createApp method. This demonstrates the modern Vue 3 setup. ```javascript import { createApp } from 'vue'; import App from './App.vue'; import hiPrintPlugin from 'vue-plugin-hiprint'; const app = createApp(App); app.use(hiPrintPlugin); app.mount('#app'); ``` -------------------------------- ### Data Persistence Example Source: https://github.com/ccsimple/vue-plugin-hiprint/blob/main/_autodocs/MANIFEST.txt Conceptual example for data persistence within the hiprint system. This might involve saving print job configurations or user preferences. ```javascript // Example: Saving template data // localStorage.setItem('myTemplate', JSON.stringify(templateData)); ``` -------------------------------- ### Install vue-plugin-hiprint Source: https://github.com/ccsimple/vue-plugin-hiprint/blob/main/README.md Use npm to install the vue-plugin-hiprint package. This is the recommended way to include the library in your project if you do not need to modify hiprint's core code. ```bash npm install vue-plugin-hiprint ``` -------------------------------- ### Batch Operation Example Source: https://github.com/ccsimple/vue-plugin-hiprint/blob/main/_autodocs/MANIFEST.txt Demonstrates performing operations on multiple elements simultaneously, such as alignment or distribution. This enhances efficiency in template design. ```javascript template.alignElements('left', selectedElementIds); template.distributeElements('horizontal', selectedElementIds); ``` -------------------------------- ### IPP Printing Protocol Example Source: https://github.com/ccsimple/vue-plugin-hiprint/blob/main/_autodocs/MANIFEST.txt Conceptual example of how to interact with the IPP (Internet Printing Protocol) for printing. This typically involves sending print jobs to IPP-enabled printers. ```javascript // Example: Sending a print job via IPP (implementation details vary) // fetch('/ipp/print', { // method: 'POST', // body: printJobData // }); ``` -------------------------------- ### Event System Example Source: https://github.com/ccsimple/vue-plugin-hiprint/blob/main/_autodocs/MANIFEST.txt Illustrates how to subscribe to and handle events emitted by the hiprint system. This is crucial for managing print job lifecycle and user interactions. ```javascript hiprint.on('print-success', (data) => { console.log('Print successful:', data); }); hiprint.on('print-error', (error) => { console.error('Print failed:', error); }); ``` -------------------------------- ### Open Direct Print Client via URLScheme Source: https://github.com/ccsimple/vue-plugin-hiprint/blob/main/README.md Launch the direct printing client by opening the 'hiprint://' URL scheme in the browser. Ensure the client is installed with administrator privileges to register the URL scheme correctly. ```javascript // js window.open("hiprint://"); ``` -------------------------------- ### Undo/Redo Functionality Example Source: https://github.com/ccsimple/vue-plugin-hiprint/blob/main/_autodocs/MANIFEST.txt Demonstrates the usage of undo and redo operations, typically available in a design or editing context. This allows users to revert or reapply changes. ```javascript template.undo(); template.redo(); ``` -------------------------------- ### PDF Export Example Source: https://github.com/ccsimple/vue-plugin-hiprint/blob/main/_autodocs/MANIFEST.txt Demonstrates the functionality to export a print template or job as a PDF document. This is useful for archiving or sharing printouts. ```javascript template.toPDF({ data: printData, path: '/path/to/save/print.pdf' }); ``` -------------------------------- ### Set Global Configuration Source: https://github.com/ccsimple/vue-plugin-hiprint/blob/main/_autodocs/MANIFEST.txt Example of setting global configuration for hiprint using the setConfig method. This affects all subsequent operations. ```javascript import hiprint from 'hiprint'; hiprint.setConfig({ // global settings }); ``` -------------------------------- ### Get Client List via hiwebSocket.getClients() Source: https://github.com/ccsimple/vue-plugin-hiprint/blob/main/apiDoc.md Directly call the getClients method on hiwebSocket to retrieve the client list. This is a synchronous call. ```javascript hiwebSocket.getClients(); ``` -------------------------------- ### Example Client Data Structure Source: https://github.com/ccsimple/vue-plugin-hiprint/blob/main/apiDoc.md This JSON object represents the structure of the client data returned by the hiprint plugin, including printer lists and client details. ```json paperSize = { HB2OhMUEJuQx9YdxAAAV: { clientId: "HB2OhMUEJuQx9YdxAAAV", printerList: [ { name: "导出为WPS PDF", displayName: "导出为WPS PDF", description: "", status: 0, isDefault: false, options: { "printer-location": "", "printer-make-and-model": "Kingsoft Virtual Printer Driver", system_driverinfo: "Kingsoft Virtual Printer Driver;0,3,0,0;WPS Office;12,1,0,19768", }, }, {...}, {...} ], hostname: "PC-2024111111", version: "1.0.13", platform: "win32", arch: "x64", mac: "aa:bb:cc:dd:ee:ff", ip: "192.168.1.2", ipv6: "240e:390:96a4:bb70:1486:fcc8:3ed9:42be", clientUrl: "http://192.168.1.2:17521", machineId: "5a6f6a42-fb17-4b3f-bc2f-3fb104f4910a", nickName: "打印客户端1", }, "wHOB6kn6JkPLV-b5AAAm": { clientId: "wHOB6kn6JkPLV-b5AAAm", printerList: [ { name: "TSC TTP-244", displayName: "TSC TTP-244", description: "", status: 0, isDefault: true, options: { "printer-location": "", "printer-make-and-model": "TSC TTP-244", system_driverinfo: "TSC TTP-244;0.3.0.0;Seagull Printer Drivers;1.0.0", }, }, {...}, {...} ], hostname: "PC-2025111111", version: "1.0.13", platform: "win32", arch: "x64", mac: "aa:bb:cc:dd:ee:ff", ip: "192.168.1.3", ipv6: "fe80::99e:98ee:16f:18", clientUrl: "http://192.168.127.111:17521", machineId: "48017401-113e-4394-a348-2526f0c9031b", nickName: "打印客户端2", }, }; ``` -------------------------------- ### Font and Field Management Source: https://github.com/ccsimple/vue-plugin-hiprint/blob/main/_autodocs/MANIFEST.txt Conceptual example related to managing fonts and fields within print templates. This could involve loading custom fonts or defining data fields. ```javascript // Example: Registering a custom font // hiprint.registerFont('MyFont', '/path/to/myfont.ttf'); ``` -------------------------------- ### Get Client List via hiwebSocket Source: https://github.com/ccsimple/vue-plugin-hiprint/blob/main/apiDoc.md Retrieve the client collection from hiwebSocket if the connection is open. This is useful for real-time updates. ```javascript if (hiwebSocket.opened) { console.log("客户端集合:", hiwebSocket.clients); } ``` -------------------------------- ### Get Printer List Source: https://github.com/ccsimple/vue-plugin-hiprint/blob/main/apiDoc.md Retrieves the list of available printers. Similar to clients, this is pushed by the server on connection or can be fetched. ```APIDOC ## GET /api/printers ### Description Retrieves the list of available printers across all connected clients. ### Method GET ### Endpoint /api/printers ### Parameters None ### Request Example None ### Response #### Success Response (200) - **printerList** (Array) - A list of printer objects. Each printer object includes a `server` property indicating the client it belongs to. #### Response Example ```json [ { "name": "导出为WPS PDF", "displayName": "导出为WPS PDF", "description": "", "status": 0, "isDefault": false, "options": { "printer-location": "", "printer-make-and-model": "Kingsoft Virtual Printer Driver", "system_driverinfo": "Kingsoft Virtual Printer Driver;0,3,0,0;WPS Office;12,1,0,19768" }, "server": { "clientId": "2EhIpBydILmQRrVLAAAE", "hostname": "PC-2024111111", "version": "1.0.13", "platform": "win32", "arch": "x64", "mac": "fc:34:97:be:39:3f", "ip": "192.168.1.2", "ipv6": "240e:390:96a4:bb70:1486:fcc8:3ed9:42be", "clientUrl": "http://192.168.1.2:17521", "machineId": "5a6f6a42-fb17-4b3f-bc2f-3fb104f4910a", "nickName": "打印客户端1" } } ] ``` ``` -------------------------------- ### Print Data Structure Source: https://github.com/ccsimple/vue-plugin-hiprint/blob/main/_autodocs/MANIFEST.txt Example of the data structure expected for printing. This JSON object maps to the fields defined in the print template, such as table columns. ```json { "name": "John Doe", "age": 30, "city": "New York" } ``` -------------------------------- ### Get Printer List via hiwebSocket Source: https://github.com/ccsimple/vue-plugin-hiprint/blob/main/apiDoc.md Retrieve the printer list from hiwebSocket if the connection is open. This provides real-time printer information. ```javascript if (hiwebSocket.opened) { console.log("打印机列表:", hiwebSocket.printerList); } ``` -------------------------------- ### Auto Connect Function Usage Source: https://github.com/ccsimple/vue-plugin-hiprint/blob/main/_autodocs/MANIFEST.txt Example of using the autoConnect function to manage printer connections automatically. This simplifies the process of keeping printers connected. ```javascript import { autoConnect } from 'vue-plugin-hiprint'; autoConnect(); ``` -------------------------------- ### Define Table Element with Column Definitions Source: https://github.com/ccsimple/vue-plugin-hiprint/blob/main/_autodocs/MANIFEST.txt Example of defining a table element within a print template, including specific column definitions for data display. This allows for structured tabular data printing. ```javascript { type: 'table', options: { x: 50, y: 100, width: 300, height: 150, columns: [ { title: 'Name', field: 'name', width: 100 }, { title: 'Age', field: 'age', width: 50 }, { title: 'City', field: 'city', width: 150 } ] } } ``` -------------------------------- ### Get Paper Size Information for Printers Source: https://github.com/ccsimple/vue-plugin-hiprint/blob/main/apiDoc.md Request paper size details for a specific printer or all printers using `hiwebSocket.getPaperSizeInfo`. This feature is only supported on Windows. The `paperSizeInfo` event will provide the results. ```javascript // 获取指定打印机纸张信息 hiwebSocket.getPaperSizeInfo(printerName); // 获取所有打印机纸张信息 hiwebSocket.getPaperSizeInfo(); hinnn.event.on("paperSizeInfo", (paperSize) => { console.log(`${printerName} 纸张:`, paperSize); }); ``` -------------------------------- ### Get Client Collection Source: https://github.com/ccsimple/vue-plugin-hiprint/blob/main/apiDoc.md Retrieves the collection of connected clients. The server pushes this information upon successful connection, or it can be fetched via API. ```APIDOC ## GET /api/clients ### Description Retrieves the list of connected printing clients. ### Method GET ### Endpoint /api/clients ### Parameters None ### Request Example None ### Response #### Success Response (200) - **clients** (Array) - A list of client objects, each containing details like clientId, hostname, printerList, IP address, etc. #### Response Example ```json { "clients": [ { "clientId": "HB2OhMUEJuQx9YdxAAAV", "hostname": "PC-2024111111", "version": "1.0.13", "platform": "win32", "arch": "x64", "mac": "aa:bb:cc:dd:ee:ff", "ip": "192.168.1.2", "ipv6": "240e:390:96a4:bb70:1486:fcc8:3ed9:42be", "clientUrl": "http://192.168.1.2:17521", "machineId": "5a6f6a42-fb17-4b3f-bc2f-3fb104f4910a", "nickName": "打印客户端1", "printerList": [ { "name": "导出为WPS PDF", "displayName": "导出为WPS PDF", "description": "", "status": 0, "isDefault": false, "options": { "printer-location": "", "printer-make-and-model": "Kingsoft Virtual Printer Driver", "system_driverinfo": "Kingsoft Virtual Printer Driver;0,3,0,0;WPS Office;12,1,0,19768" } } ] } ] } ``` ``` -------------------------------- ### Get Client List via hiprint API Source: https://github.com/ccsimple/vue-plugin-hiprint/blob/main/apiDoc.md Fetch the latest client collection using the hiprint API. This method provides an asynchronous callback with the client data. ```javascript hiprint.getClients((clients) => { console.log("客户端集合:", clients); }); ``` -------------------------------- ### Initialize Hiprint with Host and Token Source: https://github.com/ccsimple/vue-plugin-hiprint/blob/main/apiDoc.md Use `hiprint.init` to connect to a local desktop client. Provide the client's address as `host` and the configured `token`. ```javascript hiprint.init({ ...otherOptions, host: "http://localhost:17521", // 桌面客户端地址 token: "vue-plugin-hiprint", // 客户端设置的令牌 }); ``` -------------------------------- ### Global Direct Print Method Usage Source: https://github.com/ccsimple/vue-plugin-hiprint/blob/main/_autodocs/MANIFEST.txt Shows how to use the global $print2 method for direct printing, bypassing potential intermediate steps. This is useful for immediate print actions. ```javascript this.$print2({ url: '/api/getPrintData', // ... other options }); ``` -------------------------------- ### Connect to Transit Server with Hiprint Source: https://github.com/ccsimple/vue-plugin-hiprint/blob/main/apiDoc.md Initialize Hiprint to connect to a transit server by specifying the server's address as `host` and the corresponding `token`. ```javascript hiprint.init({ ...otherOptions, host: "https://v5.printjs.cn:17521", // 桌面客户端地址 token: "hiprint-17521", // 中转服务器设置的令牌 }); ``` ```javascript hiwebSocket.setHost( "https://v5.printjs.cn:17521", "hiprint-17521", // callback (connect) => { if (connect) { console.log("连接成功"); // do something after connected } else { console.log("连接失败"); } } ); ``` -------------------------------- ### Configure Print Callbacks and Direct Printing Source: https://github.com/ccsimple/vue-plugin-hiprint/blob/main/README.md This JavaScript code illustrates how to use callbacks for browser print previews (`hiprintTemplate.print`) and direct printing (`hiprintTemplate.print2`). It shows how to specify printer names, titles, and listen for print success or error events. ```javascript // 浏览器预览打印, 无法监听是否点击了 打印/取消 按钮 hiprintTemplate.print( this.printData, {}, { callback: () => { console.log("浏览器打印窗口已打开"); }, } ); // 直接打印 // 打印机名称: 通过 hiprintTemplate.getPrinterList() 获取 其中的 name hiprintTemplate.print2(printData, { printer: "打印机名称", title: "打印标题" }); hiprintTemplate.on("printSuccess", function (data) { console.log("打印完成"); }); hiprintTemplate.on("printError", function (data) { console.log("打印失败"); }); ``` -------------------------------- ### Initialize hiprint Core Source: https://github.com/ccsimple/vue-plugin-hiprint/blob/main/_autodocs/MANIFEST.txt Basic initialization of the hiprint core library. This is a fundamental step before using any hiprint functionalities. ```javascript import hiprint from 'hiprint'; hiprint.init({ // configuration options }); ``` -------------------------------- ### Set Host and Token via HiWebSocket API Source: https://github.com/ccsimple/vue-plugin-hiprint/blob/main/apiDoc.md Use `hiwebSocket.setHost` to establish a connection with the Hiprint client. A callback function is provided to handle connection success or failure. ```javascript hiwebSocket.setHost( "http://localhost:17521", "vue-plugin-hiprint", // callback (connect) => { if (connect) { console.log("连接成功"); // do something after connected } else { console.log("连接失败"); } } ); ``` -------------------------------- ### Initialize Transit Service Connection Source: https://github.com/ccsimple/vue-plugin-hiprint/blob/main/README.md Configure vue-plugin-hiprint to connect to the node-hiprint-transit service by providing the host URL and an authentication token. This enables communication with multiple printing clients through the proxy. ```javascript import { hiprint } from "vue-plugin-hiprint"; hiprint.init({ host: "https://v4.printjs.cn:17521", // 此处输入服务启动后的地址 token: "hiprint-17521", // 用于鉴权的token,hiprint* (*可替换为[0-9a-zA-Z-_]字符) }); ``` ```javascript hiwebSocket.setHost("https://printjs.cn:17521", "vue-plugin-hiprint"); ``` -------------------------------- ### Global Print Method Usage Source: https://github.com/ccsimple/vue-plugin-hiprint/blob/main/_autodocs/MANIFEST.txt Demonstrates how to use the global $print method provided by the plugin to initiate a print job. This method is available on all Vue instances. ```javascript this.$print({ url: '/api/getPrintData', // ... other options }); ``` -------------------------------- ### Initialize Drag-and-Drop Design Source: https://github.com/ccsimple/vue-plugin-hiprint/blob/main/README.md Initializes the hiprint library for drag-and-drop design. Ensure that elements with class '.ep-draggable-item' have corresponding 'tid' attributes to enable drag-and-drop functionality. ```javascript import { hiprint, defaultElementTypeProvider } from "vue-plugin-hiprint"; // 初始化可拖拽的元素 hiprint.init({ providers: [new defaultElementTypeProvider()], }); // $('.ep-draggable-item') 包含 tid, 与上边的 provider 中的 tid 对应 才能正常拖拽生成元素 hiprint.PrintElementTypeManager.buildByHtml($(".ep-draggable-item")); hiprintTemplate = new hiprint.PrintTemplate({ template: {}, // 模板json settingContainer: "#PrintElementOptionSetting", // 元素参数容器 paginationContainer: ".hiprint-printPagination", // 多面板的容器, 实现多面板, 需要在添加一个
// ------- 下列是可选功能 ------- // ------- 下列是可选功能 ------- // ------- 下列是可选功能 ------- // 图片选择功能 onImageChooseClick: (target) => { // 测试 3秒后修改图片地址值 setTimeout(() => { // target.refresh(url,options,callback) // callback(el, width, height) // 原元素,宽,高 // target.refresh(url,false,(el,width,height)=>{ // el.options.width = width; // el.designTarget.css('width', width + "pt"); // el.designTarget.children('.resize-panel').trigger($.Event('click')); // }) target.refresh( "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAtAAAAIIAQMAAAB99EudAAAABlBMVEUmf8vG2O41LStnAAABD0lEQVR42u3XQQqCQBSAYcWFS4/QUTpaHa2jdISWLUJjjMpclJoPGvq+1WsYfiJCZ4oCAAAAAAAAAAAAAAAAAHin6pL9c6H/fOzHbRrP0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0u/SY9LS0tLS0tLS0tLS0n+edm+UlpaWlpaWlpaWlpaW/tl0Ndyzbno7/+tPTJdd1wal69dNa6abx+Lq6TSeYtK7BX/Diek0XULSZZrakPRtV0i6Hu/KIt30q4fM0pvBqvR9mvsQkZaW9gyJT+f5lsnzjR54xAk8mAUeJyMPwYFH98ALx5Jr0kRLLndT7b64UX9QR/0eAAAAAAAAAAAAAAAAAAD/4gpryzr/bja4QgAAAABJRU5ErkJggg==", { // auto: true, // 根据图片宽高自动等比(宽>高?width:height) // width: true, // 按宽调整高 // height: true, // 按高调整宽 real: true, // 根据图片实际尺寸调整(转pt) } ); }, 3000); // target.getValue() // target.refresh(url) }, // 自定义可选字体 // 或者使用 hiprintTemplate.setFontList([]) // 或元素中 options.fontList: [] fontList: [ { title: "微软雅黑", value: "Microsoft YaHei" }, { title: "黑体", value: "STHeitiSC-Light" }, { title: "思源黑体", value: "SourceHanSansCN-Normal" }, { title: "王羲之书法体", value: "王羲之书法体" }, { title: "宋体", value: "SimSun" }, { title: "华为楷体", value: "STKaiti" }, { title: "cursive", value: "cursive" }, ], dataMode: 1, // 1:getJson 其他:getJsonTid 默认1 history: true, // 是否需要 撤销重做功能 onDataChanged: (type, json) => { // 模板发生改变回调 console.log(type); // 新增、移动、删除、修改(参数调整)、大小、旋转 console.log(json); // 返回 template }, onUpdateError: (e) => { // 更新失败回调 console.log(e); }, }); // 设计器的容器 hiprintTemplate.design("#hiprint-printTemplate"); ``` -------------------------------- ### Set Direct Print Address, Port, and Token Source: https://github.com/ccsimple/vue-plugin-hiprint/blob/main/README.md This JavaScript snippet shows how to initialize the hiprint library with specific connection details, including the host address, port number, and an optional authentication token. This is crucial for establishing a connection to the printing service. ```javascript hiprint.init({ host: "http://localhost:17521", // 可在此处设置连接地址与端口号 token: "token", // 可在此处设置连接 token 可缺省 }); ``` -------------------------------- ### Direct Printing with Socket.io Source: https://github.com/ccsimple/vue-plugin-hiprint/blob/main/_autodocs/MANIFEST.txt Illustrates direct printing using Socket.io, a common method for real-time communication between the client and the print server. This requires a running Socket.io server. ```javascript // Assuming a Socket.io connection is established // socket.emit('print', { // template: templateData, // data: printData // }); ``` -------------------------------- ### Initialize Code-Based Design Source: https://github.com/ccsimple/vue-plugin-hiprint/blob/main/README.md Initializes the hiprint library for code-based design. This method is not recommended for complex layouts. Use this when drag-and-drop is not feasible. ```javascript import { hiprint, defaultElementTypeProvider } from "vue-plugin-hiprint"; // 引入后使用示例 hiprint.init(); // 下列方法都是没有拖拽设计页面的, 相当于代码模式, 使用代码设计页面 var hiprintTemplate = new hiprint.PrintTemplate(); var panel = hiprintTemplate.addPrintPanel({ width: 100, height: 130, paperFooter: 340, paperHeader: 10, }); //文本 panel.addPrintText({ options: { width: 140, height: 15, top: 20, left: 20, title: "hiprint插件手动添加text", textAlign: "center", }, }); //条形码 panel.addPrintText({ options: { width: 140, height: 35, top: 40, left: 20, title: "123456", textType: "barcode", }, }); //二维码 panel.addPrintText({ options: { width: 35, height: 35, top: 40, left: 165, title: "123456", textType: "qrcode", }, }); //长文本 panel.addPrintLongText({ options: { width: 180, height: 35, top: 90, left: 20, title: "长文本:hiprint是一个很好的webjs打印,浏览器在的地方他都可以运行", }, }); //打印 hiprintTemplate.print({}); ``` -------------------------------- ### Listen for Client List Updates via hinnn.event Source: https://github.com/ccsimple/vue-plugin-hiprint/blob/main/apiDoc.md Subscribe to client list updates using hinnn.event.on. This is useful for reacting to changes in the client collection. ```javascript hinnn.event.on("clients", (clients) => { console.log("客户端集合:", clients); }); ``` -------------------------------- ### Include Vue-Plugin-Hiprint and Dependencies in HTML Source: https://github.com/ccsimple/vue-plugin-hiprint/blob/main/README.md This HTML snippet shows how to include the necessary JavaScript libraries and CSS for Vue-Plugin-Hiprint in a Uniapp project running in a web browser. Ensure all scripts are correctly linked, especially the print-lock.css for styling. ```html ``` -------------------------------- ### Render API (JPEG, PDF, Print) Source: https://github.com/ccsimple/vue-plugin-hiprint/blob/main/apiDoc.md Utilizes the render API (available from electron-hiprint@^1.0.12-beta7) to generate JPEG, PDF, or initiate printing directly via the socket. ```APIDOC ## POST /socket/render ### Description Uses the render API via the WebSocket connection to generate JPEG or PDF, or to initiate printing. This feature is an extension and not built into the core hiprint library. ### Method POST ### Endpoint /socket/render ### Parameters #### Request Body - **type** (String) - Required - The type of render operation. Can be 'render-jpeg' or 'render-pdf'. - **payload** (Object) - Required - The data for the render operation. - **template** (Object) - Required if `html` is not provided - The template object. - **data** (Object) - Required if `html` is not provided - The print data. - **html** (String) - Required if `template` and `data` are not provided - An HTML string. - **options** (Object) - Optional - Additional options for rendering. ### Request Example ```json { "type": "render-jpeg", "payload": { "template": { ... }, // template object "data": { ... } // print data } } ``` ### Response #### Success Response (200) - **data** (Object) - Contains the buffer of the generated JPEG or PDF. - **buffer** (String) - The base64 encoded buffer data. #### Error Response - **msg** (String) - Error message. ### Events - **render-jpeg-success**: Emitted upon successful JPEG rendering. Receives the data object with the buffer. - **render-jpeg-error**: Emitted upon JPEG rendering error. Receives the data object with the error message. - **render-pdf-success**: Emitted upon successful PDF rendering. Receives the data object with the buffer. - **render-pdf-error**: Emitted upon PDF rendering error. Receives the data object with the error message. ``` -------------------------------- ### Handle Client Connection Errors (Element UI) Source: https://github.com/ccsimple/vue-plugin-hiprint/blob/main/README.md Display an error message using Element UI's $alert component when the direct printing client fails to connect. Provide links to download and run the client. ```javascript // element-ui this.$alert( `连接【${hiwebSocket.host}】失败!
请确保目标服务器已 下载 运行 打印服务!`, "客户端未连接", { dangerouslyUseHtmlString: true } ); ``` -------------------------------- ### Zoom and Paper Configuration Source: https://github.com/ccsimple/vue-plugin-hiprint/blob/main/_autodocs/MANIFEST.txt Shows how to configure zoom levels and paper settings for print templates. This affects the visual representation and output dimensions. ```javascript template.setZoom(1.5); // Zoom to 150% template.setPaperSize('A4'); ``` -------------------------------- ### Fetch Latest Client Information Source: https://github.com/ccsimple/vue-plugin-hiprint/blob/main/apiDoc.md Manually request the latest client information using `hiprint.getClientInfo` or `hiwebSocket.getClientInfo`. The `clientInfo` event can also be used to receive updates. ```javascript hiprint.getClientInfo((clientInfo) => { console.log("最新客户端信息:", clientInfo); }); // OR hiwebSocket.getClientInfo(); hinnn.event.on("clientInfo", (clientInfo) => { console.log("最新客户端信息:", clientInfo); }); ``` -------------------------------- ### Handle Client Connection Errors (Ant Design) Source: https://github.com/ccsimple/vue-plugin-hiprint/blob/main/README.md Display an error message using Ant Design's $error component when the direct printing client fails to connect. Provide links to download and run the client. ```javascript // ant-design this.$error({ title: "客户端未连接", content: (h) => (
连接【{hiwebSocket.host}】失败!
请确保目标服务器已 下载 运行 打印服务!
), }); ``` -------------------------------- ### Direct Print (electron-hiprint) Source: https://github.com/ccsimple/vue-plugin-hiprint/blob/main/apiDoc.md Handles direct printing using the electron-hiprint library, supporting single or multiple templates. ```APIDOC ## POST /hiprint/print ### Description Performs silent printing using the electron-hiprint library. Supports printing a single template or multiple templates in a batch. ### Method POST ### Endpoint /hiprint/print ### Parameters #### Request Body - **templates** (Array) - Required - An array of template objects to be printed. - **template** (Object) - Required - The hiprint template object. - **data** (Object | Array) - Required - The data to be printed with the template. - **options** (Object) - Optional - Printing options. - **printer** (String) - Required - The name of the printer. - **copies** (Number) - Optional - The number of copies to print. Defaults to 1. - **landscape** (Boolean) - Optional - Whether to print in landscape mode. Defaults to false. ### Request Example ```json { "templates": [ { "template": { ... }, // hiprint template object "data": { ... }, // print data "options": { "printer": "Microsoft Print to PDF", "copies": 2, "landscape": false } } ] } ``` ### Response #### Success Response (200) - **message** (String) - Confirmation message of the print job. #### Response Example ```json { "message": "Print job submitted successfully." } ``` ### Events - **printSuccess**: Emitted when the print job is successful. Receives the response object. - **printError**: Emitted when the print job fails. Receives the error object. ``` -------------------------------- ### Render API for JPEG, PDF, and Print Source: https://github.com/ccsimple/vue-plugin-hiprint/blob/main/apiDoc.md Utilize the render API (requires electron-hiprint@^1.0.12-beta7) to generate JPEG or PDF, or initiate printing directly via hiwebSocket.socket. This API is not built into hiprint itself. ```javascript const socket = hiwebSocket.socket; socket.emit("render-jpeg", { template: panel, // 模板对象 data: printData, // Object打印数据 }); socket.emit("render-jpeg", { html: "html字符串", // html 字符串 }); socket.on("render-jpeg-success", (data) => { // data.buffer }); socket.on("render-jpeg-error", (data) => { // data.msg }); ``` -------------------------------- ### hiprint Core API Source: https://github.com/ccsimple/vue-plugin-hiprint/blob/main/_autodocs/MANIFEST.txt Reference for the core hiprint object API, including initialization, template management, configuration, and event system. ```APIDOC ## hiprint Core API Reference This section details the core API methods and classes available in the hiprint library. ### Methods - **init()**: Initializes the hiprint system. Refer to `configuration.md` for configuration options. - **setConfig(config)**: Sets global configuration for hiprint. ### Classes - **PrintTemplate**: Represents a print template and provides methods for managing and printing templates. It includes over 20 methods for template manipulation. - **PrintElementTypeManager**: Manages the types of printable elements. - **PrintElementTypeGroup**: Manages groups of printable element types. ### Events - **Core Event System**: Details on the core event system for handling printing-related events. ### Advanced API - **Advanced API**: Access to advanced functionalities not covered in basic methods. ``` -------------------------------- ### Create a PrintTemplate Instance Source: https://github.com/ccsimple/vue-plugin-hiprint/blob/main/_autodocs/MANIFEST.txt Instantiating a PrintTemplate object, which is used to define and manage print layouts. This is a core object for creating print jobs. ```javascript import hiprint from 'hiprint'; const template = new hiprint.PrintTemplate({ // template definition }); ``` -------------------------------- ### Render JPEG from Template Source: https://github.com/ccsimple/vue-plugin-hiprint/blob/main/apiDoc.md Use the render API via hiwebSocket.socket to generate a JPEG image from a hiprint template and data. This requires electron-hiprint@^1.0.12-beta7 or later. The client ID is mandatory. ```javascript const socket = hiwebSocket.socket; socket.emit("render-jpeg", { clientId: "HB2OhMUEJuQx9YdxAAAV", // 客户端 ID template: panel, // 模板对象 data: printData, // Object打印数据 }); ``` -------------------------------- ### Global Integration for Vue/Vue3 Source: https://github.com/ccsimple/vue-plugin-hiprint/blob/main/README.md Integrates the hiprint plugin globally into Vue/Vue3 applications for easy access. Use '$pluginName' to access hiprint methods and global print functions. ```javascript // main.js中 引入安装 import { hiPrintPlugin } from "vue-plugin-hiprint"; Vue.use(hiPrintPlugin, "$pluginName"); // $pluginName 为自定义名称 hiPrintPlugin.disAutoConnect(); /// 提供的全局方法: // this.$pluginName == hiprint 全局对象 let hiprintTemplate = this.$pluginName.PrintTemplate({ template: {}, // 模板json [对象] }); hiprintTemplate.print({name:'i不简'}); /// provider 不能为null, 可以为 undefined args: 同模板对应调用 print 方法 // 1. 打印 this.$print(undefined, templateJson, ...args); this.$print(provider, templateJson, ...args); // 2. 直接打印 this.print2(undefined, templateJson, ...args); this.print2(provider, templateJson, ...args); ``` -------------------------------- ### QRCode Element Configuration Source: https://github.com/ccsimple/vue-plugin-hiprint/blob/main/_autodocs/MANIFEST.txt Configuration options for the 'qrcode' element type, including size, error correction level, and the data to be encoded. Essential for QR code generation. ```javascript { type: 'qrcode', options: { x: 10, y: 10, width: 100, height: 100, text: 'https://example.com', correctLevel: 'H' // High error correction } } ``` -------------------------------- ### Element Selection and Operation Source: https://github.com/ccsimple/vue-plugin-hiprint/blob/main/_autodocs/MANIFEST.txt Illustrates how to select and manipulate elements within a print template, such as moving, resizing, or deleting them. This is common in template editors. ```javascript const selectedElements = template.getElementsAt(x, y); template.moveElement(elementId, newX, newY); ``` -------------------------------- ### Print Elements Reference Source: https://github.com/ccsimple/vue-plugin-hiprint/blob/main/_autodocs/MANIFEST.txt Reference for all supported print element types, including their options and customization. ```APIDOC ## Print Elements Reference This section provides details on all available print element types and their configurations. ### Element Types - **text**: Supports text, barcodes, and QR codes. - **image**: For embedding images. - **longText**: For handling long text content. - **table**: Includes table and column definition capabilities. - **hline**: Horizontal line element. - **vline**: Vertical line element. - **rect**: Rectangular element. - **oval**: Oval element. - **barcode**: Specific element for barcodes. - **qrcode**: Specific element for QR codes. - **html**: Allows embedding custom HTML content. ### Common Options - **Public Options**: Describes common options applicable to most element types. ### Custom Elements - **Custom Elements**: Information on creating and using custom print elements. ``` -------------------------------- ### Print Template with Elements Source: https://github.com/ccsimple/vue-plugin-hiprint/blob/main/_autodocs/MANIFEST.txt Defining a print template that includes various elements like text, tables, and lines. This demonstrates how to structure a print layout. ```javascript const template = new hiprint.PrintTemplate([ { type: 'text', text: 'Hello World', options: { x: 50, y: 50, // ... other text options } }, { type: 'table', options: { x: 50, y: 100, // ... table options } }, { type: 'hline', options: { x: 50, y: 200, width: 200, // ... line options } } ]); ``` -------------------------------- ### Vue Integration API Source: https://github.com/ccsimple/vue-plugin-hiprint/blob/main/_autodocs/MANIFEST.txt API reference for integrating hiprint with Vue.js applications, including global methods and connection management. ```APIDOC ## Vue Integration API Reference This section covers the API for integrating hiprint with Vue.js applications. ### Vue Plugin - **hiPrintPlugin**: The Vue plugin object used for integration. ### Global Methods - **this.$print()**: A global method available in Vue components for initiating printing. - **this.$print2()**: Another global method for direct printing. ### Connection Management - **autoConnect()**: Manages automatic connection to printing services. - **disAutoConnect()**: Disables automatic connection. ### Integration Examples - **Vue 2.x and Vue 3.x Integration Examples**: Demonstrates how to integrate the plugin in different Vue versions. ``` -------------------------------- ### Configure Language for i18n Settings Source: https://github.com/ccsimple/vue-plugin-hiprint/blob/main/README.md This JavaScript code demonstrates how to set the language for the Vue-Plugin-Hiprint library during initialization. It allows you to choose from a list of supported languages, defaulting to 'cn' (Simplified Chinese). ```javascript hiprint.init({ lang: "en", // 设置语言 ['cn', 'en', 'de', 'es', 'fr', 'it', 'ja', 'ru', 'cn_tw'] }); ``` -------------------------------- ### Image Element Configuration Source: https://github.com/ccsimple/vue-plugin-hiprint/blob/main/_autodocs/MANIFEST.txt Configuration options for the 'image' element type, including source URL, size, and position. This allows embedding images into print layouts. ```javascript { type: 'image', options: { x: 10, y: 10, width: 100, height: 100, src: 'path/to/your/image.png' } } ``` -------------------------------- ### Handle Print Overlap and Styles with Custom CSS Source: https://github.com/ccsimple/vue-plugin-hiprint/blob/main/README.md This JavaScript code demonstrates how to apply custom print styles or include external print CSS using the `styleHandler` option in `hiprintTemplate.print` and `hiprintTemplate.print2`. This is useful for resolving print overlap or applying specific visual treatments. ```javascript /** * 从 在index.html添加: * * 或者 * * 以处理打印所需css, 当然你也可以自行处理 * 比如: index.html目录下放一个print-lock.css, 然后在index.html添加: * */ // 添加自定义样式 hiprintTemplate.print( this.printData, {}, { styleHandler: () => { // 这里拼接成放html->head标签内的css/style // 1.例如:使用hiprin官网的样式 let css = ''; // 2.重写样式:所有文本红色 css += ""; return css; }, } ); // 直接打印 hiprintTemplate.print2(this.printData, { styleHandler: () => { // 这里拼接成放html->head标签内的css/style // 1.例如:使用hiprin官网的样式 let css = ''; // 2.重写样式:所有文本红色 css += ""; return css; }, }); ```