VUE实现纯前端PDF下载

VUE实现纯前端PDF下载

<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 @ 2025-02-27 12:43  haonanElva  阅读(40)  评论(0)    收藏  举报