|
|
@@ -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 };
|
|
|
+}
|