vue使用hiprint做打印模板并打印

需求:前端能够在很多功能打印,一个打印的单据可能需要多个模板。

hiprint可用将模板保存为字符串。

设计:建立一个模板表;有以下字段:id(唯一键),name(前端显示模板名称),printJson(模板字符串),type(分类-同类的模板在同一个地方显示并可打印),等(做成配置时需要其他条件自己考虑加)

前端统一传值可为两种对象和数组(对象只打印一个,数组有多少条数据打印多少个),这个hiprint会自己判断,可以不管。

下载地址:http://hiprint.io/Content/download/hiprint.zip

刚下载下的hiprint有这些文件

将hiprint文件夹放入public里面

建一个打印页面print.html

<!DOCTYPE html>
<html>

    <head>
        <meta charset="utf-8" />
        <title>自定义打印测试程序</title>
        <!-- hiprint -->
        <link href="hiprint/css/hiprint.css" rel="stylesheet">
        <link href="hiprint/css/print-lock.css" rel="stylesheet">
        <link href="hiprint/css/print-lock.css" media="print" rel="stylesheet">
        <link href="hiprint/bootstrap/bootstrap.min.css" rel="stylesheet">
        <style>
            .hiprint-printPaper{
                border: solid black 1px;
                margin: 10px auto;
            }
        </style>
        <!-- jQuery (hiprint 的所有 JavaScript 插件都依赖 jQuery,所以必须放在前边) -->
        <script src="hiprint/jquery.min.js"></script>
        <script src="hiprint/bootstrap/bootstrap.min.js"></script>
        <!-- 加载 hiprint 的所有 JavaScript 插件。你也可以根据需要只加载单个插件。 -->
        <!-- polyfill.min.js解决浏览器兼容性问题v6.26.0-->
        <script src="hiprint/polyfill.min.js"></script>
        <!-- hiprint 核心js-->
        <script src="hiprint/hiprint.bundle.js"></script>
        <!-- 条形码生成组件-->
        <script src="hiprint/plugins/JsBarcode.all.min.js"></script>
        <!-- 二维码生成组件-->
        <script src="hiprint/plugins/qrcode.js"></script>
        <!-- 调用浏览器打印窗口helper类,可自行替换-->
        <script src="hiprint/plugins/jquery.hiwprint.js"></script>
        <script src="./zhht/Server.js"></script>
        <script src="/src/main.js"></script>
        
    </head>

    <body>
        <div class="btn-group btn-group-justified" role="group" aria-label="...">
            <div class="btn-group" role="group" >
                <button type="button" class="btn btn-default" id="goTemplate" style="background-color: rgb(214, 214, 214);width: 200px;position: fixed;left: 0;top: 0;" onclick="goTemplate()">打印设计</button>
                <button type="button" class="btn btn-default" id="NowPrint" style="background-color: greenyellow;width: 200px;position: fixed;right: 0;top: 0;">立即打印</button>
            </div>
        </div>
        <div id="content">
            <div class="jumbotron">
                <h1 id="Title">正在加载数据请稍后</h1>
                <p id="Describe">正在从服务器中加载数据,请稍后..........</p>
            </div>
        </div>
    </body>
    <script>
        //全局默认对象
        var hiprintTemplate;
        var printData = {} // 打印数据
        var printJson // 打印模板
        const nowPrintTemplate = JSON.parse(sessionStorage.getItem('nowPrintTemplate'))
        if (nowPrintTemplate) {
            printData = nowPrintTemplate.printData
            printJson = nowPrintTemplate.printJson
            console.log('放在缓存里的数据:', nowPrintTemplate);
            GlobalLoading()
        }
        // var Debug = false;
        //全局提前定义好一个叫做LoadPrintDataOk的方法在脚本代码加载完成后调用
        window.LoadPrintDataOk = function(){

        }
        //打印
        function Print(){
            if(hiprintTemplate){
                hiprintTemplate.print(printData);
            }
        }
        //等待页面加载完成后初始化
        // $(document).ready(function(){
        //     TemplateName = ReadURLArgs('TemplateName');
        //     if(TemplateName){
        //         GlobalLoading();
        //     }else{
        //         document.getElementById('Title').innerText = "没有任何有效的模板名称";
        //         document.getElementById('Describe').innerText = "无法从服务器加载任何有效的打印数据?请检查URL地址是否正确";
        //     }

        // });
        //去服务器加载JS脚本
            //加载模板
        function GlobalLoading(){
            // 将当前打印模板打印数据放缓存里
            hiprintTemplate = new hiprint.PrintTemplate ({
                template: JSON.parse(printJson.printJson)
            });
            var printEle = document.getElementById('NowPrint');
            printEle.onclick = Print;
            //将html渲染到页面上
            $("#content").html(hiprintTemplate.getHtml(printData));
        }
        const channel = new BroadcastChannel('zhht_print_channel');
        channel.onmessage = function(event) {
            printData = event.data.printData
            printJson = event.data.printJson
            console.log('放在Channel里的数据:', event.data);
            sessionStorage.setItem('nowPrintTemplate', JSON.stringify({printJson, printData}))
            GlobalLoading()
        }
        // 前往设计页面
        function goTemplate(){
            window.location.assign('/hiprint/custom.html')
        }
    </script>
</html>

在hiprint下的custom.html也就是设计页面的数据改为传进去的数据

保存时保存到后端,写个js文件引用

var url
async function setUrl(){
    try {
        const furl = await fetch('/URLConfig.json')
        const json = furl.json()
        const res = await json.then()
        url = res.baseURL
    } catch (res) {
        console.log(res)
    }
}
setUrl()
//读取本地的Token值
function GetToken(){
    return sessionStorage.getItem('Access-Token')
}
//账户检查
function CheckUser(){
    const userToken = GetToken()
    if(userToken == null){
        alert('当前没有任何账户登录,请再登录后重新保存')
        throw 'User Not Found'
    }else{
        return userToken
    }
}
//根方法
function send(requestParam,succeed,lose){
    const userToken = CheckUser()
    const requestUrl = url + '/api/Print/editDetail'
    const TmpF = fetch(requestUrl, {
        'headers': {
          'accept': 'application/json, text/plain, */*',
          'accept-language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6',
          'authorization': 'Bearer '+userToken,
          'cache-control': 'no-cache',
          'content-type': 'application/json',
          'pragma': 'no-cache'
        },
        'body': JSON.stringify(requestParam),
        'method': 'POST',
        'mode': 'cors'
      })
    TmpF.then(resp=>{
        if(resp.status == 200){
            succeed(resp)
        }else{
            lose(resp)
        }
    }).catch(erro => {
        return lose(erro)
    })
}
function queryList(requestParam,succeed,lose){
    send(requestParam,resp=>{
        ServerData(resp,succeed)
    },
    lose)
}
//读取Data中的数据
function ServerData(resp,cb){
    resp.json().then(data=>{
        cb(data)
    })
}

然后再写个组件,弹窗显示打印页面,引用打印页面,传入数据(打印内容与打印模板)

<template>
  <div>
    <a-modal
      v-model="visible"
      centered
      title="打印预览"
      width="90%"
      :maskClosable="false"
      :footer="false"
      :confirm-loading="loading"
      @cancel="cancel">
      <iframe
        v-if="visible"
        src="/print.html"
        width="100%"
        :height="scrollY + 'px'"></iframe>
    </a-modal>
  </div>
</template>
  <script>
  export default {
    name: 'ModelPrint',
    data() {
      return {
        visible: false,
        loading: false,
        printData: null,
        printJson: null,
        scrollY: 0,
        channel: null
      }
    },
    created() {
      this.channel = new BroadcastChannel('zhht_print_channel')
      this.scrollY = document.documentElement.clientHeight - 140
    },
    methods: {
      com() {
        this.channel.postMessage({
          printData: this.printData,
          printJson: this.printJson
        })
      },
      ok() {},
      cancel() {
        sessionStorage.removeItem('nowPrintTemplate')
        this.visible = false
      }
    }
  }
  </script>
  <style scoped></style>
  

然后在要打印的页面使用,我这边是把打印组件封装到表格组件里了,做成了配置项

效果如图:

点击打印调用浏览器打印页面

点击设计进入设计页面,如图

目前还有很大的瑕疵,例如比较复杂的打印模板无法处理、配置比较麻烦等。

  • 8
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
使用vue-hiprint完成标签打印功能,可以按照以下步骤进行操作: 1. 安装vue-hiprint插件 可以通过npm安装vue-hiprint插件,命令如下: ```npm install vue-hiprint``` 2. 引入vue-hiprint插件 在Vue项目的main.js中引入vue-hiprint插件,代码如下: ``` import Vue from 'vue' import HiPrint from 'vue-hiprint' Vue.use(HiPrint) ``` 3. 编写标签模板 创建标签模板,可以使用HTML和CSS编写模板。例如,以下是一个2×4的标签模板: ``` <div class="label-wrapper"> <div class="label"> <div class="name">Name 1</div> <div class="address">Address 1</div> </div> <div class="label"> <div class="name">Name 2</div> <div class="address">Address 2</div> </div> <div class="label"> <div class="name">Name 3</div> <div class="address">Address 3</div> </div> <div class="label"> <div class="name">Name 4</div> <div class="address">Address 4</div> </div> </div> <style> .label-wrapper { display: flex; flex-wrap: wrap; } .label { width: 50%; height: 50%; border: 1px solid #000; padding: 10px; } .name { font-weight: bold; } .address { margin-top: 10px; } </style> ``` 4. 使用vue-hiprint组件 在Vue组件中使用vue-hiprint组件,并传入标签模板,代码如下: ``` <template> <hi-print ref="print" :debug="true"> <div class="label-wrapper"> <div class="label"> <div class="name">Name 1</div> <div class="address">Address 1</div> </div> <div class="label"> <div class="name">Name 2</div> <div class="address">Address 2</div> </div> <div class="label"> <div class="name">Name 3</div> <div class="address">Address 3</div> </div> <div class="label"> <div class="name">Name 4</div> <div class="address">Address 4</div> </div> </div> </hi-print> </template> ``` 5. 调用打印方法 在Vue组件中调用vue-hiprint打印方法,并指定打印的标签大小和数量,代码如下: ``` this.$refs.print.print({ mediaSize: { width: '2.5in', height: '1.5in' }, copies: 8 }) ``` 这样就可以完成使用vue-hiprint插件实现标签打印功能了。在调用打印方法时,可以根据需要自定义标签大小和打印的数量。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值