关于javascript:hiprint自定义前端打印组件

7次阅读

共计 5201 个字符,预计需要花费 14 分钟才能阅读完成。

我的项目技术栈:umi3+react17+antd pro5

我的项目须要打印性能,须要能自定义打印模版,极短的工夫找到了一个叫 hiprint 的插件

官网地址:hiprint 插件

该插件基于 Jquery,所以在 react 我的项目中须要引入 jquery,好好受哇

先从官网下载对应的文件,失去 hiprint 文件包。

官网示例看源代码能够用鼠标右键 -> 查看源码

踩坑从引入插件开始,首先须要引入 jQuery 相干的配置,在全局配置了 jQuery 的设置,不失效,最初无奈全局引入

import $ from 'jquery';

源码中能够通过 html 自定义拖拽组件,我在实践中试了,有问题,折中应用了他本来的拖拽组件

最大的毛病:代码被编译过,无奈精确读取源码的设计(钻研了好几天)

1. 在 hiprint.bundle.js 文件中引入相应的文件包

// 打印设计面板的款式
import './css/hiprint.css';
// 打印机预览和间接打印的款式
import './css/print-lock.css';
// 二维码插件
import QRCode from 'qrcodejs2';
// 条形码插件
import JsBarcode from 'jsbarcode';
import jQuery from 'jquery';
// 兼容 IE
import './polyfill.min.js';

import hiwprint from './plugins/jquery.hiwprint.js';
import './plugins/jquery.minicolors.min.js';
// 间接打印性能须要用到的 socket.io 插件
import io from './plugins/socket.io.js';
// 这些是对应的文件包内的插件
import jsPDF from './plugins/jspdf/jspdf.min.js';
import './plugins/jspdf/canvas2image.js';
import canvg from './plugins/jspdf/canvg.min.js';
import html2canvas from './plugins/jspdf/html2canvas.min.js';
import $ from 'jquery';
// window 在调用 IO 判断的时候须要有值
window.io = io;
// 传递 jquery 到打印预览的 iframe 弹窗
hiwprint(jQuery);

...

