VUE实现纯前端PDF下载

VUE实现纯前端PDF下载

1
2
3
4
5
6
7
<div class="cotext" ref="printDom">
              <div id="printDom">
 
......./具体要下载内容的代码/
 
            </div>
</div>

  

注:先安装依赖

1."html2canvas": "^1.4.1",

 "jspdf": "^2.5.2",

复制代码
exportInfo(){
                html2canvas(document.querySelector("#printDom"), {
                    allowTaint: true,
                    backgroundColor: "white",
                    useCORS: true, //支持图片跨域
                    scale: 2, //设置放大的倍数
                }).then((canvas) => {
                    //内容的宽度
                    const contentWidth = canvas.width;
                    //内容的高度
                    const contentHeight = canvas.height;
                    //一页pdf显示htm1页面生成的canvas高度,a4纸的尺寸[595.28,841.89];
                    const pageHeight = (contentWidth / 592.28) * 841.89;
                    //未生成pdf的htm1页面高度
                    let leftHeight = contentHeight;
                    //页面偏移
                    let position = 0;
                    //a4纸的尺寸[595.28,841.89],htm1页面生成的canvas在pdf中图片的宽高
                    const imgwidth = 595.28;
                    const imgHeight = (592.28 / contentWidth) * contentHeight;
                    //canvas转图片数据
                    const pageData = canvas.toDataURL("img/jpeg", 1.0);

                    //新建JSPDF对象
                    const PDF = new jsPDF("", "pt", "a4");
                    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 -= 841.89;
                            if (leftHeight > 0) {
                                PDF.addPage();
                            }
                        }
                    }
                    // PDF.text("这是标题", 10, 20); // 在PDF中添加标题,位置可以自定义
                    PDF.save("xxx.pdf");
                    PDF.output("datauristring");
                });
            },
复制代码

 

posted @   haonanElva  阅读(1)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
历史上的今天:
2017-02-27 前端常用正则验证
2017-02-27 移动端页面底部固定芬兰
点击右上角即可分享
微信分享提示