vue3將頁面生成pdf導(dǎo)出的操作指南
前言
最近工作中有需要將一些前端頁面(如報表頁面等)導(dǎo)出為pdf
的需求,博主采用的是html2Canvas + jspdf
。
步驟
1.引入兩個依賴
npm i html2canvas npm i jspdf
點擊jsPDF GitHub、jsPDF 文檔 查看關(guān)于jsPDF
更多信息。
2.在utils
文件夾下新建html2pdf.ts
文件
import html2canvas from 'html2canvas'; import jsPDF from 'jspdf' export const htmlToPDF = async (htmlId: string, title: string = "報表", bgColor = "#fff") => { let pdfDom: HTMLElement | null = document.getElementById(htmlId) as HTMLElement pdfDom.style.padding = '0 10px !important' const A4Width = 595.28; const A4Height = 841.89; let canvas = await html2canvas(pdfDom, { scale: 2, useCORS: true, backgroundColor: bgColor, }); let pageHeight = (canvas.width / A4Width) * A4Height; let leftHeight = canvas.height; let position = 0; let imgWidth = A4Width; let imgHeight = (A4Width / canvas.width) * canvas.height; /* 根據(jù)自身業(yè)務(wù)需求 是否在此處鍵入下方水印代碼 */ let pageData = canvas.toDataURL("image/jpeg", 1.0); let PDF = new jsPDF("p", '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 -= A4Height; if (leftHeight > 0) PDF.addPage(); } } PDF.save(title + ".pdf"); }
如果你想給pdf
加上水印,則添加下面這段代碼:
const ctx: any = canvas.getContext('2d'); ctx.textAlign = 'center'; ctx.textBaseline = 'middle'; ctx.rotate((20 * Math.PI) / 180); ctx.font = '20px Microsoft Yahei'; ctx.fillStyle = 'rgba(184, 184, 184, 0.8)'; for (let i = canvas.width * -1; i < canvas.width; i += 240) { for (let j = canvas.height * -1; j < canvas.height; j += 200) { // 填充文字,x 間距, y 間距 ctx.fillText('水印名', i, j); } }
3.在目標(biāo)頁面引入方法即可
import { htmlToPDF } from '@/utils/html2pdf'
<div id="test-id" style="padding: 20px 0;"> <div style="background: #000;width: 100px;height: 100px;margin: auto;"></div> <p>test</p> <p>test</p> <p>test</p> <p>test</p> <p>test</p> <p>test</p> <p>test</p> </div> <button @click="() => htmlToPDF('test-id','test pdf')">導(dǎo)出</button>
效果如下:
到此這篇關(guān)于vue3將頁面生成pdf導(dǎo)出的操作指南的文章就介紹到這了,更多相關(guān)vue3將頁面生成pdf內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
element組件中自定義組件的樣式不生效問題(vue scoped scss無效)
這篇文章主要介紹了解決element組件中自定義組件的樣式不生效問題(vue scoped scss無效),具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-09-09vue鼠標(biāo)懸停事件監(jiān)聽實現(xiàn)方法
頁面在鼠標(biāo)懸停(不動)n秒之后,頁面進(jìn)行相應(yīng)的事件,下面這篇文章主要給大家介紹了關(guān)于vue鼠標(biāo)懸停事件監(jiān)聽的相關(guān)資料,文中通過實例代碼介紹的非常詳細(xì),需要的朋友可以參考下2022-09-09axios 實現(xiàn)post請求時把對象obj數(shù)據(jù)轉(zhuǎn)為formdata
今天小編就為大家分享一篇axios 實現(xiàn)post請求時把對象obj數(shù)據(jù)轉(zhuǎn)為formdata,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-10-10解決vue動態(tài)下拉菜單 有數(shù)據(jù)未反應(yīng)的問題
這篇文章主要介紹了解決vue動態(tài)下拉菜單 有數(shù)據(jù)未反應(yīng)的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-08-08