找回密码
 立即注册
首页 业界区 业界 使用 html2canvas + jsPDF 生成PDF 的简单示例(含文字 ...

使用 html2canvas + jsPDF 生成PDF 的简单示例(含文字下沉修复)

东新 2025-11-25 17:00:08
在前端项目中,尤其是后台管理系统、发票/报告导出、在线编辑器、前端页面截图导出等场景,将页面内容导出为 PDF 是非常常见的需求。现在使用 html2canvas + jsPDF 进行构建 hooks 作为示例。
一、为什么需要自定义封装?

自个实现全局 hooks 可控,想怎么来就怎么来(参考 html2pdf.js)。
直接使用 html2canvas 和 jsPDF 通常会遇到:

  • 内容被截断 / 超出容器
  • 内容生成不居中
  • 图片跨域污染导致失败
  • Tailwind/UnoCSS 的样式与 html2canvas 不兼容
  • PDF 页面分页不正确
  • 文字渲染模糊
  • 文字下沉(文本 baseline 问题)
要做到尽可能无损的渲染,需要:

  • 克隆 DOM,在单独容器中渲染(目前使用这个方法实现内容不居中问题)
  • 处理 position/overflow/scroll 等不兼容属性
  • 修复不支持的 CSS 颜色函数(oklab/oklch 等)
  • 手动分页 + 图片等比缩放
  • 覆盖一些框架默认样式(如 img display)
二、核心导出功能实现

以下代码实现了完整的导出流程:

  • 自动加载 html2canvas / jsPDF
  • DOM 克隆渲染
  • Canvas 控制切分页
  • PDF 导出或预览
  • 进度回调
代码较长,这里展示关键核心结构:
  1. export function useHtml2Pdf() {
  2.   const exporting = ref(false);
  3.   const progress = ref(0);
  4.   const previewImages = ref<string[]>([]);
  5.   // 加载库
  6.   const loadLibraries = async () => { ... }
  7.   // DOM → Canvas
  8.   const renderToCanvas = async () => { ... }
  9.   // Canvas → PDF
  10.   const splitCanvasToPdf = () => { ... }
  11.   // 导出与预览
  12.   const exportPdf = async () => { ... }
  13.   const previewPdf = async () => { ... }
  14.   return { exporting, progress, previewImages, exportPdf, previewPdf };
  15. }
复制代码
完整代码已在文章结尾处附带(代码以及实现就不详细解读了)。
三、为什么会出现“文字下沉”?

这是使用 html2canvas 时 最常见也是最诡异的 bug 之一

  • 同一行文字字体不同
  • 图片与文字混合排版
  • Tailwind / UnoCSS 的 baseline 设置
  • img 默认为 display: inline 或 inline-block
  • html2canvas 会根据 CSS 计算内容 baseline,高度计算错误
具体表现:

  • 文字被向下“压”了一点点,与真实页面不一致
  • 某些容器中的文本垂直位置偏离
根本原因

UnoCSS / Tailwind 默认对 img 设置为:
  1. display: inline;
  2. vertical-align: middle;
复制代码
导致 html2canvas 在计算行内盒高度时:

  • 文字基线被迫下移
  • 图片对齐方式干扰文本
html2canvas 本身对 inline-level box 的计算就比较脆弱,因此这个默认样式会破坏它的内部排版逻辑。
四、一行 CSS 解决文字下沉问题

解决方案:强制 img 不参与 inline 排版
  1. img {
  2.   display: inline-block !important;
  3. }
复制代码
为什么这行能解决?


  • inline-block 会创建自己的盒模型,不再参与行内 baseline 对齐。
  • html2canvas 计算布局时,不需要处理 inline-level baseline,从而避免错位。
  • 避免 Tailwind/UnoCSS 默认的 vertical-align: middle 影响布局高度。
这是经过大量社区使用、实测最稳定的解决方案。
注意:这种 bug 仅在截屏(html2canvas)时出现,真实 DOM 渲染正常。
五、完整代码
  1. import { ref, onMounted, type Ref } from 'vue';
  2. /**
  3. * html2canvas 配置选项
  4. */
  5. export interface Html2CanvasOptions {
  6.   scale?: number; // 清晰度倍数,默认使用 devicePixelRatio * 1.5
  7.   useCORS?: boolean; // 是否使用 CORS
  8.   allowTaint?: boolean; // 是否允许跨域图片污染 canvas
  9.   backgroundColor?: string; // 背景色
  10.   logging?: boolean; // 是否启用日志
  11.   width?: number; // 宽度
  12.   height?: number; // 高度
  13.   windowWidth?: number; // 窗口宽度
  14.   windowHeight?: number; // 窗口高度
  15.   x?: number; // X 偏移
  16.   y?: number; // Y 偏移
  17.   scrollX?: number; // X 滚动
  18.   scrollY?: number; // Y 滚动
  19.   onclone?: (clonedDoc: Document, clonedElement: HTMLElement) => void; // 克隆回调
  20. }
  21. /**
  22. * 图片质量配置
  23. */
  24. export interface ImageOptions {
  25.   type?: 'png' | 'jpeg' | 'webp'; // 图片类型
  26.   quality?: number; // 图片质量 0-1,仅对 jpeg/webp 有效
  27. }
  28. /**
  29. * 页面分页配置
  30. */
  31. export interface PagebreakOptions {
  32.   mode?: ('avoid-all' | 'css' | 'legacy')[]; // 分页模式
  33.   before?: string | string[]; // 在此元素前分页
  34.   after?: string | string[]; // 在此元素后分页
  35.   avoid?: string | string[]; // 避免在此元素处分页
  36.   enabled?: boolean; // 是否启用自动分页,默认true
  37.   avoidSinglePage?: boolean; // 是否避免单页内容强制分页,默认true
  38. }
  39. /**
  40. * PDF 页面格式类型
  41. */
  42. export type PdfFormat =
  43.   | 'a0' | 'a1' | 'a2' | 'a3' | 'a4' | 'a5' | 'a6' | 'a7' | 'a8' | 'a9' | 'a10'
  44.   | 'b0' | 'b1' | 'b2' | 'b3' | 'b4' | 'b5' | 'b6' | 'b7' | 'b8' | 'b9' | 'b10'
  45.   | 'c0' | 'c1' | 'c2' | 'c3' | 'c4' | 'c5' | 'c6' | 'c7' | 'c8' | 'c9' | 'c10'
  46.   | 'dl' | 'letter' | 'government-letter' | 'legal' | 'junior-legal'
  47.   | 'ledger' | 'tabloid' | 'credit-card'
  48.   | [number, number]; // 自定义尺寸 [width, height] in mm
  49. /**
  50. * PDF 导出配置选项
  51. */
  52. export interface Html2PdfOptions {
  53.   fileName?: string; // 文件名
  54.   scale?: number; // 清晰度倍数,默认使用 devicePixelRatio * 1.5
  55.   padding?: number; // 页面内边距 (mm)
  56.   format?: PdfFormat; // PDF格式,默认为 'a4'
  57.   orientation?: 'portrait' | 'landscape'; // 方向
  58.   align?: 'left' | 'center' | 'right'; // 内容对齐方式
  59.   image?: ImageOptions; // 图片配置
  60.   html2canvas?: Partial<Html2CanvasOptions>; // html2canvas 配置
  61.   pagebreak?: PagebreakOptions; // 分页配置
  62.   onProgress?: (progress: number) => void; // 进度回调 0-100
  63. }
  64. /**
  65. * 返回值类型
  66. */
  67. export interface UseHtml2PdfReturn {
  68.   exporting: Ref<boolean>;
  69.   progress: Ref<number>; // 进度 0-100
  70.   previewImages: Ref<string[]>; // 预览图片数组
  71.   exportPdf: (
  72.     element: HTMLElement | string | null,
  73.     options?: Html2PdfOptions
  74.   ) => Promise<void>;
  75.   previewPdf: (
  76.     element: HTMLElement | string | null,
  77.     options?: Html2PdfOptions
  78.   ) => Promise<void>;
  79. }
  80. /**
  81. * 使用 html2canvas + jsPDF 生成 PDF
  82. * 适配 Vue 3 + Nuxt.js 3
  83. */
  84. export function useHtml2Pdf(): UseHtml2PdfReturn {
  85.   const exporting = ref(false);
  86.   const progress = ref(0);
  87.   const previewImages = ref<string[]>([]);
  88.   const { $message } = useNuxtApp();
  89.   // 库实例
  90.   let html2canvas: any = null;
  91.   let jsPDF: any = null;
  92.   // 库加载状态
  93.   let librariesLoading: Promise<void> | null = null;
  94.   /**
  95.    * 加载必要的库
  96.    */
  97.   const loadLibraries = async (): Promise<void> => {
  98.     if (librariesLoading) {
  99.       return librariesLoading;
  100.     }
  101.     librariesLoading = (async () => {
  102.       try {
  103.         const [html2canvasModule, jsPDFModule] = await Promise.all([
  104.           import('html2canvas'),
  105.           import('jspdf'),
  106.         ]);
  107.         html2canvas = html2canvasModule.default || html2canvasModule;
  108.         jsPDF = (jsPDFModule as any).jsPDF;
  109.       } catch (error) {
  110.         console.error('PDF 库加载失败:', error);
  111.         throw error;
  112.       }
  113.     })();
  114.     return librariesLoading;
  115.   };
  116.   // 在客户端预加载库
  117.   if (process.client) {
  118.     onMounted(() => {
  119.       loadLibraries().catch((error) => {
  120.         console.error('预加载 PDF 库失败:', error);
  121.       });
  122.     });
  123.   }
  124.   /**
  125.    * 更新进度
  126.    */
  127.   const updateProgress = (value: number, callback?: (progress: number) => void): void => {
  128.     progress.value = Math.min(100, Math.max(0, value));
  129.     if (callback) {
  130.       callback(progress.value);
  131.     }
  132.   };
  133.   /**
  134.    * 获取目标元素
  135.    */
  136.   const getElement = (element: HTMLElement | string | null): HTMLElement | null => {
  137.     if (!element || process.server) return null;
  138.     if (typeof element === 'string') {
  139.       return document.querySelector(element) as HTMLElement;
  140.     }
  141.     return element;
  142.   };
  143.   /**
  144.    * 保存和恢复元素样式
  145.    */
  146.   interface StyleState {
  147.     overflow: string;
  148.     maxHeight: string;
  149.     height: string;
  150.     scrollTop: number;
  151.     scrollLeft: number;
  152.     bodyOverflow: string;
  153.     bodyScrollTop: number;
  154.   }
  155.   const saveStyles = (element: HTMLElement): StyleState => {
  156.     return {
  157.       overflow: element.style.overflow,
  158.       maxHeight: element.style.maxHeight,
  159.       height: element.style.height,
  160.       scrollTop: element.scrollTop,
  161.       scrollLeft: element.scrollLeft,
  162.       bodyOverflow: document.body.style.overflow,
  163.       bodyScrollTop: window.scrollY,
  164.     };
  165.   };
  166.   const applyCaptureStyles = (element: HTMLElement): void => {
  167.     element.style.overflow = 'visible';
  168.     element.style.maxHeight = 'none';
  169.     element.style.height = 'auto';
  170.     document.body.style.overflow = 'hidden';
  171.     element.scrollTop = 0;
  172.     element.scrollLeft = 0;
  173.     window.scrollTo(0, 0);
  174.   };
  175.   const restoreStyles = (element: HTMLElement, state: StyleState): void => {
  176.     element.style.overflow = state.overflow;
  177.     element.style.maxHeight = state.maxHeight;
  178.     element.style.height = state.height;
  179.     element.scrollTop = state.scrollTop;
  180.     element.scrollLeft = state.scrollLeft;
  181.     document.body.style.overflow = state.bodyOverflow;
  182.     window.scrollTo(0, state.bodyScrollTop);
  183.   };
  184.   /**
  185.    * 修复不支持的 CSS 颜色函数
  186.    */
  187.   const fixUnsupportedColors = (clonedDoc: Document, originalElement: HTMLElement): void => {
  188.     clonedDoc.body.style.backgroundColor = '#ffffff';
  189.     clonedDoc.body.style.margin = '0';
  190.     clonedDoc.body.style.padding = '0';
  191.     const allElements = clonedDoc.querySelectorAll('*');
  192.     const colorProperties = [
  193.       'color',
  194.       'background-color',
  195.       'background',
  196.       'border-color',
  197.       'border-top-color',
  198.       'border-right-color',
  199.       'border-bottom-color',
  200.       'border-left-color',
  201.       'outline-color',
  202.       'box-shadow',
  203.       'text-shadow',
  204.     ];
  205.     allElements.forEach((el, index) => {
  206.       if (el instanceof HTMLElement) {
  207.         // 尝试从原始文档找到对应元素
  208.         let originalEl: HTMLElement | null = null;
  209.         if (originalElement) {
  210.           const originalAll = originalElement.querySelectorAll('*');
  211.           if (originalAll[index]) {
  212.             originalEl = originalAll[index] as HTMLElement;
  213.           }
  214.         }
  215.         const targetEl = originalEl || el;
  216.         try {
  217.           const computedStyle = window.getComputedStyle(targetEl, null);
  218.           colorProperties.forEach((prop) => {
  219.             try {
  220.               const computedValue = computedStyle.getPropertyValue(prop);
  221.               const styleValue = targetEl.style.getPropertyValue(prop);
  222.               if (
  223.                 (styleValue && (
  224.                   styleValue.includes('oklab') ||
  225.                   styleValue.includes('oklch') ||
  226.                   styleValue.includes('lab(') ||
  227.                   styleValue.includes('lch(')
  228.                 )) ||
  229.                 (computedValue && (
  230.                   computedValue.includes('oklab') ||
  231.                   computedValue.includes('oklch')
  232.                 ))
  233.               ) {
  234.                 if (computedValue && (computedValue.includes('rgb') || computedValue.includes('#'))) {
  235.                   el.style.setProperty(prop, computedValue, 'important');
  236.                 } else if (prop.includes('shadow')) {
  237.                   el.style.setProperty(prop, 'none', 'important');
  238.                 } else {
  239.                   el.style.removeProperty(prop);
  240.                 }
  241.               }
  242.             } catch (e) {
  243.               // 忽略单个属性的错误
  244.             }
  245.           });
  246.         } catch (e) {
  247.           // 如果无法获取计算样式,跳过该元素
  248.         }
  249.       }
  250.     });
  251.     if (originalElement) {
  252.       (originalElement as HTMLElement).style.position = 'relative';
  253.       (originalElement as HTMLElement).style.width = 'auto';
  254.       (originalElement as HTMLElement).style.height = 'auto';
  255.     }
  256.   };
  257.   /**
  258.    * 创建渲染容器
  259.    */
  260.   const createRenderContainer = (sourceElement: HTMLElement): { overlay: HTMLElement; container: HTMLElement; cleanup: () => void } => {
  261.     // 创建 overlay 容器样式
  262.     const overlayCSS = {
  263.       position: 'fixed',
  264.       overflow: 'hidden',
  265.       zIndex: 1000,
  266.       left: 0,
  267.       right: 0,
  268.       bottom: 0,
  269.       top: 0,
  270.       backgroundColor: 'rgba(0,0,0,0.8)',
  271.       opacity: 0
  272.     };
  273.     // 创建内容容器样式
  274.     const containerCSS = {
  275.       position: 'absolute',
  276.       width: 'auto',
  277.       left: 0,
  278.       right: 0,
  279.       top: 0,
  280.       height: 'auto',
  281.       margin: 'auto',
  282.       backgroundColor: 'white'
  283.     };
  284.     // 创建 overlay 容器
  285.     const overlay = document.createElement('div');
  286.     overlay.className = 'html2pdf__overlay';
  287.     Object.assign(overlay.style, overlayCSS);
  288.     // 创建内容容器
  289.     const container = document.createElement('div');
  290.     container.className = 'html2pdf__container';
  291.     Object.assign(container.style, containerCSS);
  292.     // 克隆源元素并添加到容器中
  293.     const clonedElement = sourceElement.cloneNode(true) as HTMLElement;
  294.     container.appendChild(clonedElement);
  295.     overlay.appendChild(container);
  296.     document.body.appendChild(overlay);
  297.     // 清理函数
  298.     const cleanup = () => {
  299.       if (document.body.contains(overlay)) {
  300.         document.body.removeChild(overlay);
  301.       }
  302.     };
  303.     return { overlay, container, cleanup };
  304.   };
  305.   /**
  306.    * 渲染 DOM -> Canvas
  307.    */
  308.   const renderToCanvas = async (
  309.     element: HTMLElement,
  310.     options?: {
  311.       scale?: number;
  312.       html2canvas?: Partial<Html2CanvasOptions>;
  313.       onProgress?: (progress: number) => void;
  314.     }
  315.   ): Promise<HTMLCanvasElement> => {
  316.     // 确保库已加载
  317.     await loadLibraries();
  318.     if (!html2canvas) {
  319.       throw new Error('html2canvas 未加载');
  320.     }
  321.     const {
  322.       scale: customScale,
  323.       html2canvas: html2canvasOptions = {},
  324.       onProgress: progressCallback,
  325.     } = options || {};
  326.     const defaultScale = (window.devicePixelRatio || 1) * 1.5;
  327.     const finalScale = customScale ?? html2canvasOptions.scale ?? defaultScale;
  328.     const fullWidth = element.scrollWidth || html2canvasOptions.width || element.offsetWidth;
  329.     const fullHeight = element.scrollHeight || html2canvasOptions.height || element.offsetHeight;
  330.     // 保存样式
  331.     const styleState = saveStyles(element);
  332.     applyCaptureStyles(element);
  333.     // 创建渲染容器
  334.     const { container, cleanup } = createRenderContainer(element);
  335.     const clonedElement = container.firstElementChild as HTMLElement;
  336.     // 等待布局稳定
  337.     await new Promise((resolve) => {
  338.       requestAnimationFrame(() => {
  339.         requestAnimationFrame(resolve);
  340.       });
  341.     });
  342.     updateProgress(10, progressCallback);
  343.     try {
  344.       // 合并默认配置和自定义配置
  345.       const canvasOptions = {
  346.         scale: finalScale,
  347.         useCORS: true,
  348.         allowTaint: false,
  349.         logging: false,
  350.         backgroundColor: '#ffffff',
  351.         width: fullWidth,
  352.         height: fullHeight,
  353.         windowWidth: fullWidth,
  354.         windowHeight: fullHeight,
  355.         x: 0,
  356.         y: 0,
  357.         scrollX: 0,
  358.         scrollY: 0,
  359.         ...html2canvasOptions,
  360.         onclone: (clonedDoc: Document, clonedElementFromCanvas: HTMLElement) => {
  361.           fixUnsupportedColors(clonedDoc, element);
  362.           // 执行用户自定义的 onclone 回调
  363.           if (html2canvasOptions.onclone) {
  364.             html2canvasOptions.onclone(clonedDoc, clonedElementFromCanvas);
  365.           }
  366.         },
  367.       };
  368.       updateProgress(20, progressCallback);
  369.       // 使用克隆的元素进行渲染
  370.       const canvas = await html2canvas(clonedElement, canvasOptions);
  371.       updateProgress(50, progressCallback);
  372.       return canvas;
  373.     } finally {
  374.       // 清理容器
  375.       cleanup();
  376.       // 恢复样式
  377.       restoreStyles(element, styleState);
  378.     }
  379.   };
  380.   /**
  381.    * 获取页面尺寸配置(单位:mm)
  382.    * 参考 jsPDF 的页面尺寸定义,使用精确的 pt 到 mm 转换
  383.    */
  384.   const getPageSizes = (
  385.     format: PdfFormat,
  386.     orientation: 'portrait' | 'landscape' = 'portrait'
  387.   ): { width: number; height: number } => {
  388.     // 如果是自定义数组格式 [width, height]
  389.     if (Array.isArray(format)) {
  390.       return { width: format[0], height: format[1] };
  391.     }
  392.     // pt 到 mm 的转换因子:1 pt = 72/25.4 mm
  393.     const k = 72 / 25.4;
  394.     // 所有页面格式的尺寸(单位:pt)
  395.     // 参考 jsPDF 的页面格式定义
  396.     const pageFormatsPt: Record<string, [number, number]> = {
  397.       // A 系列
  398.       a0: [2383.94, 3370.39],
  399.       a1: [1683.78, 2383.94],
  400.       a2: [1190.55, 1683.78],
  401.       a3: [841.89, 1190.55],
  402.       a4: [595.28, 841.89],
  403.       a5: [419.53, 595.28],
  404.       a6: [297.64, 419.53],
  405.       a7: [209.76, 297.64],
  406.       a8: [147.40, 209.76],
  407.       a9: [104.88, 147.40],
  408.       a10: [73.70, 104.88],
  409.       
  410.       // B 系列
  411.       b0: [2834.65, 4008.19],
  412.       b1: [2004.09, 2834.65],
  413.       b2: [1417.32, 2004.09],
  414.       b3: [1000.63, 1417.32],
  415.       b4: [708.66, 1000.63],
  416.       b5: [498.90, 708.66],
  417.       b6: [354.33, 498.90],
  418.       b7: [249.45, 354.33],
  419.       b8: [175.75, 249.45],
  420.       b9: [124.72, 175.75],
  421.       b10: [87.87, 124.72],
  422.       
  423.       // C 系列
  424.       c0: [2599.37, 3676.54],
  425.       c1: [1836.85, 2599.37],
  426.       c2: [1298.27, 1836.85],
  427.       c3: [918.43, 1298.27],
  428.       c4: [649.13, 918.43],
  429.       c5: [459.21, 649.13],
  430.       c6: [323.15, 459.21],
  431.       c7: [229.61, 323.15],
  432.       c8: [161.57, 229.61],
  433.       c9: [113.39, 161.57],
  434.       c10: [79.37, 113.39],
  435.       
  436.       // 其他格式
  437.       dl: [311.81, 623.62],
  438.       letter: [612, 792],
  439.       'government-letter': [576, 756],
  440.       legal: [612, 1008],
  441.       'junior-legal': [576, 360],
  442.       ledger: [1224, 792],
  443.       tabloid: [792, 1224],
  444.       'credit-card': [153, 243],
  445.     };
  446.     const formatLower = format.toLowerCase();
  447.     let pageSize: [number, number];
  448.     if (pageFormatsPt.hasOwnProperty(formatLower)) {
  449.       pageSize = pageFormatsPt[formatLower];
  450.     } else {
  451.       // 默认使用 A4
  452.       pageSize = pageFormatsPt.a4;
  453.       console.warn(`未识别的页面格式 "${format}",使用默认格式 A4`);
  454.     }
  455.     // 转换为 mm
  456.     let width = pageSize[0] / k;
  457.     let height = pageSize[1] / k;
  458.     // 处理方向
  459.     if (orientation === 'portrait') {
  460.       // 纵向:确保宽度 < 高度
  461.       if (width > height) {
  462.         [width, height] = [height, width];
  463.       }
  464.     } else if (orientation === 'landscape') {
  465.       // 横向:确保宽度 > 高度
  466.       if (height > width) {
  467.         [width, height] = [height, width];
  468.       }
  469.     }
  470.     return { width, height };
  471.   };
  472.   /**
  473.    * 将 Canvas 切分页、生成 PDF
  474.    */
  475.   const splitCanvasToPdf = (
  476.     canvas: HTMLCanvasElement,
  477.     options: {
  478.       format: PdfFormat;
  479.       orientation: 'portrait' | 'landscape';
  480.       padding: number;
  481.       fileName: string;
  482.       align?: 'left' | 'center' | 'right';
  483.       image?: ImageOptions;
  484.       pagebreak?: PagebreakOptions;
  485.       onProgress?: (progress: number) => void;
  486.     },
  487.     doDownload = false
  488.   ): { pdf: any; images: string[] } => {
  489.     if (!jsPDF) {
  490.       throw new Error('jsPDF 未加载');
  491.     }
  492.     const {
  493.       format,
  494.       orientation,
  495.       padding,
  496.       fileName,
  497.       align = 'center',
  498.       image = { type: 'jpeg', quality: 0.95 },
  499.       pagebreak = { enabled: false, avoidSinglePage: true },
  500.       onProgress: progressCallback,
  501.     } = options;
  502.     // 获取页面尺寸
  503.     const pageSize = getPageSizes(format, orientation);
  504.    
  505.     // 对于自定义尺寸(数组格式),需要特殊处理
  506.     // jsPDF 构造函数格式:new jsPDF(orientation, unit, format)
  507.     // 如果 format 是数组 [width, height],则作为自定义尺寸传递
  508.     const pdfFormat: string | [number, number] = Array.isArray(format)
  509.       ? format
  510.       : format;
  511.    
  512.     const pdf = new jsPDF(orientation, 'mm', pdfFormat);
  513.     const pageWidth = pageSize.width;
  514.     const pageHeight = pageSize.height;
  515.    
  516.     // margin = [top, left, bottom, right]
  517.     // 这里 padding 相当于左右边距(当四边相等时)
  518.     // 支持独立设置四个方向的边距,默认只设置一个值
  519.     const marginTop = padding;
  520.     const marginLeft = padding;
  521.     const marginBottom = padding;
  522.     const marginRight = padding;
  523.    
  524.     // 可用内容区域(考虑边距)
  525.     const innerWidth = pageWidth - marginLeft - marginRight;
  526.     const innerHeight = pageHeight - marginTop - marginBottom;
  527.     // 计算图片尺寸,保持宽高比
  528.     // 先计算基于可用区域的宽度和高度的比例,看哪个更限制
  529.     const widthRatio = innerWidth / canvas.width;
  530.     const heightRatio = innerHeight / canvas.height;
  531.     const scaleRatio = Math.min(widthRatio, heightRatio);
  532.     // 图片在 PDF 中的尺寸
  533.     let imgWidth: number;
  534.     let imgHeight: number;
  535.     // 图片尺寸基于可用区域和内容比例
  536.     imgWidth = canvas.width * scaleRatio;
  537.     imgHeight = canvas.height * scaleRatio;
  538.     // 确保图片不超过可用区域
  539.     if (imgWidth > innerWidth) {
  540.       imgWidth = innerWidth;
  541.       imgHeight = (canvas.height / canvas.width) * innerWidth;
  542.     }
  543.     if (imgHeight > innerHeight) {
  544.       imgHeight = innerHeight;
  545.       imgWidth = (canvas.width / canvas.height) * innerHeight;
  546.     }
  547.     // 计算PDF页面在canvas像素坐标系中的高度
  548.     // 1mm = (canvas像素 / PDF尺寸mm) 的比例
  549.     let pxPageHeight: number;
  550.     if(pagebreak.enabled) {
  551.       const pxPerMm = canvas.width / (pageSize.width - marginLeft - marginRight);
  552.       pxPageHeight = Math.floor(innerHeight * pxPerMm);
  553.     } else {
  554.       pxPageHeight = Math.floor(canvas.width * (imgHeight / imgWidth));
  555.     }
  556.     // 计算水平位置
  557.     let xPosition: number;
  558.     switch (align) {
  559.       case 'left':
  560.         // 左对齐:从左边距开始
  561.         xPosition = marginLeft;
  562.         break;
  563.       case 'right':
  564.         // 右对齐:从右边距开始计算,确保图片在右边
  565.         xPosition = pageWidth - marginRight - imgWidth;
  566.         break;
  567.       case 'center':
  568.       default:
  569.         // 居中:计算居中位置
  570.         xPosition = marginLeft + (innerWidth - imgWidth) / 2;
  571.         break;
  572.     }
  573.     // 确定图片类型和质量
  574.     const imageType = image.type || 'jpeg';
  575.     const imageQuality = image.quality ?? (imageType === 'png' ? undefined : 0.95);
  576.     const pdfImageFormat = imageType === 'png' ? 'PNG' : 'JPEG';
  577.     // 确保图片质量在有效范围内
  578.     const finalQuality = imageQuality !== undefined
  579.       ? Math.max(0, Math.min(1, imageQuality))
  580.       : undefined;
  581.     const images: string[] = [];
  582.     // 根据配置决定是否分页
  583.     const pxFullHeight = canvas.height;
  584.     let nPages = 1;
  585.     if (pagebreak.enabled) {
  586.       // 计算需要的页数
  587.       const calculatedPages = Math.ceil(pxFullHeight / pxPageHeight);
  588.       // 如果避免单页强制分页,且内容不超过一页,则不分页
  589.       if (pagebreak.avoidSinglePage && calculatedPages === 1) {
  590.         nPages = 1;
  591.       } else {
  592.         nPages = calculatedPages;
  593.       }
  594.     } else {
  595.       nPages = Math.ceil(pxFullHeight / pxPageHeight);;
  596.     }
  597.     // 估算总页数用于进度计算
  598.     const estimatedTotalPages = nPages;
  599.     // 创建页面 canvas
  600.     const pageCanvas = document.createElement('canvas');
  601.     const pageCtx = pageCanvas.getContext('2d');
  602.     if (!pageCtx) {
  603.       throw new Error('无法创建 Canvas 上下文');
  604.     }
  605.    
  606.     pageCanvas.width = canvas.width;
  607.     pageCanvas.height = pxPageHeight;
  608.     // 分页处理
  609.     for (let page = 0; page < nPages; page++) {
  610.       // 最后一页可能需要调整高度
  611.       let currentPxPageHeight = pxPageHeight;
  612.       let currentPageHeight = innerHeight;
  613.       
  614.       if (page === nPages - 1 && pxFullHeight % pxPageHeight !== 0) {
  615.         // 最后一页:使用剩余高度
  616.         currentPxPageHeight = pxFullHeight % pxPageHeight;
  617.         currentPageHeight = (currentPxPageHeight / canvas.width) * innerWidth;
  618.         pageCanvas.height = currentPxPageHeight;
  619.       }
  620.       // 清空并绘制当前页的内容
  621.       pageCtx.fillStyle = 'white';
  622.       pageCtx.fillRect(0, 0, pageCanvas.width, currentPxPageHeight);
  623.       
  624.       pageCtx.drawImage(
  625.         canvas,
  626.         0,
  627.         page * pxPageHeight,
  628.         pageCanvas.width,
  629.         currentPxPageHeight,
  630.         0,
  631.         0,
  632.         pageCanvas.width,
  633.         currentPxPageHeight
  634.       );
  635.       const sourceHeight = (currentPageHeight / imgHeight) * canvas.height;
  636.       // 根据配置生成图片数据
  637.       const mimeType = `image/${imageType}`;
  638.       const pageImgData = finalQuality !== undefined
  639.         ? pageCanvas.toDataURL(mimeType, finalQuality)
  640.         : pageCanvas.toDataURL(mimeType);
  641.       // 添加新页(除了第一页)
  642.       if (page > 0) {
  643.         pdf.addPage();
  644.       }
  645.       // 添加图片到 PDF(x = marginLeft, y = marginTop)
  646.       pdf.addImage(
  647.         pageImgData,
  648.         pdfImageFormat,
  649.         xPosition,
  650.         marginTop,
  651.         imgWidth,
  652.         currentPageHeight
  653.       );
  654.       if (!doDownload) {
  655.         images.push(pageImgData);
  656.       }
  657.       // 更新进度 (50-90%)
  658.       if (progressCallback && estimatedTotalPages > 0) {
  659.         const pageProgress = 50 + ((page + 1) / estimatedTotalPages) * 40;
  660.         updateProgress(pageProgress, progressCallback);
  661.       }
  662.     }
  663.     updateProgress(95, progressCallback);
  664.     if (doDownload) {
  665.       pdf.save(fileName);
  666.       updateProgress(100, progressCallback);
  667.     }
  668.     return { pdf, images };
  669.   };
  670.   /**
  671.    * 导出 PDF
  672.    * @param element 需要导出的 DOM 元素或选择器
  673.    * @param options 配置项
  674.    */
  675.   const exportPdf = async (
  676.     element: HTMLElement | string | null,
  677.     options?: Html2PdfOptions
  678.   ): Promise<void> => {
  679.     // 服务端检查
  680.     if (process.server) {
  681.       if ($message) $message.error('PDF生成功能仅在客户端可用');
  682.       return;
  683.     }
  684.     const targetElement = getElement(element);
  685.     if (!targetElement) {
  686.       if ($message) $message.error('未找到要导出的 DOM 元素');
  687.       return;
  688.     }
  689.     const {
  690.       fileName = 'document.pdf',
  691.       scale,
  692.       padding = 0,
  693.       format = 'a4',
  694.       orientation = 'portrait',
  695.       align = 'center',
  696.       image,
  697.       html2canvas: html2canvasOptions,
  698.       pagebreak,
  699.       onProgress,
  700.     } = options || {};
  701.     try {
  702.       exporting.value = true;
  703.       updateProgress(0, onProgress);
  704.       // 确保库已加载
  705.       await loadLibraries();
  706.       if (!jsPDF) {
  707.         throw new Error('jsPDF 未加载');
  708.       }
  709.       // 渲染为 Canvas
  710.       const canvas = await renderToCanvas(targetElement, {
  711.         scale,
  712.         html2canvas: html2canvasOptions,
  713.         onProgress: (progress) => {
  714.           // 将 Canvas 渲染进度映射到 0-50%
  715.           updateProgress(progress * 0.5, onProgress);
  716.         },
  717.       });
  718.       // 切分并生成 PDF
  719.       splitCanvasToPdf(
  720.         canvas,
  721.         {
  722.           fileName,
  723.           padding,
  724.           format,
  725.           orientation,
  726.           align,
  727.           image,
  728.           pagebreak,
  729.           onProgress: (progress) => {
  730.             // 将 PDF 生成进度映射到 50-100%
  731.             updateProgress(50 + progress * 0.5, onProgress);
  732.           },
  733.         },
  734.         true // 下载
  735.       );
  736.       if ($message) {
  737.         $message.success('PDF生成成功');
  738.       }
  739.     } catch (error: any) {
  740.       console.error('PDF 生成失败:', error);
  741.       updateProgress(0);
  742.       if ($message) {
  743.         $message.error(error?.message || 'PDF生成失败,请稍后重试');
  744.       }
  745.       throw error;
  746.     } finally {
  747.       exporting.value = false;
  748.     }
  749.   };
  750.   /**
  751.    * 预览 PDF(在新窗口打开)
  752.    * @param element 需要导出的 DOM 元素或选择器
  753.    * @param options 配置项
  754.    */
  755.   const previewPdf = async (
  756.     element: HTMLElement | string | null,
  757.     options?: Html2PdfOptions
  758.   ): Promise<void> => {
  759.     // 服务端检查
  760.     if (process.server) {
  761.       if ($message) $message.error('PDF预览功能仅在客户端可用');
  762.       return;
  763.     }
  764.     const targetElement = getElement(element);
  765.     if (!targetElement) {
  766.       if ($message) $message.error('未找到要导出的 DOM 元素');
  767.       return;
  768.     }
  769.     const {
  770.       fileName = 'preview.pdf',
  771.       scale,
  772.       padding = 0,
  773.       format = 'a4',
  774.       orientation = 'portrait',
  775.       align = 'center',
  776.       image,
  777.       html2canvas: html2canvasOptions,
  778.       pagebreak,
  779.       onProgress,
  780.     } = options || {};
  781.     try {
  782.       exporting.value = true;
  783.       updateProgress(0, onProgress);
  784.       // 确保库已加载
  785.       await loadLibraries();
  786.       if (!jsPDF) {
  787.         throw new Error('jsPDF 未加载');
  788.       }
  789.       // 渲染为 Canvas
  790.       const canvas = await renderToCanvas(targetElement, {
  791.         scale,
  792.         html2canvas: html2canvasOptions,
  793.         onProgress: (progress) => {
  794.           // 将 Canvas 渲染进度映射到 0-50%
  795.           updateProgress(progress * 0.5, onProgress);
  796.         },
  797.       });
  798.       // 切分并生成 PDF(不下载,生成预览图片)
  799.       const { pdf, images } = splitCanvasToPdf(
  800.         canvas,
  801.         {
  802.           fileName,
  803.           padding,
  804.           format,
  805.           orientation,
  806.           align,
  807.           image,
  808.           pagebreak,
  809.           onProgress: (progress) => {
  810.             // 将 PDF 生成进度映射到 50-100%
  811.             updateProgress(50 + progress * 0.5, onProgress);
  812.           },
  813.         },
  814.         false // 不下载
  815.       );
  816.       // 更新预览图片
  817.       previewImages.value = images;
  818.       // 生成 PDF Blob 并在新窗口打开
  819.       const pdfBlob = pdf.output('blob');
  820.       const url = URL.createObjectURL(pdfBlob);
  821.       const previewWindow = window.open(url, '_blank');
  822.       if (!previewWindow) {
  823.         if ($message) $message.warning('请允许弹出窗口以预览PDF');
  824.         // 如果无法打开新窗口,则下载
  825.         pdf.save(fileName);
  826.         updateProgress(100, onProgress);
  827.         return;
  828.       }
  829.       // 清理URL对象
  830.       previewWindow.addEventListener('load', () => {
  831.         setTimeout(() => URL.revokeObjectURL(url), 1000);
  832.       });
  833.       updateProgress(100, onProgress);
  834.       if ($message) {
  835.         $message.success('PDF预览已打开');
  836.       }
  837.     } catch (error: any) {
  838.       console.error('PDF 预览失败:', error);
  839.       updateProgress(0);
  840.       if ($message) {
  841.         $message.error(error?.message || 'PDF预览失败,请稍后重试');
  842.       }
  843.       throw error;
  844.     } finally {
  845.       exporting.value = false;
  846.     }
  847.   };
  848.   return {
  849.     exporting,
  850.     progress,
  851.     previewImages,
  852.     exportPdf,
  853.     previewPdf,
  854.   };
  855. }
复制代码
最后


  • 使用 css 框架例如 unocss 等会出现 oklab 等渲染报错,目前查询是因为使用行内类样式,例如 text-[xxx] or 其他,详细大家可以看下 html2canvas 源码实现。
  • 不使用根据 Dom 节点克隆之后先创建容器的话会导致生成的 pdf 内容不是居中的,那么应该是需要更详细的计算绘制内容(反正没成功),有大佬可以评论区贴下代码给我研究下。
  • 文字下沉大部分是 css 框架问题,drawImage 生成的图片导致的,直接全局设置即可,三行代码搞定。
  • 生成 pdf 只有视图看到的话需要先滚动到顶部等一系列样式操作才能正常全部绘制。
    ...
欢迎评论区进行讨论!

来源:程序园用户自行投稿发布,如果侵权,请联系站长删除
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!

相关推荐

3 天前

举报

您需要登录后才可以回帖 登录 | 立即注册