把页面利用canvas转换成图片,然后再用图片的base64码转成pdf
安装2个插件:
npm install --save html2canvas //html页面转换成图片
npm install jspdf --save //把base64转换为PDF
js配置文件:
// 导出页面为PDF格式
import html2Canvas from "html2canvas";
import JsPDF from "jspdf";
export function getPdf(title, id) {
html2Canvas(document.querySelector(`#${id}`), {
allowTaint: true,
}).then(function (canvas) {
let contentWidth = canvas.width;
let contentHeight = canvas.height;
let pageHeight = (contentWidth / 592.28) * 841.89;
let leftHeight = contentHeight;
let position = 0;
let imgWidth = 595.28;
let imgHeight = (592.28 / contentWidth) * contentHeight;
let pageData = canvas.toDataURL("image/jpeg", 1.0);
let PDF = new JsPDF("", "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 -= 841.89;
if (leftHeight > 0) {
PDF.addPage();
}
}
}
PDF.save(title + ".pdf");
});
}
页面使用:
<m-button @click="getPdf('导出pdf', 'pcctable')">导出pdf</m-button>
<m-table :columns="columns" :data-source="data" @pageChange="pageChange" :total="formState.queryData.total" id="pcctable"></m-table>
import { getPdf } from "@/utils/exportPdf";
整张pdf:
// 导出页面为PDF格式
import html2Canvas from "html2canvas";
import JsPDF from "jspdf";
export function getPdf(title:string, id:string) {
document.documentElement.scrollTop = 0
let canvas = document.createElement("canvas") // 生成canvas上下文
let context = canvas.getContext("2d")
let _articleHtml = document.querySelector(`#${id}`)
let _w = _articleHtml.clientWidth //获取需要导出pdf区域的宽度和高度
let _h = _articleHtml.clientHeight
let scale = 3 //将画布宽&&高放大三倍,提高清晰度
if(_w >_h){
_h = _w
}
canvas.width = _w * scale
canvas.height = _h * scale
context.scale(scale, scale)
let opts = {
scale: 1,
width: _w,//dom 原始宽度
height: _h,
canvas: canvas,
// useCORS: true //允许canvas画布内可以跨域请求外部链接图片, 允许跨域请求。
}
// 以上部分都是为了强化清晰度的,放大canvas画布
html2Canvas(_articleHtml, opts).then(canvas => {
createPdfAll(canvas, scale)
})
// 自定义宽高
function createPdfAll (canvas, scale) {
let contentWidth = canvas.width / scale
let contentHeight = canvas.height / scale
let pdf = new JsPDF('', 'pt', [contentWidth, contentHeight]) //自定义宽高
let pageData = canvas.toDataURL('image/jpeg', 1.0) //转换图片为dataURL
pdf.addImage(pageData, 'JPEG', 0, 0, contentWidth, contentHeight) //添加图像到页面
pdf.save(`${title}.pdf`)
}