使用pdfmake导出pdf文件

package配置pdfmake html2canvas,然后npm安装

javascript 复制代码
"pdfmake": "0.2.10",
"html2canvas": "1.4.1",

使用如下,

html里面组件加个id为exportPdf

然后调用下面的方法即可

输出的pdf为整个组件的截图

javascript 复制代码
import * as pdfMake from 'pdfmake/build/pdfmake';
import html2canvas from 'html2canvas';

exportPdf() {
    const widthScale = 2;
    const pdfWidth = 600 * widthScale; // pdf宽度
    const cntElem = document.getElementById('exportPdf');// 组件的id
    const width = cntElem.offsetWidth;
    const height = cntElem.scrollHeight;
    const scale = 3; // 数字越大,导出的pdf越清晰
    const opts = {
      scale: scale,
      width: width,
      height: height,
      useCORS: true,
    };

    html2canvas(cntElem, opts).then(canvas => {
      const contents = [];
      contents.push({
        image: canvas.toDataURL('image/jpeg'),
        width: pdfWidth,
      });

      pdfMake
        .createPdf({
          pageSize: {
            width: pdfWidth,
            height: pdfWidth / (width / height), // 按照实际高度比,自定义pdf高度
          },
          pageMargins: [0, 0],
          content: contents,
        })
        .download('11111');//1111是pdf的名称
    });
  }
相关推荐
To_OC6 小时前
写了三遍 Todo List,我终于搞懂了 React 父子组件到底怎么通信
前端·javascript·react.js
勇往直前plus6 小时前
Vue3(篇一) 核心概念——响应式模板语法与组件基础
前端·javascript·vue.js
用户938515635078 小时前
从零搭建 AI 日记助手:用 Milvus 向量数据库 + RAG 让机器读懂你的每一天
javascript·人工智能·全栈
a1117769 小时前
坦克大战3D Three.js 3D (开源项目)
开发语言·javascript·3d
kyriewen10 小时前
别再乱用useEffect了——你写的10个里有8个不该存在
前端·javascript·react.js
Ivanqhz10 小时前
Rust &‘static str浅析
java·前端·javascript·rust
zandy101111 小时前
衡石 Agentic BI的ReAct 推理框架在 Agentic BI 中的工程化实践
前端·javascript·react.js
郝亚军12 小时前
webstorm如何创建vue 3.js
javascript·vue.js·webstorm
এ慕ོ冬℘゜12 小时前
jQuery attr() 方法超详细讲解:属性获取、赋值、实战踩坑全解
前端·javascript·jquery
Hilaku13 小时前
为什么大厂对前端算法要求极高?
前端·javascript·程序员