JeecgBoot3.6.1 中打印功能实现

news/2024/7/10 3:09:40 标签: jeecgboot, java, vue

JeecgBoot3.6.1中实现打印功能

前言

在项目开发中我们可能会遇到打印得需求,基于JeecgBoot框架做了如下案例

一、前端

vueListvue_5">1、vue页面代码:List.vue

java"><template>
    <BasicTable @register="registerTable" :rowSelection="rowSelection">
      <!--本身的列表代码省略-->	
      <!--插槽:table标题-->
      <template #tableTitle>
        <a-button type="primary" @click="print"> 重打指引单</a-button>
      </template>
    </BasicTable>
  </div>
</template>

<script lang="ts" name="triage-hisOpWaitQueue" setup>
  import { ref } from 'vue';
  import { BasicTable, TableAction } from '/@/components/Table';
  import { useListPage } from '/@/hooks/system/useListPage';
  import { columns, searchFormSchema } from './List.data';
  import { list, selectTeacInfo } from './List.api';
  import { useUserStore } from '/@/store/modules/user';
  import { useMessage } from '/@/hooks/web/useMessage';
  import printJS from 'print-js';

  const checkedKeys = ref<Array<string | number>>([]);
  const userStore = useUserStore();
  const { createWarningModal } = useMessage();
  // 定义一个响应式 ref 作为表格数据源
  const dataSource = ref([]);
  //注册table数据
  const { tableContext } = useListPage({
    tableProps: {
      title: '',
      dataSource,
      api: list,
      columns,
      canResize: false,
      formConfig: {
        //labelWidth: 120,
        schemas: searchFormSchema,
        autoSubmitOnEnter: true,
        showAdvancedButton: true,
        fieldMapToNumber: [],
        fieldMapToTime: [],
      },
      actionColumn: {
        width: 150,
        fixed: 'right',
      },
    },
  });

  const [registerTable, { reload }, { rowSelection, selectedRowKeys }] = tableContext;
  /**
   * 打印公共方法
   * 
   */
  async function print() {
    const printInfo = await selectTeacInfo({
      queryType: '1',
      queryValue: '213123213213123',
    });
    console.log(JSON.stringify(printInfo));
    if (printInfo.state == 0) {
      createWarningModal({ title: '温馨提示', content: '数据为空' });
    } else {
      const data = {
        标题: printInfo.teaVO.title + '(学生明细)',
        教师名称: printInfo.teaVO.teaName,
        教师年龄: printInfo.teaVO.teaAge,
        教师性别: printInfo.teaVO.teaSex,
      };

      // 根据stuList生成二维数组
      let htmlContent2 = '';
      const data2D = [];
        for (const item of printInfo.stuList) {
          data2D.push([
            item.teaName || '-', // 学生名称
            item.teaAge, // 学生年龄
            item.describe || '-', // 学生描述(如果不存在特殊提示,则用破折号填充)
          ]);
        }

        // 构建HTML内容
        htmlContent2 =
          '<tr><td colspan="3" style="text-align: center;font-weight: bold;">学生明细</td></tr>' +
          // 添加列标题行
          '<tr style="text-align: center;font-weight: bold;"><td>学生名称</td><td>学生年龄</td><td>学生描述</td></tr>';

      let htmlContent = '<table>';
      for (const key in data) {
        htmlContent += '<tr><td>' + key + '</td><td colspan="3">' + data[key] + '</td></tr>';
      }

      // 遍历每一行
      for (const row of data2D) {
        htmlContent2 += '<tr>';

        // 遍历每一列
        for (const item of row) {
          htmlContent2 += `<td style="width: 15ch; word-wrap: break-word; overflow-wrap: break-word;">${item}</td>`;
        }

        htmlContent2 += '</tr>';
      }
      htmlContent += htmlContent2;
      htmlContent += '</table>';
      htmlContent = htmlContent.replace('Document', 'Guide Bill');
      printJS({
        printable: htmlContent,
        type: 'raw-html',
        header: 'Guide Bill',
        style:
          '.printable { font-family: Arial; } .description { font-weight: bold; } table { border-collapse: collapse; width: 100%; } td { border: 1px solid black; padding: 5px; }',
      });
    }
  }

  /**
   * 成功回调
   */
  function handleSuccess() {
    (selectedRowKeys.value = []) && reload();
  }
</script>

<style scoped>
  .btn {
    margin-right: 4px;
  }
</style>

2、List.api.ts

java">import { defHttp } from '/@/utils/http/axios';
import { useMessage } from '/@/hooks/web/useMessage';

const { createConfirm } = useMessage();

enum Api {
  selectTeacInfo= '/teacher/teacher/selectTeacInfo',
}

/**
 * 查询打印信息
 * @param params
 * @returns
 */
export const selectTeacInfo = (params) => defHttp.get({ url: Api.selectTeacInfo, params });

3、后端返回数据结构

