Przeglądaj źródła

fix:648【行政审批】协同办公里的表单,支持可导出PDF、可打印

mlchen 5 dni temu
rodzic
commit
9cd5168122

+ 130 - 0
src/views/bpm/collaborative/detail.vue

@@ -208,6 +208,9 @@
     ></outgoingDetails>
     <div slot="footer" class="footer">
       <el-button type="primary" @click="print">打印</el-button>
+      <el-button :loading="pdfExporting" @click="exportPdf">
+        导出PDF
+      </el-button>
       <!-- <el-button @click="openPreview">预览</el-button> -->
       <el-button @click="cancel">返回</el-button>
     </div>
@@ -243,6 +246,11 @@ import businessTripComponent from '@/BIZComponents/processSubmitDialog/component
 import { getGroupUserTree, getProduceTreeByCode } from '@/api/main';
 import { listOrganizations, getUserPage } from '@/api/system/organization';
 import { getTaskListByProcessInstanceId } from '@/api/bpm/task';
+import {
+  buildPdfFileName,
+  buildSinglePdfFileName,
+  exportHtmlListToPdf
+} from './export/pdfExport';
 import store from '@/store';
 
 export default {
@@ -283,6 +291,8 @@ export default {
       isRight: false,
       previewDialog: false,
       previewHtml: '',
+      // 「导出PDF」生成中标记,用于按钮 loading 与防重复点击
+      pdfExporting: false,
       remoteOptionsCache: {},
       tasks: [],
       deptList: [],
@@ -395,6 +405,10 @@ export default {
       if (this.form.id) {
         storageApi.getInfoBySourceBizNo(this.form.id).then((res) => {
           this.outgoingData = res;
+        }).catch((e) => {
+          // 外发单只是装饰性区块:取不到不能打断单据详情展示
+          this.outgoingData = null;
+          console.warn('加载外发单信息失败', e);
         });
         this.getTaskList();
       }
@@ -567,6 +581,10 @@ export default {
         if (this.form.id) {
           storageApi.getInfoBySourceBizNo(this.form.id).then((res) => {
             this.outgoingData = res;
+          }).catch((e) => {
+            // 外发单只是装饰性区块:取不到不能打断批量打印
+            this.outgoingData = null;
+            console.warn('加载外发单信息失败', e);
           });
           // 等待审批记录加载完成,确保 generateTasksPrintHtml 有数据
           await this.loadTasks(this.form.id);
@@ -613,6 +631,118 @@ export default {
       }, 300);
     },
 
+      // 单条导出PDF:内容与「打印」同源(同一份 generatePrintHtml 输出)
+      async exportPdf() {
+        if (this.pdfExporting) return;
+        this.pdfExporting = true;
+        try {
+          const making =
+            this.jsonData ||
+            (this.form.formJson && JSON.parse(this.form.formJson.makingJson));
+          // 与 print() 一致:先确保远程数据就绪,再做 id -> name 映射
+          await this.ensureRemoteData(making);
+          const html = this.generatePrintHtml(
+            making,
+            this.form.valueJson || {},
+            this.form
+          );
+          const fileName = buildSinglePdfFileName(
+            this.form.formName,
+            this.form.formName ? null : this.form.id
+          );
+          await exportHtmlListToPdf([html], fileName);
+          this.$message &&
+            this.$message.success &&
+            this.$message.success('导出PDF成功');
+        } catch (e) {
+          console.error('导出PDF失败', e);
+          this.$message &&
+            this.$message.error &&
+            this.$message.error(e && e.message ? e.message : '导出PDF失败');
+        } finally {
+          this.pdfExporting = false;
+        }
+      },
+
+      // 批量导出PDF:数据装配与 printRows 完全一致,每条记录一份 HTML,按序分页
+      async exportPdfRows(rows, options = {}) {
+        if (!rows || !rows.length) {
+          this.$message &&
+            this.$message.warning &&
+            this.$message.warning('请先勾选需要导出的记录');
+          return { pageCount: 0, skipped: 0 };
+        }
+        if (this.pdfExporting) return { pageCount: 0, skipped: 0 };
+        this.pdfExporting = true;
+        const htmlList = [];
+        let failed = 0;
+        try {
+          for (let i = 0; i < rows.length; i += 1) {
+            const row = rows[i];
+            try {
+              // 复用 printRows 的数据装配逻辑,保证 PDF 与打印内容一致
+              // eslint-disable-next-line no-undef
+              this.form = _.cloneDeep(row);
+              // 兼容后端附件字段名为 file 或 files
+              const adoptList = this.form?.valueJson?.blank_adopzrdd;
+              if (Array.isArray(adoptList)) {
+                adoptList.forEach((item) => {
+                  if (item && item.file == null && item.files != null) {
+                    item.file = item.files;
+                  }
+                });
+              }
+              this.applyMockReimbursement();
+              if (this.form.id) {
+                storageApi
+                  .getInfoBySourceBizNo(this.form.id)
+                  .then((res) => {
+                    this.outgoingData = res;
+                  })
+                  .catch((e) => {
+                    // 外发单只是装饰性区块:取不到不能打断批量导出
+                    this.outgoingData = null;
+                    console.warn('加载外发单信息失败', e);
+                  });
+                // 等待审批记录加载完成,确保 generateTasksPrintHtml 有数据
+                await this.loadTasks(this.form.id);
+              }
+              this.jsonData = JSON.parse(this.form.formJson.makingJson);
+              this.jsonData.config.dataSource &&
+                this.jsonData.config.dataSource.forEach((item) => {
+                  item.headers = {
+                    Authorization: getToken()
+                  };
+                });
+              await this.ensureRemoteData(this.jsonData).catch((e) => {
+                console.warn('预加载远程数据失败', e);
+              });
+              htmlList.push(
+                this.generatePrintHtml(
+                  this.jsonData,
+                  this.form.valueJson || {},
+                  this.form
+                )
+              );
+            } catch (e) {
+              // 单条装配失败不打断整批:计入 skipped,由调用方提示
+              failed += 1;
+              console.warn('记录装配失败,已跳过', row && row.id, e);
+            }
+          }
+          const fileName = options.fileName || buildPdfFileName('');
+          const result = await exportHtmlListToPdf(htmlList, fileName, {
+            onProgress: options.onProgress
+          });
+          return {
+            pageCount: result.pageCount,
+            skipped: (result.skipped || 0) + failed
+          };
+        } finally {
+          this.pdfExporting = false;
+        }
+      },
+
     async openPreview() {
       try {
         const making = this.jsonData || (this.form.formJson && JSON.parse(this.form.formJson.makingJson));

+ 414 - 0
src/views/bpm/collaborative/export/pdfExport.js

@@ -0,0 +1,414 @@
+import html2canvas from 'html2canvas';
+import jsPDF from 'jspdf';
+
+/**
+ * 行政审批「导出PDF」渲染工具。
+ * 内容来源固定为 detail.vue 的 generatePrintHtml 输出(与「打印」同源),
+ * 这里只负责把同一份 HTML 渲染成 canvas 再切片落到 PDF 页面上。
+ */
+
+/** A4 纵向在 96dpi 下的尺寸(210mm x 297mm),用于确定渲染宽度与页面高度 */
+export const A4_WIDTH_PX = 793.7;
+export const A4_HEIGHT_PX = 1122.5;
+
+/** PDF 页尺寸用毫米绘制,保证产出标准 A4(210mm x 297mm) */
+const A4_WIDTH_MM = 210;
+const A4_HEIGHT_MM = 297;
+/** CSS px -> mm(96dpi) */
+const PX_TO_MM = 25.4 / 96;
+
+/** canvas 渲染倍数,与 seal.vue 的 html2canvas 用法保持一致 */
+export const RENDER_SCALE = 2;
+
+/** 尾页最小高度:尾页不足时把上一页切分点回退,避免产出近似空白页 */
+export const MIN_PAGE_TAIL_PX = 24;
+
+/** 单页图片导出质量(文本类内容,jpg 高质量已足够清晰且体积可控) */
+const JPEG_QUALITY = 0.95;
+
+const RENDER_HOST_ATTR = 'data-pdf-export-host';
+const IMAGE_WAIT_TIMEOUT = 15000;
+
+function pad2(value) {
+  return value < 10 ? '0' + value : '' + value;
+}
+
+/** yyyyMMddHHmmss,与 export/recordExport.js 的 timestampText 同口径 */
+export function timestampText(date) {
+  const now = date || new Date();
+  return (
+    now.getFullYear() +
+    pad2(now.getMonth() + 1) +
+    pad2(now.getDate()) +
+    pad2(now.getHours()) +
+    pad2(now.getMinutes()) +
+    pad2(now.getSeconds())
+  );
+}
+
+/** 批量文件名:行政审批_{页签}_{yyyyMMddHHmmss}.pdf(沿用 buildExportFileName 口径) */
+export function buildPdfFileName(tabLabel, date) {
+  return (
+    ['行政审批', tabLabel || '全部记录', timestampText(date)].join('_') + '.pdf'
+  );
+}
+
+/** 单条文件名:行政审批_{单据名}_{流水号}_{yyyyMMddHHmmss}.pdf */
+export function buildSinglePdfFileName(docName, serialNo, date) {
+  const head = ['行政审批', docName, serialNo]
+    .map((item) =>
+      item === null || item === undefined ? '' : String(item).trim()
+    )
+    .filter((item) => item !== '');
+  head.push(timestampText(date));
+  return head.join('_') + '.pdf';
+}
+
+/**
+ * 从 generatePrintHtml 的完整 document 中取出 <style> 与 .pf-container,
+ * 正则与 printRows / openPreview 完全一致,保证样式与骨架同源。
+ */
+export function extractPrintParts(fullHtml) {
+  const html =
+    fullHtml === null || fullHtml === undefined ? '' : String(fullHtml);
+  const styleMatch = html.match(/<style>([\s\S]*?)<\/style>/);
+  const containerMatch = html.match(/<div class="pf-container">[\s\S]*<\/div>/);
+  return {
+    style: styleMatch ? styleMatch[1] : '',
+    body: containerMatch ? containerMatch[0] : html
+  };
+}
+
+/**
+ * 把注入样式里会逃出容器的两条选择器限定到宿主容器上:
+ * body{...} -> [data-pdf-export-host]{...},a{...} -> [data-pdf-export-host] a{...}。
+ * .pf-* 与 @media print 规则原样保留;generatePrintHtml 对打印窗口仍是完整
+ * document,不受影响。宿主 div 是 body 的等价物,字体/颜色照常向下继承。
+ */
+export function scopePrintStyle(style) {
+  const scope = '[' + RENDER_HOST_ATTR + ']';
+  return String(style || '')
+    .replace(/(^|\})\s*body\s*\{/g, (whole, head) => head + ' ' + scope + '{')
+    .replace(/(^|\})\s*a\s*\{/g, (whole, head) => head + ' ' + scope + ' a{');
+}
+
+/**
+ * 计算一条记录的分页切片(单位:CSS px,相对容器顶部)。
+ * 只在块级元素的缝隙处切分,避免把一行文字截成两半;
+ * 单个块高于整页时退化为按页高硬切(该块本身无法再拆)。
+ */
+export function computePageSlices(boxes, pageHeight, contentHeight) {
+  const height = Math.max(0, Math.floor(contentHeight || 0));
+  if (!height) return [];
+  const blocks = (boxes || [])
+    .filter(
+      (box) =>
+        box &&
+        typeof box.top === 'number' &&
+        typeof box.height === 'number' &&
+        box.height > 0
+    )
+    .slice()
+    .sort((a, b) => a.top - b.top);
+  if (!pageHeight || pageHeight <= 0) return [{ start: 0, end: height }];
+
+  const slices = [];
+  let cursor = 0;
+  let guard = 0;
+  while (cursor < height && guard < 5000) {
+    guard += 1;
+    const pageEnd = cursor + pageHeight;
+    if (pageEnd >= height) {
+      slices.push({ start: cursor, end: height });
+      break;
+    }
+    let cut = -1;
+    blocks.forEach((box) => {
+      const bottom = box.top + box.height;
+      if (box.top < cursor) return;
+      if (bottom <= pageEnd && bottom > cut) cut = bottom;
+    });
+    // 没有合法的块边界(如超长表格)时按页高硬切,保证仍有推进
+    if (cut <= cursor) cut = pageEnd;
+    const end = Math.min(cut, height);
+    slices.push({ start: cursor, end });
+    cursor = end;
+  }
+  return adjustTailSlice(slices.filter((item) => item.end > item.start));
+}
+
+/** 尾页过矮时把上一页切分点下移,页面总数不变且内容不丢 */
+function adjustTailSlice(slices) {
+  if (slices.length < 2) return slices;
+  const last = slices[slices.length - 1];
+  const tailHeight = last.end - last.start;
+  if (tailHeight >= MIN_PAGE_TAIL_PX) return slices;
+  const prev = slices[slices.length - 2];
+  const need = MIN_PAGE_TAIL_PX - tailHeight;
+  const spare = Math.max(0, prev.end - prev.start - MIN_PAGE_TAIL_PX);
+  const shift = Math.min(need, spare);
+  if (shift > 0) {
+    prev.end -= shift;
+    last.start -= shift;
+  }
+  return slices;
+}
+
+/**
+ * 批量记录的分页计划:每条记录独立切片,切片之间不重叠,
+ * 记录之间天然分页(第一条切片的 start 恒为 0)。
+ */
+export function planRecordPages(records, pageHeight) {
+  return (records || [])
+    .map((record) =>
+      computePageSlices(
+        (record && record.boxes) || [],
+        pageHeight,
+        (record && record.contentHeight) || 0
+      )
+    )
+    .filter((slices) => slices.length > 0);
+}
+
+const HOST_STYLE = [
+  'position:fixed',
+  'left:-100000px',
+  'top:0',
+  'width:' + A4_WIDTH_PX + 'px',
+  'background:#ffffff',
+  'color:#333333',
+  'pointer-events:none',
+  'z-index:-1'
+].join(';');
+
+function createRenderHost() {
+  const host = document.createElement('div');
+  host.setAttribute(RENDER_HOST_ATTR, '');
+  host.style.cssText = HOST_STYLE;
+  document.body.appendChild(host);
+  return host;
+}
+
+function removeNode(node) {
+  try {
+    if (node && node.parentNode) node.parentNode.removeChild(node);
+  } catch (e) {
+    // 清理失败不影响导出结果
+  }
+}
+
+/** 等待容器内图片加载结束,避免 canvas 里缺图 */
+function waitForImages(root) {
+  const images = root
+    ? Array.prototype.slice.call(root.querySelectorAll('img'))
+    : [];
+  return Promise.all(
+    images.map(
+      (img) =>
+        new Promise((resolve) => {
+          if (img.complete) {
+            resolve();
+            return;
+          }
+          let timer = null;
+          const done = () => {
+            if (timer) clearTimeout(timer);
+            img.removeEventListener('load', done);
+            img.removeEventListener('error', done);
+            resolve();
+          };
+          img.addEventListener('load', done);
+          img.addEventListener('error', done);
+          timer = setTimeout(done, IMAGE_WAIT_TIMEOUT);
+        })
+    )
+  );
+}
+
+/** 采集 .pf-container 直属块的行盒,供分页切分使用 */
+export function collectBlockBoxes(container, baseTop) {
+  const boxes = [];
+  if (!container || !container.children) return boxes;
+  Array.prototype.forEach.call(container.children, (el) => {
+    const rect = el.getBoundingClientRect();
+    if (!rect || !rect.height) return;
+    boxes.push({
+      top: Math.round(rect.top - baseTop),
+      height: Math.round(rect.height)
+    });
+  });
+  return boxes;
+}
+
+/** 把切片边界夹到实际 canvas 高度内,防止越界切片 */
+function clampSlices(slices, canvasHeightCss) {
+  return slices
+    .map((slice) => ({
+      start: Math.max(0, Math.min(slice.start, canvasHeightCss)),
+      end: Math.max(0, Math.min(slice.end, canvasHeightCss))
+    }))
+    .filter((slice) => slice.end > slice.start);
+}
+
+/**
+ * 渲染一条记录:注入离屏容器 -> html2canvas -> 按页切片。
+ * 返回的 canvas 与 slices 由调用方负责释放。
+ */
+export async function renderRecordSlices(fullHtml, options = {}) {
+  const scale = options.scale || RENDER_SCALE;
+  const pageHeight = options.pageHeight || A4_HEIGHT_PX;
+  const host = createRenderHost();
+  try {
+    const parts = extractPrintParts(fullHtml);
+    host.innerHTML =
+      (parts.style
+        ? '<style>' + scopePrintStyle(parts.style) + '</style>'
+        : '') + parts.body;
+    if (document.fonts && document.fonts.ready) {
+      try {
+        await document.fonts.ready;
+      } catch (e) {
+        // 字体接口不可用时直接继续
+      }
+    }
+    await waitForImages(host);
+    const container = host.querySelector('.pf-container') || host;
+    const hostRect = host.getBoundingClientRect();
+    const baseTop = hostRect.top;
+    const boxes = collectBlockBoxes(container, baseTop);
+    const width = Math.ceil(hostRect.width) || A4_WIDTH_PX;
+    const contentHeight = Math.ceil(
+      Math.max(host.scrollHeight || 0, hostRect.height || 0)
+    );
+    const slices = computePageSlices(boxes, pageHeight, contentHeight);
+    if (!slices.length) return { canvas: null, slices: [] };
+    const canvas = await html2canvas(host, {
+      scale: scale,
+      backgroundColor: '#ffffff',
+      useCORS: true,
+      allowTaint: false,
+      logging: false,
+      imageTimeout: IMAGE_WAIT_TIMEOUT,
+      windowWidth: Math.max(width, Math.ceil(A4_WIDTH_PX)),
+      windowHeight: Math.max(contentHeight, 1000)
+    });
+    return {
+      canvas: canvas,
+      slices: clampSlices(slices, canvas.height / scale)
+    };
+  } finally {
+    removeNode(host);
+  }
+}
+
+/** 从整条记录的 canvas 上裁出一页,返回 dataURL */
+function sliceToImage(canvas, slice, scale) {
+  const sy = Math.max(0, Math.round(slice.start * scale));
+  const sh = Math.max(1, Math.round((slice.end - slice.start) * scale));
+  const available = Math.max(1, canvas.height - sy);
+  const height = Math.min(sh, available);
+  const temp = document.createElement('canvas');
+  temp.width = canvas.width;
+  temp.height = height;
+  const ctx = temp.getContext('2d');
+  ctx.fillStyle = '#ffffff';
+  ctx.fillRect(0, 0, temp.width, temp.height);
+  ctx.drawImage(
+    canvas,
+    0,
+    sy,
+    canvas.width,
+    height,
+    0,
+    0,
+    canvas.width,
+    height
+  );
+  let dataUrl = '';
+  try {
+    dataUrl = temp.toDataURL('image/jpeg', JPEG_QUALITY);
+  } catch (error) {
+    const tainted = new Error(
+      '导出失败:页面中含有跨域图片,画布被污染,无法生成 PDF'
+    );
+    tainted.code = 'TAINTED_CANVAS';
+    tainted.cause = error;
+    throw tainted;
+  }
+  temp.width = 0;
+  temp.height = 0;
+  return dataUrl;
+}
+
+function releaseCanvas(canvas) {
+  try {
+    if (canvas) {
+      canvas.width = 0;
+      canvas.height = 0;
+    }
+  } catch (e) {
+    // 释放失败无副作用
+  }
+}
+
+/**
+ * 主入口:把 N 份打印 HTML 合成 1 个 PDF。
+ * 每条记录从新的一页开始,单条记录超长时按块边界续页,不丢内容。
+ */
+export async function exportHtmlListToPdf(htmlList, fileName, options = {}) {
+  const list = (Array.isArray(htmlList) ? htmlList : [htmlList]).filter(
+    (item) => item !== null && item !== undefined && String(item) !== ''
+  );
+  if (!list.length) throw new Error('没有可导出的内容');
+  const scale = options.scale || RENDER_SCALE;
+  const sliceHeight = options.pageHeight || A4_HEIGHT_PX;
+  let pdf = null;
+  let pageCount = 0;
+  let skipped = 0;
+  for (let i = 0; i < list.length; i += 1) {
+    const rendered = await renderRecordSlices(list[i], {
+      scale: scale,
+      pageHeight: sliceHeight
+    });
+    const canvas = rendered.canvas;
+    const slices = rendered.slices || [];
+    if (!canvas || !slices.length) {
+      // 该条无内容:跳过并计数,由调用方提示,不能报「全部导出成功」
+      releaseCanvas(canvas);
+      skipped += 1;
+      continue;
+    }
+    try {
+      slices.forEach((slice) => {
+        const image = sliceToImage(canvas, slice, scale);
+        if (!pdf) {
+          pdf = new jsPDF({
+            orientation: 'portrait',
+            unit: 'mm',
+            format: [A4_WIDTH_MM, A4_HEIGHT_MM],
+            compress: true
+          });
+        } else {
+          pdf.addPage();
+        }
+        pdf.addImage(
+          image,
+          'JPEG',
+          0,
+          0,
+          A4_WIDTH_MM,
+          Math.min(slice.end - slice.start, sliceHeight) * PX_TO_MM
+        );
+        pageCount += 1;
+      });
+    } finally {
+      releaseCanvas(canvas);
+    }
+    if (typeof options.onProgress === 'function') {
+      options.onProgress(i + 1, list.length);
+    }
+  }
+  if (!pdf || !pageCount) throw new Error('没有可导出的内容');
+  pdf.save(fileName || buildPdfFileName(''));
+  return { pageCount: pageCount, skipped: skipped };
+}

+ 42 - 0
src/views/bpm/collaborative/index.vue

@@ -202,6 +202,15 @@
                 >
                   导出
                 </el-button>
+                <el-button
+                  type="primary"
+                  class="el-icon-document"
+                  size="small"
+                  :loading="pdfExportLoading"
+                  @click="handleExportPdf"
+                >
+                  导出PDF
+                </el-button>
               </template>
               <template v-slot:formName="{ row }">
                 <el-link
@@ -360,6 +369,7 @@
     mapListRecord,
     writeWorkbook
   } from './export/recordExport';
+  import { buildPdfFileName } from './export/pdfExport';
   import BLANK_TABLE_HEADERS from '@/BIZComponents/processSubmitDialog/components/blank_table_headers.json';
 
   // 默认表单数据
@@ -397,6 +407,7 @@
         createTime1: [],
         selection: [],
         exportLoading: false,
+        pdfExportLoading: false,
         // 个人 / 部门 / 通知我的
         activeName: 'user',
         columnsVersion: 1,
@@ -834,6 +845,37 @@
         }
         this.$refs.printService.printRows(this.selection);
       },
+      /* 勾选记录批量导出 PDF:复用 detail 组件的 exportPdfRows(与打印同源) */
+      async handleExportPdf() {
+        if (this.pdfExportLoading) return;
+        if (!this.selection || this.selection.length === 0) {
+          this.$message.warning('请先勾选需要导出的记录');
+          return;
+        }
+        const service = this.$refs.printService;
+        if (!service || typeof service.exportPdfRows !== 'function') {
+          this.$message.error('导出组件未就绪');
+          return;
+        }
+        this.pdfExportLoading = true;
+        try {
+          const result = await service.exportPdfRows(this.selection, {
+            fileName: buildPdfFileName(this.currentTabLabel)
+          });
+          if (result && result.skipped > 0) {
+            this.$message.warning(
+              '有 ' + result.skipped + ' 条记录没有可导出的内容,已跳过'
+            );
+          } else {
+            this.$message.success('导出PDF成功');
+          }
+        } catch (e) {
+          console.error('导出PDF失败', e);
+          this.$message.error(e && e.message ? e.message : '导出PDF失败');
+        } finally {
+          this.pdfExportLoading = false;
+        }
+      },
       /* 导出取数:复用当前页签的列表接口与筛选条件 */
       requestPage(pageNo, pageSize) {
         let [createTimeBegin, createTimeEnd] = this.createTime1 || [];