1 . 前端导出 pdf 分页带表头
- 这个主要使用了 pdfMake 这个插件 ,需要有一份字体文件。
- 使用时需要结合 表数据 和 pafMake 的配置 生成的表格。
相关代码:
注:加上 headerRows 分页的时候会每页带表头。
-
导出 pdf 不分页
-
使用了 html2canvas jsPdf 这个两个插件 。
-
过程是使用 html2canvas 这个插件把 html 元素 转化成 canvas 再由canvas 转化成 图片 ,然后由jsPdf 生成pdf .
export default {
install(Vue, options) {
Vue.prototype.getPdf = function() {
let title = this.htmlTitle
// jsPDF 导出分页
// html2Canvas(document.querySelector(''), {
// allowTaint: true,
// useCORS: true, // 【重要】开启跨域配置
// scrollY: 30, // 纵向偏移量 写死0 可以避免滚动造成偶尔偏移的现象
// dpi: window.devicePixelRatio * 4,
// scale: 3,
// }).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')
// })
// jsPDF 导出不分页
// 生成的pdf只有页面窗口可见的区域,有滚动条的下面没有生成出来,需在生成PDF前,改overflow属性auto为visible
// 获取dom高度、宽度
var shareContent = document.querySelector('');
var width = shareContent.offsetWidth / 4;
var height = shareContent.offsetHeight / 4;
// let _this = this;
// eslint-disable-next-line
// let loadingInstance = Loading.service({ text: '正在导出,请稍等' });
html2Canvas(document.getElementById(''), {
dpi: 900,
scrolly: 0,
// width:eleW,//生成后的宽度
// height:eleH,//生成后的高度
scrollx: -10,
useCORS: true, //允许canvas画布内可以跨域请求外部链接图片, 允许跨域请求。
// backgroundColor: null //避免图片有白色边框
}).then((canvas) => {
var context = canvas.getContext('2d');
context.mozImageSmoothingEnabled = false;
context.webkitImageSmoothingEnabled = false;
context.msImageSmoothingEnabled = false;
context.imageSmoothingEnabled = false;
var pageData = canvas.toDataURL('image/jpeg', 1.0);
var img = new Image();
img.src = pageData;
img.onload = () => {
// 获取dom高度、宽度
img.width = img.width / 2;
img.height = img.height / 2;
console.log(img.width, '------ img.width');
console.log(img.height, '------img.height');
img.style.transform = 'scale(0.5)';
if (width > height) {
// 此可以根据打印的大小进行自动调节
// eslint-disable-next-line
var pdf = new JsPDF('l', 'mm', [width * 0.505, height * 0.545]);
} else {
// eslint-disable-next-line
var pdf = new JsPDF('p', 'mm', [width * 0.505, height * 0.545]);
}
pdf.addImage(pageData, 'jpeg', 0, 0, width * 0.505, height * 0.545);
pdf.save(title + '.pdf');
// loadingInstance.close();
};
});