vue-plugin-hiprint

repository·main·Indexed 23 days ago

https://github.com/ccsimple/vue-plugin-hiprint

A JavaScript utility library based on hiprint 2.5.4 for Vue 2.x and 3.x projects. It enables visual print template design with support for drag-and-drop, pagination, headers/footers, and JSON template export. The plugin supports browser preview printing via print() and silent printing via print2() using the electron-hiprint client or node-hiprint-transit proxy server. It includes features for managing Socket.io connections, retrieving printer lists, and handling paper size information on Windows.

Tokens
8.9K
Snippets
19
Records
35
Agent score
83%

What's inside vue-plugin-hiprint

  1. Use node-hiprint-transit for proxy printing

    main

    To solve cross-origin issues or access printers across different network segments, you can use the node-hiprint-transit proxy service.

    When using a transit service, you must:

    1. Update hiprint.init to point to the transit service host and provide the required token.
    2. In print2, ippRequest, or ippRequest options, you must specify the client ID to tell the proxy which client should handle the print job.

    Workflow:

    • Retrieve clients and printerList from hiwebSocket.
    • Pass the client ID (from hiwebSocket.clients[clientId]) into the print2 options.
    // 1. Initialize with transit service
    import { hiprint } from "vue-plugin-hiprint";
    hiprint.init({
      host: "https://v4.printjs.cn:17521",
      token: "hiprint-17521",
    });
    
    // 2. Specify client in print2
    var clientId = "AlBaUCNs3AIMFPLZAAAh";
    var client = hiwebSocket.clients[clientId];
    var printer = hiwebSocket.printerList[0];
    
    hiprintTemplate.print2(printData, {
      client: clientId,
      printer: client.printerList[0].name,
      title: "hiprint测试打印",
    });
  2. Important usage notes and warnings

    main

    Before using vue-plugin-hiprint, be aware of the following critical constraints:

    • Not a Vue Component Library: This is a JavaScript utility library. It does not include built-in Vue components (the demo components are separate and must be copied manually).
    • Difference from hiprint.io: vue-plugin-hiprint is significantly different from the official hiprint.io website. Do not confuse the two or mix their usage.
    • Node.js Version: Requires Node.js 16.x (specifically 16.18.1 was used for development).
    • Printing Client: You should use the associated printing client or modify its source code to ensure compatibility with this project's templates.
    • Cross-Origin Issues: When deploying to production, you may encounter cross-origin issues when connecting to the printing client. Ensure you are using HTTPS to resolve this.
  3. Connect to a hiprint client or transit server

    main

    You can connect to a local desktop client (like electron-hiprint) or a transit server using either hiprint.init or the hiwebSocket API.

    Using hiprint.init

    Pass the host and token in the initialization options.

    Using hiwebSocket.setHost

    This method allows you to set the connection parameters and provides a callback to handle connection success or failure.

    Connecting to a Transit Server

    When using a transit server (e.g., https://v5.printjs.cn:17521), ensure you use the correct token assigned by the server. If using the public transit server, it is recommended to use a unique token (e.g., hiprint-test-1).

  4. Handle printing overlap and style issues

    main

    To prevent printing overlap or styling issues, you must include the print-lock.css file in your index.html with media="print".

    You can also inject custom CSS dynamically using the styleHandler option in print or print2 methods. This is useful for overriding default styles (e.g., making all text red) or linking to external stylesheets.

    // Adding custom styles via styleHandler
    hiprintTemplate.print(
      this.printData,
      {},
      {
        styleHandler: () => {
          // 1. Link external CSS
          let css = '<link href="http://hiprint.io/Content/hiprint/css/print-lock.css" media="print" rel="stylesheet">';
          // 2. Override styles
          css += "<style>.hiprint-printElement-text{color:red !important;}</style>";
          return css;
        },
      }
    );
  5. Manage Socket.io auto-connection

    main

    By default, the plugin attempts to connect via Socket.io. You can control this behavior to prevent errors or manage connections manually.

    Disable Auto-Connect:

    • In Vue: Vue.use(hiPrintPlugin, "$hiprint", false); or call hiPrintPlugin.disAutoConnect();.
    • In Components: Import disAutoConnect from vue-plugin-hiprint and call it.

    Manual Connection with Callback: Use autoConnect to listen for connection status before attempting to print.

    Troubleshooting Socket Errors: If you encounter connection errors due to socket.io version mismatches (e.g., npm package vs. server version), it is recommended to use the client provided on the project's Gitee repository, which supports more parameters like color, copies, and DPI.

    // Disable auto-connect in Vue
    import { hiPrintPlugin } from "vue-plugin-hiprint";
    Vue.use(hiPrintPlugin, "$hiprint", false);
    hiPrintPlugin.disAutoConnect();
    
    // Or in a component
    import { disAutoConnect, autoConnect, hiprint } from "vue-plugin-hiprint";
    disAutoConnect();
    
    // Connection callback and printing
    autoConnect((status, msg) => {
      if (status) {
        hiprintTemplate.print2(printData, {
          printer: "",
          title: "hiprint测试打印",
        });
      }
    });
  6. Use in jQuery or uniapp projects

    main

    To use vue-plugin-hiprint in non-Vue environments like jQuery or uniapp, you must ensure the environment supports the window global object. You need to include several dependencies via <script> tags in your index.html.

    Required Dependencies:

    • jquery (Mandatory)
    • jsbarcode (For barcodes)
    • bwip-js (For QR codes and barcodes)
    • nzh (For converting numbers to Chinese characters)
    • @claviska/jquery-minicolors (For color selection)
    • socket.io-client (Required for print2 direct printing)
    • canvg, jspdf, and html2canvas (Required for PDF generation)
    • vue-plugin-hiprint

    Note on Global Access: When loaded via script tags, hiprint is injected into the global scope. You can access plugin utilities via window["vue-plugin-hiprint"].

    <!-- index.html -->
    <head>
      <!-- Print styles are mandatory -->
      <link
        rel="stylesheet"
        type="text/css"
        media="print"
        href="https://unpkg.com/vue-plugin-hiprint@latest/dist/print-lock.css"
      />
      <!-- Dependencies -->
      <script src="https://unpkg.com/jquery@3.6.1/dist/jquery.js"></script>
      <script src="https://unpkg.com/jsbarcode@3.11.5/dist/JsBarcode.all.min.js"></script>
      <script src="https://unpkg.com/bwip-js@4.5.1/dist/bwip-js.js"></script>
      <script src="https://unpkg.com/nzh@1.0.14/dist/nzh.min.js"></script>
      <script src="https://unpkg.com/@claviska/jquery-minicolors@2.3.6/jquery.minicolors.min.js"></script>
      <script src="https://unpkg.com/socket.io-client@4.5.1/dist/socket.io.min.js"></script>
      <script src="https://unpkg.com/canvg@3.0.10/lib/umd.js"></script>
      <script src="https://unpkg.com/jspdf@2.5.1/dist/jspdf.umd.min.js"></script>
      <script src="https://unpkg.com/html2canvas@1.4.1/dist/html2canvas.js"></script>
      <script src="https://unpkg.com/vue-plugin-hiprint@latest/dist/vue-plugin-hiprint.js"></script>
    </head>
    <body defer>
      <script>
        // hiprint is injected globally
        console.log(hiprint);
        var autoConnect = window["vue-plugin-hiprint"].autoConnect;
      </script>
    </body>
  7. Perform silent printing via transit server (中转打印)

    main

    When using a transit server (middleman) instead of a direct connection, you must provide a client ID (obtained from the clients list) in your print options. This ensures the print job is routed to the correct client.

    Single Template via Transit

    Pass the client ID within the options object of hiprintTemplate.print2().

    Multiple Templates via Transit

    Pass the client ID within the top-level options object of the hiprint.print2() call.

    const hiprintTemplate = new hiprint.PrintTemplate({
      template: {}, // 模板json对象
    });
    // 单一模板静默打印
    hiprintTemplate.print2(
      printData, // Object | Array<Object> 打印数据,数组时为批量打印
      {
        client: "HB2OhMUEJuQx9YdxAAAV", // 客户端 ID
        printer: "打印机名称",
        title: "打印任务名称",
      }
    );
    hiprintTemplate.on("printSuccess", (res) => {
      console.log("打印成功", res);
    });
    hiprintTemplate.on("printError", (err) => {
      console.error("打印失败", err);
    });
    
    // OR
    
    // 多模板静默打印
    hiprint.print2(
      {
        templates: [
          {
            template: hiprintTemplate,
            data: printData, // Object | Array<Object> 打印数据,数组时为批量打印
            options: {
              printer: "Microsoft Print to PDF", // 打印机名称
              copies: 2, // 打印份数
              landscape: false, // 是否横向打印
            },
          },
          // 支持多模板,在此处继续添加如上格式即可
        ],
        options: {
          client: "HB2OhMUEJuQx9YdxAAAV", // 客户端 ID
        },
      },
      (res) => {
        console.log("打印成功", res);
      },
      (err) => {
        console.error("打印失败", err);
      }
    );
  8. Use Drag-and-Drop Design Mode (Recommended)

    main
    The recommended way to use hiprint is through the visual drag-and-drop designer. This involves initializing the hiprint object with providers, building draggable elements from HTML, and instantiating a PrintTemplate.
  9. Include required print styles

    main

    You must add the required print styles to your index.html file. You can use a CDN or host the file locally. The filename must be print-lock.css.

    <!-- Using CDN -->
    <link
      rel="stylesheet"
      type="text/css"
      media="print"
      href="https://cdn.jsdelivr.net/npm/vue-plugin-hiprint@latest/dist/print-lock.css"
    />
    
    <!-- OR using a local file -->
    <link rel="stylesheet" type="text/css" media="print" href="/print-lock.css" />
  10. Use the electron-hiprint client and URLScheme

    main

    For direct printing, use the electron-hiprint client (supports Win, Mac, Linux).

    URLScheme Support: Once the client is installed (run as Administrator), you can trigger it from a browser using the hiprint:// scheme. This is useful for showing error messages or prompting users to open the print service.

    Example usage: window.open("hiprint://");