java">{
	"stuList": [{
		"id": 1,
		"stuName": '张三',
		"stuAge": 15
		"describe": "优秀",
	}, {
		"id": 2,
		"stuName": '李四',
		"stuAge": 15
		"describe": "有进步空间",
	}],
	"teaVO": {
		"title": '数据列表',
		"teaAge": 26,
		"teaSex": 1,
	},
	"state": 1,
}

二、后端

java">@ApiOperation(value = "根据教师查询打印信息", notes = "根据教师查询打印信息")
@GetMapping(value = "/selectTeacInfo")
public Result<Map> selectTeacInfo(String identificationValue){
	Map map = new HashMap();
	if(StringUtils.isBlank(identificationValue)){
	    return Result.error("identificationValue参数为空");
	}else{
		// 判断是否有值
		int state = 1;
		List<Student> studentList = null;// 查询所有得学生记录
		QueryWrapper<Teacher> queryWrapper = new QueryWrapper<>();
		queryWrapper.lambda().eq(Teacher::getId,identificationValue);
		Teacher teacher = teacherService.getOne(queryWrapper);
		if (teacher!=null){
			teacher.setTitle("数据列表");// 此字段数据库中不存在,仅为显示服务
			QueryWrapper<Student> queryWrapper1 = new QueryWrapper<>();
			queryWrapper1.lambda().eq(Student::getClassId,teacher.getId());
			// 查询学生
			studentList = teacherService.list(queryWrapper1);
		}else{
			state = 0;
		}
		
		map.put("stuList",studentList);
		map.put("teaVo",teacher);
		map.put("state",state);
		return Result.ok(map);
	    }else{
		return Result.error("数据不存在");
	    }
	}
}

执行结果:

在这里插入图片描述

总结

道阻且长,一起加油哦!!!


http://www.niftyadmin.cn/n/5402619.html

相关文章

解决:selenium web browser 的版本适配问题

文章目录 解决方案&#xff1a;使用 webdriver manager 自动适配驱动 使用 selenium 操控浏览器的时候报错&#xff1a; The chromedriver version (114.0.5735.90) detected in PATH at /opt/homebrew/bin/chromedriver might not be compatible with the detected chrome ve…

《探索数据结构之美:如何高效实现哈希表》

摘要&#xff1a;哈希表是一种基于键值对的数据结构&#xff0c;它通过哈希函数将键映射到表中一个位置&#xff0c;以实现快速的插入、删除和查找操作。在本期播客中&#xff0c;我们将深入剖析哈希表的数据结构&#xff0c;分享如何用Python语言实现一个哈希表项目。此外&…

Node.js_基础知识(fs模块 - 文件操作)

写入 文件操作 流式写入&#xff1a;fs.createWriteStream(path[, options]) 可以减少打开关闭文件的次数适用于&#xff1a;大文件写入、频繁写入参数说明&#xff1a; path&#xff1a;文件路径 文件夹操作&#xff1a; 调用mkdir方法&#xff1a;fs.mkdir(./a/b/c, err &…

php连接hdfs初步探索

一、phdfs拓展 结果&#xff1a;暂时舍弃 安装此拓展时&#xff0c;无法make成功&#xff0c;因为缺少hdfs.n文件。 换了其他版本的拓展包&#xff0c;并编译都没有找到此文件。 后搜到官网的相关资料&#xff0c;此hdfs.h的文件路径的地址是$HADOOP_HDFS_HOME/include/hdfs…

计算机程序设计基础

计算机程序设计基础 程序数据结构算法。计算机程序的灵魂&#xff0c;即算法。算法实现的基础之一&#xff0c;即数据机构。应用数学&#xff0c;是数学的一门学科&#xff0c;是算法的理论基础。AI的核心&#xff0c;即人工智能算法。加密技术的核心&#xff0c;即加密算法。应…

AWS ECS Fargate禁止公网访问

当在AWS ECS(Elastic Container Service)上运行任务时,默认情况下,ECS会自动为每个任务分配一个公有IP地址。然而,并不是所有的情况下都需要或希望任务具有公有IP地址(NAT或公网拉取镜像需要)。在某些情况下,你可能希望ECS任务只能通过私有IP地址访问,并且不暴露到公共网…

前端Vue3项目如何打包成Docker镜像运行

将前端Vue3项目打包成Docker镜像并运行包括几个主要步骤&#xff1a;项目打包、编写Dockerfile、构建镜像和运行容器。下面是一个基本的流程&#xff1a; 1. 项目打包 首先&#xff0c;确保你的Vue3项目可以正常运行和打包。在项目根目录下执行以下命令来打包你的Vue3项目&am…

益生菌不一定全是“益”,也存在一定的安全风险

谷禾健康 益生菌被世界卫生组织定义为“当摄入足够量时,可为宿主带来健康益处的活微生物”。近年来,随着人们发现其可用于预防、减轻或治疗特定疾病以及改善健康,益生菌在食品和临床治疗中的应用越来越广泛。 大量研究表明,益生菌有助于维持肠道菌群的平衡,促进消化和吸收…