// 批改此处代码为导出,以便在界面中应用
export const hiprint = (function (t) {...

在我的项目运行时会有对象不存在报错,间接把对应中央的 xxx.xxx 改为 xxx?.xxx 就行了

前面做完了认真钻研了一下这个被编译后的代码,打印性能实现并不难,就是应用的 window.print 和 document.execCommand(‘print’, false, null)这两个办法。感兴趣的能够去 MDN 搜搜

2.hiprint.config.js 文件中定义的是一个拖拽组件块的配置项,最初都被打包到 hiprint.bundle.js 中去了

3. 在 pages 下定义 /Print/PrintSetting/index.tsx

// 引入 hiprint
import {hiprint} from '@/plugins/hiprint/hiprint.bundle';
import $ from 'jquery';
// 避免 ts 报类型谬误
type Win = Window & {
  hinnn?: any;
  [key: string]: any;
};

...

// 点击画布中的元素,右侧元素设置栏关上
const elementAddEventListen = () => {
  const win: Win = window;
  win.hinnn.event.on(hiprintTemplate.getPrintElementSelectEventKey(), function (t: any) {setParamsDrawerTitle(t.printElement.printElementType.title);
    setVisible(true);
  });
};
// 根底的模版配置,默认是 A4 纸
const baseConf = {
  panels: [
    {
      index: 0,
      paperType: 'A4',
      height: 297,
      width: 210,
      paperHeader: 0,
      paperFooter: 0,
      printElements: [],
      paperNumberLeft: 565,
      paperNumberTop: 819,
      paperNumberDisabled: true,
    },
  ],
};
useEffect(() => {
  // eslint-disable-next-line func-names
  $(async function () {
    /**
     * 配置打印模版参数
     * @param template: 生成的 panel 面板配置 json 数据
     * @param settingContainer: 组件属性设置的 html 容器
     * @param paginationContainer: 以后面板的分页设置容器,能够不加
     */
    hiprintTemplate = await new hiprint.PrintTemplate({
      template: baseConf,
      settingContainer: '#PrintElementOptionSetting',
      paginationContainer: '.hiprint-printPagination',
    });
    // 设置左侧拖拽事件
    hiprint.PrintElementTypeManager.build('.hiprintEpContainer', 'defaultModule');
    // hiprint.PrintElementTypeManager.buildByHtml($('.ep-draggable-item'));
    // 打印设计面板
    hiprintTemplate.design('#hiprint-printTemplate');
    // 设置右侧参数设置模版
    elementAddEventListen();
    // 获取本地打印机信息,可能有 BUG
    setTimeout(() => {const printerList = hiprintTemplate.getPrinterList();
    }, 1500);
  });
}, []);

其余性能参考官网的材料就行

4. 创立 /Print/PrintSetting/printConf.ts

外面的参数都是左侧拖拽面板的货色,能够自定义,更多请参考官网示例

/* eslint-disable */
import {hiprint} from '@/plugins/hiprint/hiprint.bundle.js';
export const DefaultElementTypeProvider = (() => {return function (options: any) {let addElementTypes = function (context: any) {
      context.addPrintElementTypes('defaultModule', [
        // 每一个 PrintElementTypeGroup 是一个组件分类块
        new hiprint.PrintElementTypeGroup('惯例组件', [
          {
            tid: 'defaultModule.text',
            title: '文本',
            data: '',
            type: 'text',
          },
          {
            tid: 'defaultModule.image',
            title: '图片',
            data: '/images/shuixi.png',
            type: 'image',
          },
          {
            tid: 'defaultModule.longText',
            title: '长文',
            data: '155123456789',
            type: 'longText',
          },
          {
            tid: 'defaultModule.table',
            field: 'table',
            title: '自定义表格',
            type: 'table',
            groupFields: ['name'],
            groupFooterFormatter: function (group: any, option: any) {console.log(group);
              console.log(option);
              return '这里自定义统计脚信息';
            },
            columns: [
              [
                {
                  title: '行号',
                  fixed: true,
                  rowspan: 2,
                  field: 'id',
                  width: 70,
                },
                {title: '人员信息', colspan: 2},
                {title: '销售统计', colspan: 2},
              ],
              [
                {
                  title: '姓名',
                  align: 'left',
                  field: 'name',
                  width: 100,
                },
                {title: '性别', field: 'gender', width: 100},
                {
                  title: '销售数量',
                  field: 'count',
                  width: 100,
                },
                {
                  title: '销售金额',
                  field: 'amount',
                  width: 100,
                },
              ],
            ],
          },
          {
            tid: 'defaultModule.tableCustom',
            title: '表格',
            type: 'tableCustom',
          },
          {
            tid: 'defaultModule.customText',
            title: '自定义文本',
            customText: '自定义文本',
            custom: true,
            type: 'text',
          },
        ]),
        new hiprint.PrintElementTypeGroup('辅助', [
          {
            tid: 'defaultModule.hline',
            title: '横线',
            type: 'hline',
          },
          {
            tid: 'defaultModule.vline',
            title: '竖线',
            type: 'vline',
          },
          {
            tid: 'defaultModule.rect',
            title: '矩形',
            type: 'rect',
          },
          {
            tid: 'defaultModule.oval',
            title: '椭圆',
            type: 'oval',
          },
        ]),
      ]);
    };
    return {addElementTypes,};
  };
})();

5. 遇到的问题
1、浏览器最小字体大小不能低于 12px,能够应用放大放大款式管制,不过不能保障打印进去成果很好,须要调整打印机的一些配置。最好还是依照 12px 来,字体抉择黑体,字体在插件就设置了 2 个选项,能够本人取增加浏览器反对的字体款式。在hiprint.bundle.js 文件中 ctrl+ f 搜寻 宋体 把在百度搜到的浏览器反对的字体选项放进去即可

2、引入的全局 hiprint 组件反复加载,因为在生成我的项目的时候会在 window 下生成对应的 hinnn 对象,

1). 能够在卸载组件的时候去删除这个 hinnn 对象,delete window.hinnn

2). 也能够在不变动的组件下来初始化引入一次,例如头部组件 RightContent

// DefaultElementTypeProvider 是上述 printConf.js 文件中引入的
hiprint.init({providers: [DefaultElementTypeProvider({})],
});

3、遇到款式查看问题,千万记得把这个文件夹屏蔽了,.eslinignore 文件里增加对应你 print 相干文件路劲下的文件

4、多模版预览打印无奈产生回调函数,应用自定义模版渲染预览(除了此办法,此性能貌似无解)

5、多模版间接打印无奈抉择打印机(未知解决)

6、间接打印性能无奈应用,显示连贯失败,下载官网的安装包,装置好后运行就好了

7、打印机设置,后更

8、后端存配置项,肯定要用原数据类型,数字不能改成字符串。hiprintTemplate.getJson()获取配置项信息

9、疾速预览没有成果,加个提早函数

10、面板宽高计算是按 cm 计算的,字体大小是按 pt 计算的,都要换算一遍成 px,设置对应的宽度大小,和字体大小

11、打印的时候设计的款式跟咱们预设款式不一样,打印机配置也没调整,在 document.ejs 文件引入对应的 link

// 文件肯定要依照门路匹配放到 public 文件夹下
<link media="print" href="<%= context.config.publicPath +'css/hiprint.css'%>" />
<link media="print" href="<%= context.config.publicPath +'css/print-lock.css'%>" />

12、图片无奈显示在面板上,动态文件就放在上述问题对应的 image 门路下。动静文件(含 http 绝对路径)须要依照先引入再应用

正文完
 0