使用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的名称
    });
  }
相关推荐
怕浪猫10 小时前
NVIDIA 全产品谱系与演进
javascript·面试·github
吴名氏.14 小时前
从零手写一个 AI Agent 框架(TypeScript 完整实现):Function Calling 循环、流式输出与错误恢复
人工智能·typescript·node.js·大模型·ai agent·functioncalling·llm 应用开发
htzyl20618 小时前
金额计算:为什么前端不该用浮点数存钱
前端·javascript·算法
map_3d_vis20 小时前
百度地图 Hello World:5 分钟用 JSAPI 4.0 显示一张地图
前端·javascript·地图·百度地图
不要试图纠正别人20 小时前
构建 0 报错,产物体积翻倍:换引擎最容易漏的对账
前端·javascript
Hilaku20 小时前
面了 30 家公司拿到 2 个 Offer!
前端·javascript·程序员
CappuccinoRose21 小时前
前端开发交互体系 - 汇总篇
开发语言·前端·javascript·css·html·交互
用户298698530141 天前
React 前端实现 Excel 与 OpenXML 双向转换:基于 WebAssembly 的浏览器端方案
javascript·react.js·excel
星落梦生1 天前
Tlias前端案例涉及知识点 (14)
开发语言·前端·javascript
FRing031 天前
vue2干货总结12(loading效果、全局前置导航守卫、搜索历史管理)
开发语言·前端·javascript·vue.js·vue2