vue 下载pdf

第一步下载

 

 第二步

创建一个htmlToPdf.js的js文件

// 导出页面为PDF格式
import html2Canvas from 'html2canvas'
import JsPDF from 'jspdf'
export default {
    install(Vue, options) {
        Vue.prototype.getPdf = function () {
            // 当下载pdf时,若不在页面顶部会造成PDF样式不对,所以先回到页面顶部再下载
            let top = document.getElementById('pdfDom');
            if (top != null) {
                top.scrollIntoView();
                top = null;
            }
            let title = this.exportPDFtitle;
            html2Canvas(document.querySelector('#pdfDom'), {
                allowTaint: true
            }).then(function (canvas) {
                // 获取canvas画布的宽高
                let contentWidth = canvas.width;
                let contentHeight = canvas.height;
                // 一页pdf显示html页面生成的canvas高度;
                let pageHeight = contentWidth / 841.89 * 592.28;
                // 未生成pdf的html页面高度
                let leftHeight = contentHeight;
                // 页面偏移
                let position = 0;
                // html页面生成的canvas在pdf中图片的宽高(本例为:横向a4纸[841.89,592.28],纵向需调换尺寸)
                let imgWidth = 841.89;
                let imgHeight = 841.89 / contentWidth * contentHeight;
                let pageData = canvas.toDataURL('image/jpeg', 1.0);
                let PDF = new JsPDF('l', 'pt', 'a4');
                // 两个高度需要区分: 一个是html页面的实际高度,和生成pdf的页面高度
                // 当内容未超过pdf一页显示的范围,无需分页
                if (leftHeight < pageHeight) {
                    PDF.addImage(pageData, 'JPEG', 0, 0, imgWidth, imgHeight)
                } else {
                    while (leftHeight > 0) {
                        PDF.addImage(pageData, 'JPEG', 0, position, imgWidth, imgHeight)
                        leftHeight -= pageHeight;
                        position -= 592.28;
                        // 避免添加空白页
                        if (leftHeight > 0) {
                            PDF.addPage();
                        }
                    }
                }
                PDF.save(title + '.pdf')
            })
        }
    }
}

 

 

 

 

第三步 在 main.js 引入

// main.js
import htmlToPdf from '@/util/htmlToPdf'
Vue.use(htmlToPdf)

 

 

 

第四步 在页面使用

 

posted @   儿允儿  阅读(1666)  评论(1编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示