vue3+ts使用html2canvas,jspd导出pdf文件

下载依赖包

javascript 复制代码
npm install html2canvas jspdf

使用

javascript 复制代码
<div ref="pdfContentref" id="content-to-print" class="contengt">
	// 里面编写需要导出的页面
</div>
<el-button @click="exportPdf" type="primary" class="btn">导出PDF</el-button>

引入

javascript 复制代码
import html2canvas from 'html2canvas';
import jsPDF from 'jspdf';
const pdfContentref = ref<any>(null);

核心代码

javascript 复制代码
const exportPdf = () => {
    const content = pdfContentref.value;
    exportDataPdf(content)
}
const exportDataPdf = (el: any) => {
  html2canvas(el, {
    scale: 3, // 设置缩放
    useCORS: true, // 允许canvas画布内 可以跨域请求外部链接图片, 允许跨域请求。
    allowTaint: true,
    logging: false, // 打印日志用的 可以不加默认为false
    backgroundColor: '#ffffff'
  }).then((canvas) => {
    console.log('生成');
    const imgData = canvas.toDataURL('image/jpeg', 1.0);
      console.log(imgData);
      const pdf = new jsPDF();
        const imgProps= pdf.getImageProperties(imgData);
        const pdfWidth = pdf.internal.pageSize.getWidth();
        const pdfHeight = (imgProps.height * pdfWidth) / imgProps.width;
        pdf.addImage(imgData, 'PNG', 0, 0, pdfWidth, pdfHeight);
        pdf.save('测试.pdf');
    
  })
}
相关推荐
Daniel李华5 小时前
echarts使用案例
android·javascript·echarts
北原_春希5 小时前
如何在Vue3项目中引入并使用Echarts图表
前端·javascript·echarts
JY-HPS5 小时前
echarts天气折线图
javascript·vue.js·echarts
尽意啊5 小时前
echarts树图动态添加子节点
前端·javascript·echarts
吃面必吃蒜5 小时前
echarts 极坐标柱状图 如何定义柱子颜色
前端·javascript·echarts
O_oStayPositive5 小时前
Vue3使用ECharts
前端·javascript·echarts
竹秋…5 小时前
echarts自定义tooltip中的内容
前端·javascript·echarts
宝贝露.5 小时前
Axure引入Echarts图无法正常显示问题
前端·javascript·echarts
人良爱编程5 小时前
Hugo的Stack主题配置记录03-背景虚化-导航栏-Apache ECharts创建地图
前端·javascript·apache·echarts·css3·html5
来颗仙人掌吃吃5 小时前
解决Echarts设置宽度为100%发现宽度变为100px的问题(Echarts图标宽度自适应问题)
前端·javascript·echarts