ScorePdf.vue 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440
  1. <template>
  2. <!-- 成绩单导出pdf -->
  3. <div class="report_module score_pdf">
  4. <template v-for="(item, page) in state.tableData">
  5. <div class="area_page print_page">
  6. <div class="area_title" v-if="item.isFirstPage">
  7. <div class="page_num">第{{ page + 1 }}页(共{{ state.pageTotal }}页)</div>
  8. <div class="title_text">【{{ `${examName}成绩单(${item?.className || ''})` }}】</div>
  9. <div class="print_time">打印时间:{{ getNowTime() }}</div>
  10. </div>
  11. <div class="area_count" v-if="item.isFirstPage">
  12. 应考:{{ item?.fiveRateResult?.examAllNum || 0 }}人&nbsp;&nbsp;
  13. 实考:{{ item?.fiveRateResult?.effectiveNum || 0 }}人&nbsp;&nbsp;
  14. 缺考:{{ Number(item?.fiveRateResult?.examAllNum || 0) - Number(item?.fiveRateResult?.effectiveNum || 0)
  15. }}人&nbsp;&nbsp;
  16. 满分:{{ item?.fullScore || 0 }}分&nbsp;&nbsp;
  17. 最高分:{{ item?.fiveRateResult?.maxScore || 0 }}分&nbsp;&nbsp;
  18. 最低分:{{ item?.fiveRateResult?.minScore || 0 }}分&nbsp;&nbsp;
  19. 年级均分:{{ item?.fiveRateResult?.avgSchoolScore || 0 }}分&nbsp;&nbsp;
  20. 班级均分:{{ item?.fiveRateResult?.avgScore || 0 }}分
  21. </div>
  22. <div class="module_table table_42">
  23. <el-table :data="item?.listData || []" border stripe :show-header="item.isFirstPage">
  24. <el-table-column v-for="item in state.staticHeaderData" :key="item.prop" :prop="item.prop"
  25. :label="item.label" :width="state.groupDataTitleData.length ? '70px' : 'auto'">
  26. <template #default="scope">
  27. <span v-if="scope.row.score != '缺考' && scope.row.score != '违纪' && item.prop === 'studentUserName'">
  28. {{ scope.row[item.prop] }}
  29. </span>
  30. <template v-else>
  31. {{ scope.row?.[item.prop] || "-" }}
  32. </template>
  33. </template>
  34. </el-table-column>
  35. <el-table-column v-for="(item, index) in state.groupDataTitleData" :key="item.prop" :prop="item.prop"
  36. :label="item.label">
  37. <template #default="scope">{{ scope.row?.dynamicsData?.groupData?.[index] || "-" }}</template>
  38. </el-table-column>
  39. </el-table>
  40. </div>
  41. </div>
  42. </template>
  43. </div>
  44. </template>
  45. <script lang="ts" setup>
  46. import {
  47. studentTranscriptTitle,
  48. queryStudentTranscript,
  49. } from "@/api/analysis";
  50. import { useAnalysisStore } from "@/store/analysis";
  51. import { getNowTime } from "@/utils/common";
  52. import { reactive, computed, nextTick } from "vue";
  53. import { ElMessage } from "element-plus";
  54. import { jsPDF } from "jspdf";
  55. import domtoimage from "dom-to-image";
  56. interface TableColumn {
  57. prop: string;
  58. label: string;
  59. display?: boolean;
  60. [key: string]: any;
  61. }
  62. interface TableCount {
  63. examStudentCount: number | string;
  64. normalCount: number | string;
  65. missExamCount: number | string;
  66. }
  67. interface State {
  68. keyWord: string;
  69. selectClassList: string[];
  70. tableData: any[];
  71. pageTotal: number;
  72. staticHeaderData: TableColumn[];
  73. groupDataTitleData: TableColumn[];
  74. tableCount: TableCount;
  75. tableLoading: Boolean;
  76. }
  77. const analysisStore = useAnalysisStore();
  78. const examName = computed(() => {
  79. return analysisStore.analysisExamInfo.examName || "";
  80. });
  81. const state = reactive<State>({
  82. keyWord: '',
  83. selectClassList: [],
  84. tableData: [],
  85. pageTotal: 0,
  86. staticHeaderData: [],
  87. groupDataTitleData: [],
  88. tableCount: {
  89. examStudentCount: 0,
  90. normalCount: 0,
  91. missExamCount: 0,
  92. },
  93. tableLoading: true
  94. });
  95. /** 获取表头 */
  96. const GetStudentTranscriptTitle = async () => {
  97. if (!analysisStore.filterObject) return;
  98. try {
  99. const res = await studentTranscriptTitle({
  100. ...analysisStore.filterObject,
  101. topicControl: 0,
  102. });
  103. if (res.code === 200) {
  104. const staticHeaderData = res.data?.title?.staticHeaderData || [];
  105. state.staticHeaderData = staticHeaderData.filter(
  106. (item: { display: any }) => item.display,
  107. );
  108. state.groupDataTitleData =
  109. res.data?.title?.dynamicsHeaderData?.groupDataTitle || [];
  110. }
  111. } catch (err) {
  112. console.error("获取表头失败:", err);
  113. }
  114. };
  115. /** 获取表格数据 */
  116. const GetTableData = async () => {
  117. if (!analysisStore.filterObject) return;
  118. try {
  119. state.tableLoading = true;
  120. const res = await queryStudentTranscript({
  121. ...analysisStore.filterObject,
  122. topicControl: 0,
  123. queryStr: state.keyWord,
  124. classIdCodes: state.selectClassList,
  125. });
  126. if (res.code === 200) {
  127. const tableData = res?.data || [];
  128. tablePageData(tableData);//分页处理(内部会设置 state.tableData 和 state.pageTotal)
  129. }
  130. } catch (err) {
  131. console.error("获取表格数据失败:", err);
  132. state.tableData = [];
  133. state.pageTotal = 0;
  134. } finally {
  135. state.tableLoading = false;
  136. }
  137. };
  138. //分页:超过一页自动换页,后续页不包含标题行和应考/实考/缺考统计行
  139. const tablePageData = (list: any[]) => {
  140. const trLineHeight = 21;//表格表头、tr行高
  141. const printPageHeight = 1285;//打印页面高度
  142. const rowNum = Math.floor(printPageHeight / trLineHeight);//每页可容纳行数 向下取整
  143. const firstPageRows = rowNum - 3;//第一页数据行数:标题行+统计行+表头行占3行
  144. const otherPageRows = rowNum;//后续页数据行数:无标题、无统计、无表头,数据行放满 原来是 rowNum - 1,后续页没有表头占位了,数据行放满
  145. const pageList: any[] = [];
  146. list.forEach((item) => {
  147. const dataList = item?.listData || [];
  148. //无数据也保留一页(标题+统计+空表)
  149. if (!dataList.length) {
  150. pageList.push({ ...item, listData: [], isFirstPage: true });
  151. return;
  152. }
  153. //总页数:第一页放 firstPageRows 行,其余每页 otherPageRows 行
  154. const pageNum =
  155. Math.ceil((dataList.length - firstPageRows) / otherPageRows) + 1;
  156. for (let page = 1; page <= pageNum; page++) {
  157. const start =
  158. page === 1 ? 0 : firstPageRows + (page - 2) * otherPageRows;
  159. const rows =
  160. page === 1
  161. ? Math.min(firstPageRows, dataList.length)
  162. : Math.min(otherPageRows, dataList.length - start);
  163. //第二页及后续页的数据放入拆出来的 listData,页面上不渲染标题和统计行
  164. pageList.push({
  165. ...item,
  166. listData: dataList.slice(start, start + rows),
  167. isFirstPage: page === 1,
  168. });
  169. }
  170. });
  171. state.tableData = pageList;
  172. state.pageTotal = pageList.length;
  173. }
  174. // 初始化
  175. const PageInit = async (keyWord: string, selectClassList: string[]) => {
  176. state.keyWord = keyWord;
  177. state.selectClassList = selectClassList;
  178. await Promise.all([GetStudentTranscriptTitle(), GetTableData()]);
  179. };
  180. // 导出PDF并在浏览器新窗口打开
  181. const ExportPdf = async () => {
  182. const elements = document.querySelectorAll(".score_pdf .print_page");
  183. if (!elements.length) {
  184. ElMessage.warning("未找到可导出的页面内容,请先加载数据!");
  185. return;
  186. }
  187. // 在用户手势内同步打开空白窗口,避免被浏览器拦截
  188. const win = window.open("", "_blank");
  189. if (!win) {
  190. ElMessage.warning("浏览器拦截了弹窗,请允许后重试");
  191. return;
  192. }
  193. win.document.write(
  194. "<p style='font-family:sans-serif;text-align:center;padding-top:40px'>成绩单 PDF 生成中…</p>",
  195. );
  196. const pdf = new jsPDF("p", "pt", "a4");
  197. const pdfWidth = pdf.internal.pageSize.getWidth();
  198. const pdfHeight = pdf.internal.pageSize.getHeight();
  199. for (const [pageIndex, element] of Array.from(elements).entries()) {
  200. await nextTick();
  201. const htmlElement = element as HTMLElement;
  202. htmlElement.style.visibility = "visible";
  203. htmlElement.offsetHeight;
  204. // 等待该页渲染完成
  205. await new Promise((resolve) => setTimeout(resolve, 150));
  206. const dataUrl = await domtoimage.toJpeg(htmlElement, {
  207. quality: 0.9,
  208. width: htmlElement.scrollWidth * 2,
  209. height: htmlElement.scrollHeight * 2,
  210. canvasWidth: htmlElement.scrollWidth * 2,
  211. canvasHeight: htmlElement.scrollHeight * 2,
  212. style: {
  213. transform: "scale(2)",
  214. "transform-origin": "top left",
  215. "background-color": "#ffffff",
  216. overflow: "visible",
  217. "white-space": "normal",
  218. position: "relative",
  219. visibility: "visible",
  220. },
  221. bgcolor: "#ffffff",
  222. });
  223. const imgProps = pdf.getImageProperties(dataUrl);
  224. const imgWidth = imgProps.width;
  225. const imgHeight = imgProps.height;
  226. const ratio = Math.min(pdfWidth / imgWidth, pdfHeight / imgHeight);
  227. const adjustWidth = imgWidth * ratio;
  228. const adjustHeight = imgHeight * ratio;
  229. const xPosition = (pdfWidth - adjustWidth) / 2;
  230. const yPosition = (pdfHeight - adjustHeight) / 2;
  231. if (pageIndex > 0) {
  232. pdf.addPage();
  233. }
  234. pdf.addImage(
  235. dataUrl,
  236. "JPEG",
  237. xPosition,
  238. yPosition,
  239. adjustWidth,
  240. adjustHeight,
  241. );
  242. }
  243. // // 直接打开生成的PDF,保留浏览器自带的下载/打印工具栏
  244. // const filename = `${examName.value}成绩单.pdf`;
  245. // // 通过 PDF 文档属性设置标题,浏览器查看器的标签页标题即显示该文件名
  246. // pdf.setProperties({ title: filename });
  247. // const blob = pdf.output("blob");
  248. // const url = URL.createObjectURL(
  249. // new File([blob], filename, { type: "application/pdf" }),
  250. // );
  251. // win.location.replace(url);
  252. // 在浏览器新窗口打开生成的PDF(中转页方案:窗口标题、下载文件名均使用指定名称)
  253. const filename = `${examName.value}成绩单.pdf`;
  254. const blob = pdf.output("blob");
  255. const url = URL.createObjectURL(
  256. new File([blob], filename, { type: "application/pdf" }),
  257. );
  258. // 转义文件名中的特殊字符,防止破坏 HTML
  259. const safeName = filename
  260. .replace(/&/g, "&amp;")
  261. .replace(/</g, "&lt;")
  262. .replace(/>/g, "&gt;")
  263. .replace(/"/g, "&quot;");
  264. // 清空"生成中"占位页,写入中转页
  265. win.document.open();
  266. win.document.write(
  267. `<!DOCTYPE html>
  268. <html lang="zh-CN">
  269. <head>
  270. <meta charset="utf-8">
  271. <title>${safeName}</title>
  272. <style>
  273. body{margin:0;font-family:-apple-system,"PingFang SC","Microsoft YaHei",sans-serif;}
  274. .bar{height:48px;display:flex;align-items:center;gap:12px;padding:0 16px;background:#f5f6f7;border-bottom:1px solid #dcdfe6;box-sizing:border-box;}
  275. .bar .fname{flex:1;font-size:14px;color:#333;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;}
  276. .bar button{color:#fff;background:#2e64fa;border:0;padding:6px 16px;border-radius:4px;font-size:13px;cursor:pointer;flex-shrink:0;}
  277. iframe{width:100%;height:calc(100vh - 48px);border:0;display:block;}
  278. @media print{
  279. .bar{display:none;}
  280. iframe{height:100vh;}
  281. }
  282. </style>
  283. </head>
  284. <body>
  285. <div class="bar">
  286. <span class="fname">${safeName}</span>
  287. <button onclick="window.print()">下载PDF</button>
  288. </div>
  289. <iframe src="${url}"></iframe>
  290. </body>
  291. </html>`,
  292. );
  293. win.document.close();
  294. };
  295. // 加载数据并导出PDF(供父组件一步调用)
  296. const LoadAndExportPdf = async (keyWord: string, selectClassList: string[]) => {
  297. await PageInit(keyWord, selectClassList);
  298. await nextTick();
  299. await ExportPdf();
  300. };
  301. // 暴露方法供父组件调用
  302. defineExpose({
  303. PageInit,
  304. ExportPdf,
  305. LoadAndExportPdf
  306. });
  307. </script>
  308. <style lang="scss" scoped>
  309. .score_pdf {
  310. width: 908px;
  311. margin: 0 auto;
  312. position: absolute;
  313. top: 0;
  314. left: -9999px;
  315. z-index: -10;
  316. .area_page {
  317. width: 908px;
  318. margin-top: 20px;
  319. padding: 12px 5px 0 !important;
  320. background-color: #fff;
  321. box-sizing: border-box;
  322. overflow: hidden;
  323. &.print_page {
  324. height: 1285px;
  325. }
  326. .area_title {
  327. width: 100%;
  328. height: 21px;
  329. line-height: 21px;
  330. display: flex;
  331. justify-content: center;
  332. align-items: center;
  333. .page_num {
  334. font-size: 12px;
  335. color: #000000;
  336. flex-shrink: 0;
  337. }
  338. .print_time {
  339. font-size: 12px;
  340. color: #000000;
  341. flex-shrink: 0;
  342. }
  343. .title_text {
  344. font-weight: bold;
  345. font-size: 16px;
  346. color: #000000;
  347. flex: 1;
  348. text-align: center;
  349. white-space: nowrap;
  350. overflow: hidden;
  351. text-overflow: ellipsis;
  352. }
  353. }
  354. .area_count {
  355. height: 21px;
  356. width: 100%;
  357. font-size: 12px;
  358. color: #000000;
  359. text-align: center;
  360. line-height: 21px;
  361. overflow: hidden;
  362. white-space: nowrap;
  363. text-overflow: ellipsis;
  364. }
  365. .module_table {
  366. width: 100%;
  367. :deep(.el-table) {
  368. border-radius: 6px;
  369. border-left: 0px;
  370. border-right: 0px;
  371. .el-table__header {
  372. height: 20px !important;
  373. thead {
  374. height: 20px !important;
  375. font-size: 12px;
  376. }
  377. .el-table__cell {
  378. height: 20px !important;
  379. }
  380. .cell {
  381. font-size: 12px;
  382. }
  383. }
  384. .el-table__body {
  385. tr {
  386. height: 20px !important;
  387. font-size: 12px;
  388. .el-table__cell {
  389. height: 20px !important;
  390. }
  391. }
  392. }
  393. .cell {
  394. line-height: 20px;
  395. display: block;
  396. text-align: center;
  397. white-space: nowrap;
  398. padding: 0 0 0 4px !important;
  399. color: #000000;
  400. }
  401. }
  402. }
  403. }
  404. }
  405. </style>