使用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的名称
    });
  }
相关推荐
:mnong7 小时前
ClawX 项目设计分析
node.js·skill
小小亮017 小时前
Next.js基础
开发语言·前端·javascript
华洛7 小时前
我用AI做了一个48秒的真人精品漫剧,不难也不贵
前端·javascript·后端
Amumu121388 小时前
Js:正则表达式(二)
开发语言·javascript·正则表达式
Sgf2278 小时前
ES8(ES2017)新特性完整指南
开发语言·javascript·ecmascript
Cobyte11 小时前
1.基于依赖追踪和触发的响应式系统的本质
前端·javascript·vue.js
代码搬运媛11 小时前
NestJS 实战:TypeORM 从入门到精通(完整教程)
node.js
老神在在00111 小时前
【Selenium 自动化精讲】浏览器弹窗与登录界面的本质区别 & 实操指南
javascript·学习·selenium·测试工具·自动化
前端小咸鱼一条12 小时前
16.迭代器 和 生成器
开发语言·前端·javascript
太难了啊12 小时前
5分钟实现你的第一个 Node.js 智能体
人工智能·node.js