| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440 |
- <template>
- <!-- 成绩单导出pdf -->
- <div class="report_module score_pdf">
- <template v-for="(item, page) in state.tableData">
- <div class="area_page print_page">
- <div class="area_title" v-if="item.isFirstPage">
- <div class="page_num">第{{ page + 1 }}页(共{{ state.pageTotal }}页)</div>
- <div class="title_text">【{{ `${examName}成绩单(${item?.className || ''})` }}】</div>
- <div class="print_time">打印时间:{{ getNowTime() }}</div>
- </div>
- <div class="area_count" v-if="item.isFirstPage">
- 应考:{{ item?.fiveRateResult?.examAllNum || 0 }}人
- 实考:{{ item?.fiveRateResult?.effectiveNum || 0 }}人
- 缺考:{{ Number(item?.fiveRateResult?.examAllNum || 0) - Number(item?.fiveRateResult?.effectiveNum || 0)
- }}人
- 满分:{{ item?.fullScore || 0 }}分
- 最高分:{{ item?.fiveRateResult?.maxScore || 0 }}分
- 最低分:{{ item?.fiveRateResult?.minScore || 0 }}分
- 年级均分:{{ item?.fiveRateResult?.avgSchoolScore || 0 }}分
- 班级均分:{{ item?.fiveRateResult?.avgScore || 0 }}分
- </div>
- <div class="module_table table_42">
- <el-table :data="item?.listData || []" border stripe :show-header="item.isFirstPage">
- <el-table-column v-for="item in state.staticHeaderData" :key="item.prop" :prop="item.prop"
- :label="item.label" :width="state.groupDataTitleData.length ? '70px' : 'auto'">
- <template #default="scope">
- <span v-if="scope.row.score != '缺考' && scope.row.score != '违纪' && item.prop === 'studentUserName'">
- {{ scope.row[item.prop] }}
- </span>
- <template v-else>
- {{ scope.row?.[item.prop] || "-" }}
- </template>
- </template>
- </el-table-column>
- <el-table-column v-for="(item, index) in state.groupDataTitleData" :key="item.prop" :prop="item.prop"
- :label="item.label">
- <template #default="scope">{{ scope.row?.dynamicsData?.groupData?.[index] || "-" }}</template>
- </el-table-column>
- </el-table>
- </div>
- </div>
- </template>
- </div>
- </template>
- <script lang="ts" setup>
- import {
- studentTranscriptTitle,
- queryStudentTranscript,
- } from "@/api/analysis";
- import { useAnalysisStore } from "@/store/analysis";
- import { getNowTime } from "@/utils/common";
- import { reactive, computed, nextTick } from "vue";
- import { ElMessage } from "element-plus";
- import { jsPDF } from "jspdf";
- import domtoimage from "dom-to-image";
- interface TableColumn {
- prop: string;
- label: string;
- display?: boolean;
- [key: string]: any;
- }
- interface TableCount {
- examStudentCount: number | string;
- normalCount: number | string;
- missExamCount: number | string;
- }
- interface State {
- keyWord: string;
- selectClassList: string[];
- tableData: any[];
- pageTotal: number;
- staticHeaderData: TableColumn[];
- groupDataTitleData: TableColumn[];
- tableCount: TableCount;
- tableLoading: Boolean;
- }
- const analysisStore = useAnalysisStore();
- const examName = computed(() => {
- return analysisStore.analysisExamInfo.examName || "";
- });
- const state = reactive<State>({
- keyWord: '',
- selectClassList: [],
- tableData: [],
- pageTotal: 0,
- staticHeaderData: [],
- groupDataTitleData: [],
- tableCount: {
- examStudentCount: 0,
- normalCount: 0,
- missExamCount: 0,
- },
- tableLoading: true
- });
- /** 获取表头 */
- const GetStudentTranscriptTitle = async () => {
- if (!analysisStore.filterObject) return;
- try {
- const res = await studentTranscriptTitle({
- ...analysisStore.filterObject,
- topicControl: 0,
- });
- if (res.code === 200) {
- const staticHeaderData = res.data?.title?.staticHeaderData || [];
- state.staticHeaderData = staticHeaderData.filter(
- (item: { display: any }) => item.display,
- );
- state.groupDataTitleData =
- res.data?.title?.dynamicsHeaderData?.groupDataTitle || [];
- }
- } catch (err) {
- console.error("获取表头失败:", err);
- }
- };
- /** 获取表格数据 */
- const GetTableData = async () => {
- if (!analysisStore.filterObject) return;
- try {
- state.tableLoading = true;
- const res = await queryStudentTranscript({
- ...analysisStore.filterObject,
- topicControl: 0,
- queryStr: state.keyWord,
- classIdCodes: state.selectClassList,
- });
- if (res.code === 200) {
- const tableData = res?.data || [];
- tablePageData(tableData);//分页处理(内部会设置 state.tableData 和 state.pageTotal)
- }
- } catch (err) {
- console.error("获取表格数据失败:", err);
- state.tableData = [];
- state.pageTotal = 0;
- } finally {
- state.tableLoading = false;
- }
- };
- //分页:超过一页自动换页,后续页不包含标题行和应考/实考/缺考统计行
- const tablePageData = (list: any[]) => {
- const trLineHeight = 21;//表格表头、tr行高
- const printPageHeight = 1285;//打印页面高度
- const rowNum = Math.floor(printPageHeight / trLineHeight);//每页可容纳行数 向下取整
- const firstPageRows = rowNum - 3;//第一页数据行数:标题行+统计行+表头行占3行
- const otherPageRows = rowNum;//后续页数据行数:无标题、无统计、无表头,数据行放满 原来是 rowNum - 1,后续页没有表头占位了,数据行放满
- const pageList: any[] = [];
- list.forEach((item) => {
- const dataList = item?.listData || [];
- //无数据也保留一页(标题+统计+空表)
- if (!dataList.length) {
- pageList.push({ ...item, listData: [], isFirstPage: true });
- return;
- }
- //总页数:第一页放 firstPageRows 行,其余每页 otherPageRows 行
- const pageNum =
- Math.ceil((dataList.length - firstPageRows) / otherPageRows) + 1;
- for (let page = 1; page <= pageNum; page++) {
- const start =
- page === 1 ? 0 : firstPageRows + (page - 2) * otherPageRows;
- const rows =
- page === 1
- ? Math.min(firstPageRows, dataList.length)
- : Math.min(otherPageRows, dataList.length - start);
- //第二页及后续页的数据放入拆出来的 listData,页面上不渲染标题和统计行
- pageList.push({
- ...item,
- listData: dataList.slice(start, start + rows),
- isFirstPage: page === 1,
- });
- }
- });
- state.tableData = pageList;
- state.pageTotal = pageList.length;
- }
- // 初始化
- const PageInit = async (keyWord: string, selectClassList: string[]) => {
- state.keyWord = keyWord;
- state.selectClassList = selectClassList;
- await Promise.all([GetStudentTranscriptTitle(), GetTableData()]);
- };
- // 导出PDF并在浏览器新窗口打开
- const ExportPdf = async () => {
- const elements = document.querySelectorAll(".score_pdf .print_page");
- if (!elements.length) {
- ElMessage.warning("未找到可导出的页面内容,请先加载数据!");
- return;
- }
- // 在用户手势内同步打开空白窗口,避免被浏览器拦截
- const win = window.open("", "_blank");
- if (!win) {
- ElMessage.warning("浏览器拦截了弹窗,请允许后重试");
- return;
- }
- win.document.write(
- "<p style='font-family:sans-serif;text-align:center;padding-top:40px'>成绩单 PDF 生成中…</p>",
- );
- const pdf = new jsPDF("p", "pt", "a4");
- const pdfWidth = pdf.internal.pageSize.getWidth();
- const pdfHeight = pdf.internal.pageSize.getHeight();
- for (const [pageIndex, element] of Array.from(elements).entries()) {
- await nextTick();
- const htmlElement = element as HTMLElement;
- htmlElement.style.visibility = "visible";
- htmlElement.offsetHeight;
- // 等待该页渲染完成
- await new Promise((resolve) => setTimeout(resolve, 150));
- const dataUrl = await domtoimage.toJpeg(htmlElement, {
- quality: 0.9,
- width: htmlElement.scrollWidth * 2,
- height: htmlElement.scrollHeight * 2,
- canvasWidth: htmlElement.scrollWidth * 2,
- canvasHeight: htmlElement.scrollHeight * 2,
- style: {
- transform: "scale(2)",
- "transform-origin": "top left",
- "background-color": "#ffffff",
- overflow: "visible",
- "white-space": "normal",
- position: "relative",
- visibility: "visible",
- },
- bgcolor: "#ffffff",
- });
- const imgProps = pdf.getImageProperties(dataUrl);
- const imgWidth = imgProps.width;
- const imgHeight = imgProps.height;
- const ratio = Math.min(pdfWidth / imgWidth, pdfHeight / imgHeight);
- const adjustWidth = imgWidth * ratio;
- const adjustHeight = imgHeight * ratio;
- const xPosition = (pdfWidth - adjustWidth) / 2;
- const yPosition = (pdfHeight - adjustHeight) / 2;
- if (pageIndex > 0) {
- pdf.addPage();
- }
- pdf.addImage(
- dataUrl,
- "JPEG",
- xPosition,
- yPosition,
- adjustWidth,
- adjustHeight,
- );
- }
- // // 直接打开生成的PDF,保留浏览器自带的下载/打印工具栏
- // const filename = `${examName.value}成绩单.pdf`;
- // // 通过 PDF 文档属性设置标题,浏览器查看器的标签页标题即显示该文件名
- // pdf.setProperties({ title: filename });
- // const blob = pdf.output("blob");
- // const url = URL.createObjectURL(
- // new File([blob], filename, { type: "application/pdf" }),
- // );
- // win.location.replace(url);
- // 在浏览器新窗口打开生成的PDF(中转页方案:窗口标题、下载文件名均使用指定名称)
- const filename = `${examName.value}成绩单.pdf`;
- const blob = pdf.output("blob");
- const url = URL.createObjectURL(
- new File([blob], filename, { type: "application/pdf" }),
- );
- // 转义文件名中的特殊字符,防止破坏 HTML
- const safeName = filename
- .replace(/&/g, "&")
- .replace(/</g, "<")
- .replace(/>/g, ">")
- .replace(/"/g, """);
- // 清空"生成中"占位页,写入中转页
- win.document.open();
- win.document.write(
- `<!DOCTYPE html>
- <html lang="zh-CN">
- <head>
- <meta charset="utf-8">
- <title>${safeName}</title>
- <style>
- body{margin:0;font-family:-apple-system,"PingFang SC","Microsoft YaHei",sans-serif;}
- .bar{height:48px;display:flex;align-items:center;gap:12px;padding:0 16px;background:#f5f6f7;border-bottom:1px solid #dcdfe6;box-sizing:border-box;}
- .bar .fname{flex:1;font-size:14px;color:#333;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;}
- .bar button{color:#fff;background:#2e64fa;border:0;padding:6px 16px;border-radius:4px;font-size:13px;cursor:pointer;flex-shrink:0;}
- iframe{width:100%;height:calc(100vh - 48px);border:0;display:block;}
- @media print{
- .bar{display:none;}
- iframe{height:100vh;}
- }
- </style>
- </head>
- <body>
- <div class="bar">
- <span class="fname">${safeName}</span>
- <button onclick="window.print()">下载PDF</button>
- </div>
- <iframe src="${url}"></iframe>
- </body>
- </html>`,
- );
- win.document.close();
- };
- // 加载数据并导出PDF(供父组件一步调用)
- const LoadAndExportPdf = async (keyWord: string, selectClassList: string[]) => {
- await PageInit(keyWord, selectClassList);
- await nextTick();
- await ExportPdf();
- };
- // 暴露方法供父组件调用
- defineExpose({
- PageInit,
- ExportPdf,
- LoadAndExportPdf
- });
- </script>
- <style lang="scss" scoped>
- .score_pdf {
- width: 908px;
- margin: 0 auto;
- position: absolute;
- top: 0;
- left: -9999px;
- z-index: -10;
- .area_page {
- width: 908px;
- margin-top: 20px;
- padding: 12px 5px 0 !important;
- background-color: #fff;
- box-sizing: border-box;
- overflow: hidden;
- &.print_page {
- height: 1285px;
- }
- .area_title {
- width: 100%;
- height: 21px;
- line-height: 21px;
- display: flex;
- justify-content: center;
- align-items: center;
- .page_num {
- font-size: 12px;
- color: #000000;
- flex-shrink: 0;
- }
- .print_time {
- font-size: 12px;
- color: #000000;
- flex-shrink: 0;
- }
- .title_text {
- font-weight: bold;
- font-size: 16px;
- color: #000000;
- flex: 1;
- text-align: center;
- white-space: nowrap;
- overflow: hidden;
- text-overflow: ellipsis;
- }
- }
- .area_count {
- height: 21px;
- width: 100%;
- font-size: 12px;
- color: #000000;
- text-align: center;
- line-height: 21px;
- overflow: hidden;
- white-space: nowrap;
- text-overflow: ellipsis;
- }
- .module_table {
- width: 100%;
- :deep(.el-table) {
- border-radius: 6px;
- border-left: 0px;
- border-right: 0px;
- .el-table__header {
- height: 20px !important;
- thead {
- height: 20px !important;
- font-size: 12px;
- }
- .el-table__cell {
- height: 20px !important;
- }
- .cell {
- font-size: 12px;
- }
- }
- .el-table__body {
- tr {
- height: 20px !important;
- font-size: 12px;
- .el-table__cell {
- height: 20px !important;
- }
- }
- }
- .cell {
- line-height: 20px;
- display: block;
- text-align: center;
- white-space: nowrap;
- padding: 0 0 0 4px !important;
- color: #000000;
- }
- }
- }
- }
- }
- </style>
|