背景:
将前端页面指定区域的内容导出为pdf,使用纯前端实现
两种实现:
方式一: 使用
jsPDF
、html2canvas
,将特定区域使用html2canvas
转化为图片,使用jsPDF
将图片转化为pdf。该方式适用于小区域转化pdf。当前转化区域有翻页时会出现内容拆分导致导致的可读性变差。
<template> <div> <!-- 其他代码 --> <el-button @click="handleDownload">下载PDF</el-button> <el-dialog :visible.sync="dialogVisible"> <div id="content-to-pdf"> <!-- 对话框内容 --> </div> </el-dialog> </div> </template> <script> import html2canvas from 'html2canvas'; import { jsPDF } from "jspdf"; export default { data() { return { dialogVisible: false, }; }, methods: { handleDownload() { const contentDom = document.getElementById('content-to-pdf'); // 使用html2canvas捕获DOM元素为图片 html2canvas(contentDom).then(canvas => { const imgData = canvas.toDataURL('image/png'); // 创建PDF并添加图片 const pdf = new jsPDF(); pdf.addImage(imgData, 'PNG', 10, 10); // 下载PDF pdf.save("download.pdf"); }); } } } </script>
方式二:
html2pdf.js
将特定区域。支持自动分页<template> <div> <!-- 其他代码 --> <el-button @click="handleDownload">下载PDF</el-button> <el-dialog :visible.sync="dialogVisible"> <div id="content-to-pdf"> <!-- 对话框内容 --> </div> </el-dialog> </div> </template> <script> import html2pdf from 'html2pdf.js'; export default { data() { return { dialogVisible: false, }; }, methods: { handleDownload() { const contentDom = document.getElementById('content-to-pdf'); html2pdf() .from(element) .set({ margin: 10, filename: '导出文档.pdf', image: { type: 'jpeg', quality: 0.98 }, html2canvas: { scale: 2, useCORS: true, // 如果你有加载图片,且跨域 allowTaint: true }, jsPDF: { unit: 'mm', format: 'a4', orientation: 'portrait' } }) .save(); } } } </script>