所用插件
html2canvas 转图片
jsPDF 转PDF
代码实现
import html2canvas from "html2canvas";
import jsPDF from "jspdf";
export default {
install(Vue) {
Vue.prototype.htmlToPdf = function (name, title) {
// 获取想要转换的 DOM 节点
const dom = document.getElementById(name);
const box = window.getComputedStyle(dom);
// DOM 节点计算后宽高
const width = parseInt(box.width, 10);
const height = parseInt(box.height, 10);
// 获取像素比
const DPR = function DPR() { // 获取设备dpi
if (window.devicePixelRatio && window.devicePixelRatio > 1) {
return window.devicePixelRatio;
}
return 1;
}
const scaleBy = DPR()
// 创建自定义 canvas 元素
const canvas = document.createElement('canvas');
// 设定 canvas 元素属性宽高为 DOM 节点宽高 * 像素比
canvas.width = width * scaleBy;
canvas.height = height * scaleBy;
// 设定 canvas css宽高为 DOM 节点宽高
canvas.style.width = `${width}px`;
canvas.style.height = `${height}px`;
// 获取画笔
const context = canvas.getContext('2d');
// 将所有绘制内容放大像素比倍
context.scale(scaleBy, scaleBy);
// 将自定义 canvas 作为配置项传入,开始绘制
html2canvas(dom, {
canvas,
backgroundColor: null,
useCORS: true, // 【重要】开启跨域配置
}).then((canvas) => {
const contentWidth = canvas.width
const contentHeight = canvas.height
const pageData = canvas.toDataURL('image/jpeg', 1.0)
const pdfWidth = (contentWidth) / 2 * 0.75 //不留白
const pdfHeight = (contentHeight) / 2 * 0.75 // 500为底部留白
const imgWidth = pdfWidth
const imgHeight = (contentHeight / 2 * 0.75) // 内容图片这里不需要留白的距离
const PDF = new jsPDF('l', 'pt', [pdfWidth, pdfHeight])
PDF.addImage(pageData, 'jpeg', 0, 0, imgWidth, imgHeight)
PDF.save(title + '.pdf')
})
// 转图片
/*
.then((imgDom) => {
let url = imgDom.toDataURL();
console.log(url) // 此时的url是图片的base64格式,可直接赋值到img的src上
})
*/
/**转pdf
*/
};
},
}
使用
引入使用 this.htmlToPdf('pdf', 'pdf');
遇到的坑
1.文字模糊 设置缩放比 scale 2.图片展示不出来 开启图片跨域 useCORS: true, // 【重要】开启跨域配置 3.截取的图片有错位 白色块 使用了插件没兼容的css样式