Vue 生成PDF並下載


實現原理

該功能原理是將頁面轉化偉canvas在把canvas轉化為base64數據 最后將數據通過pdf.js生成下載,故需要和html2canvas一起使用
友情提醒這個pdf下載不能在app里直接使用,ios里面變成在線預覽功能;

window.scrollTo(0, 0);  
        const element = document.querySelector('#showContent')  ;// 這個dom元素是要導出pdf的div容器
        setTimeout(() => {  
          html2canvas(element, {  
            height: this.$refs.footer.offsetTop,
            useCORS: true // 如果說所生成的頁面中帶有跨域的圖片,這個useCors需要設置為True 否則畫布被污染不會顯示
          }).then((canvas) => {
            console.log(canvas);
            const contentWidth = canvas.width;
            const contentHeight = canvas.height;
            // 一頁pdf顯示html頁面生成的canvas高度;
            const pdfX = (contentWidth + 10) / 2 * 0.75;
            const pdfY = (contentHeight + 500) / 2 * 0.75;// 500為底部留白
            const imgX = pdfX;
            const imgY = (contentHeight / 2 * 0.75);// 內
            const pageData = canvas.toDataURL('image/jpeg', 1.0);
            const pdf = new JsPDF('', 'pt', [pdfX, pdfY]);
            // 有兩個高度需要區分,一個是html頁面的實際高度,和生成pdf的頁面高度(841.89)
            // 內容未超過pdf一頁顯示的范圍,無需分頁
            pdf.addImage(pageData, 'jpeg', 0, 0, imgX, imgY);
            pdf.save(1234 + '.pdf'); // 生成的文件名字


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM