前言:該篇主要是解決一些簡單的頁面內容導出為PDF
1.安裝依賴
使用到兩個依賴,項目目錄下運行這兩個
//頁面轉換成圖片
npm install --save html2canvas
//圖片轉換成pdf
npm install jspdf --save
2.創建通用工具類exportPdf.js文件
可以保存在工具類目錄下;
// 導出頁面為PDF格式
import html2Canvas from 'html2canvas'
import JsPDF from 'jspdf'export function getPdf(title, id) {// 參數校驗if (!title || !id) {console.error('Title and ID are required.')return}const element = document.querySelector(`#${id}`)if (!element) {console.error(`Element with ID "${id}" not found.`)return}html2Canvas(element, {allowTaint: true,useCORS: true,scale: 2}).then(function (canvas) {const contentWidth = canvas.widthconst contentHeight = canvas.height// A4紙尺寸 (單位: pt)const a4Width = 595.28const a4Height = 841.89// 設置外邊距 (單位: pt)const marginLeft = 20const marginTop = 20const marginRight = 20const marginBottom = 20// 計算可用內容區域const availableWidth = a4Width - marginLeft - marginRightconst availableHeight = a4Height - marginTop - marginBottom// 計算縮放比例,使內容寬度適配可用區域const scale = availableWidth / contentWidth// 按比例計算圖像在頁面上的尺寸const imgWidth = contentWidth * scaleconst imgHeight = contentHeight * scale// 計算每頁可容納的高度(考慮上下邊距)const pageHeight = availableHeightlet leftHeight = imgHeightlet position = 0const pageData = canvas.toDataURL('image/jpeg', 0.95)const PDF = new JsPDF('', 'pt', 'a4')if (leftHeight < pageHeight) {// 內容高度小于頁面可用高度,直接添加圖片(帶外邊距)PDF.addImage(pageData, 'JPEG', marginLeft, marginTop, imgWidth, imgHeight)} else {// 內容高度大于頁面可用高度,分頁處理while (leftHeight > 0) {// 添加當前頁面圖像(帶外邊距)PDF.addImage(pageData, 'JPEG', marginLeft, marginTop + position, imgWidth, imgHeight)leftHeight -= pageHeightposition -= a4Height// 如果還有剩余內容,添加新頁面if (leftHeight > 0) {PDF.addPage()}}}PDF.save(title + '.pdf')}).catch(function (error) {console.error('PDF導出失敗:', error)})
}
3.Demo例子
<template><div><!-- 容器 --><div id="pdfHtml" ref="printHtml"><h1>這是一個Demo。</h1></div><button @click="exportPDF">PDF導出</button></div>
</template>
<script>
import { getPdf } from '@/utils/exportPdf';
export default {methods: {// 導出pdfexportPDF() {getPdf('關鍵因素', 'pdfHtml');}}
}
</script>