vue3.0 导出页面为PDF格式

htmlToPdf.ts

// 导出页面为PDF格式
import html2Canvas from 'html2canvas';
import JsPDF from 'jspdf';

export const htmlToPdf = async (dom, title) => {
    var pdfTitle = title;  //pdf的名称
    var pdfDom = document.querySelector(dom);
    html2Canvas(pdfDom, {
        allowTaint:false,
        useCORS: true
    }).then(function (canvas) {
        console.log(canvas);
        const marginBottom = 34;    // 项目页面显示微处理 以下用到的地方 可以忽略
        let canvasWidth = canvas.width;     //页面生成canvas宽度
        let canvasHeight = canvas.height + marginBottom; //页面生成canvas高度
        let pageHeight = canvasWidth / 592.28 * 841.89 + marginBottom;   //分页 每页的高度
        let allPageHeight = canvasHeight;  // 所有页面的高度
        let position = 0; //偏移量
        let imgWidth = 595.28; //生成canvas 图片的宽度
        let imgHeight = 592.28 / canvasWidth * canvasHeight; //生成canvas 图片的高度
        let pageData = canvas.toDataURL('image/jpeg', 3.0);
        // console.log(canvasWidth)
        // console.log(canvasHeight)
        // console.log(pageHeight)
        // console.log(allPageHeight)
        // console.log(position)
        // console.log(imgWidth)
        // console.log(imgHeight)
        // console.log(pageData)
        let PDF = new JsPDF('', 'pt', 'a4');
        if (allPageHeight < pageHeight) {
            PDF.addImage(pageData, 'JPEG', 0, 0, imgWidth, imgHeight);
        } else {
            //循环生成分页
            while (allPageHeight > 0) {
                PDF.addImage(pageData, 'JPEG', 0, position, imgWidth, imgHeight);
                allPageHeight = allPageHeight - pageHeight - marginBottom;
                position = position - 841.89 - marginBottom;
                if (allPageHeight > 0) {
                    PDF.addPage(); //添加新的一页
                }
            }
        }
        PDF.save(pdfTitle + '.pdf');  //保存pdf
    });

};

xxx.vue

<template>
    <div class="anslyse" id="clip" v-loading="listLoading">
        <h2>数据概览</h2>
        <kx-table :table-data="file_stats" :column-list="columnList"  border>
        </kx-table>
        <h2>数据详情</h2>
        <kx-table :table-data="file_list" :column-list="columnList2"  border>
        </kx-table>

    </div>
</template>
<script setup lang="ts">
import { htmlToPdf } from '@/utils/htmlToPdf';

const handleExpertPDF = async ()=>{
    if(list.value.length == 0){
        ElMessage({
            message: '当前页面暂无数据!',
            type: 'warning',
        });
        return false;
    } else {
        await htmlToPdf('#clip', '本年度数据统计分析报告');
    }

}

</script>
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容