1.vue 轉 PDF
在 Vue 項目中將 HTML 頁面轉換為 PDF 文件是一個常見需求,特別是在需要生成報告或打印頁面時。本文將介紹如何使用?html2canvas?和?jspdf?庫實現這一功能。
2.安裝依賴
首先,我們需要安裝兩個庫:html2canvas?和?jspdf?。可以使用以下命令安裝:
npm install html2canvas
npm install jspdf --save
3.創建轉換函數
在?utils?文件夾下創建一個?htmlToPdf.js?文件,并編寫以下代碼:
import html2Canvas from 'html2canvas';
import jsPDF from 'jspdf';const htmlToPdf = {
getPdf(title) {
html2Canvas(document.querySelector('#pdfDom'), {//這里pdfDom就是你打印/下載頁面區域的div的id
allowTaint: false,
taintTest: false,
logging: false,
useCORS: true,
dpi: window.devicePixelRatio * 4, // 提高分辨率
scale: 4 // 按比例增加分辨率
}).then(canvas => {
const pdf = new jsPDF('p', 'mm', 'a4'); // A4 紙,縱向
const ctx = canvas.getContext('2d');
const a4w = 190, a4h = 277; // A4 大小,四邊各保留 10mm 邊距
const imgHeight = Math.floor(a4h * canvas.width / a4w);
let renderedHeight = 0;while (renderedHeight < canvas.height) {
const page = document.createElement('canvas');
page.width = canvas.width;
page.height = Math.min(imgHeight, canvas.height - renderedHeight);
page.getContext('2d').putImageData(ctx.getImageData(0, renderedHeight, canvas.width, Math.min(imgHeight, canvas.height - renderedHeight)), 0, 0);
pdf.addImage(page.toDataURL('image/jpeg', 1.0), 'JPEG', 10, 10, a4w, Math.min(a4h, a4w * page.height / page.width));
renderedHeight += imgHeight;
if (renderedHeight < canvas.height) {
pdf.addPage();
}
}
pdf.save(title + '.pdf'); //這里title可以改為你下載pdf文件時的默認文件名
});
}
};export default htmlToPdf;
4.在vue組件中使用
在需要生成 PDF 的 Vue 組件中,引用并使用上述函數。首先,在組件中引入?htmlToPdf?:
import htmlToPdf from '@/utils/htmlToPdf';
然后,在模板中添加一個包含需要轉換內容的?div,并設置一個按鈕來觸發 PDF 生成:
<div id="pdfDom"> 這里的 id 要和 htmlToPdf 函數中你寫的id保持一致
<!-- 這里是你需要打印/轉為pdf文件下載的頁面內容 -->
</div>
<div class="preview-content-operateBtn">
<button class="previewBtn" @click="onClickDownLoad">下載 PDF 簡歷</button>
</div>
在按鈕的點擊方法中調用?htmlToPdf.getPdf?函數:
methods: { //這里以vue2的選項式代碼示例onClickDownLoad() {htmlToPdf.getPdf('下載名稱');}
}
解決常見問題:
模糊問題:通過放大 canvas 尺寸和調整 DPI 來解決。
頁邊距問題:在生成 PDF 時預留頁邊距。
跨域圖片問題:將圖片轉換為 base64 格式,避免跨域錯誤。
通過以上步驟,我們可以在 Vue 項目中輕松實現 HTML 轉 PDF 的功能,并解決常見的模糊、頁邊距和跨域圖片問題。
本文僅供個人學習使用記錄