<template>
|
<div>
|
<div ref="elementToCrop" >
|
<div style="width: 100%;">
|
<vue-office-excel :minRowLength="0" :src="excel" @rendered="rendered"/>
|
</div>
|
</div>
|
</div>
|
</template>
|
|
<script>
|
import VueOfficeExcel from '@vue-office/excel'
|
import '@vue-office/excel/lib/index.css'
|
import html2canvas from "html2canvas";
|
import jsPDF from "jspdf";
|
export default {
|
name:"previewExcel",
|
props: {
|
},
|
data() {
|
return {
|
excel: '',//excel文档地址
|
cutAfterWidth:this.$route.params.cutAfterWidth,//裁剪后要减去的宽
|
};
|
},
|
computed: {
|
},
|
created() {
|
console.log(this.$route.params.baseOperationType,"看看")
|
if(this.$route.params.baseOperationType!=undefined){
|
this.excel=this.$route.params.url
|
}
|
},
|
mounted() {
|
},
|
watch: {
|
},
|
methods: {
|
rendered(){
|
console.log("渲染完成")
|
if(this.$route.params.baseOperationType!=undefined){
|
this.excel=this.$route.params.url
|
this.cropAndDownload()
|
}
|
},
|
async cropAndDownload() {
|
const elementToCrop = this.$refs.elementToCrop;
|
const canvas = await html2canvas(elementToCrop);
|
const croppedCanvas = document.createElement("canvas");
|
const croppedContext = croppedCanvas.getContext("2d");
|
croppedCanvas.width = canvas.width ; //裁剪前
|
croppedCanvas.height = canvas.height - 100; // 去掉上下各100px
|
// 在新的Canvas上绘制裁剪后的图像
|
croppedContext.drawImage(
|
canvas,
|
50, // 开始裁剪的左侧位置
|
20, // 开始裁剪的上侧位置
|
croppedCanvas.width-this.cutAfterWidth, // 裁剪后的宽度
|
croppedCanvas.height-300, // 裁剪后的高度
|
0, // 新Canvas中绘制的左侧位置
|
0, // 新Canvas中绘制的上侧位置
|
croppedCanvas.width, // 新Canvas中绘制的宽度
|
croppedCanvas.height // 新Canvas中绘制的高度
|
);
|
// 将裁剪后的Canvas转换为DataURL
|
const croppedImage = croppedCanvas.toDataURL("image/png");
|
// 更新数据,以在页面上显示裁剪后的图片
|
this.croppedImage = croppedImage;
|
// 创建PDF文档
|
const pdf = new jsPDF({
|
unit:"mm",
|
format:"a4"
|
});
|
// A4
|
const a4Width = 210;
|
const a4Height = 297;
|
// 计算缩放比例,确保canvas等比例缩放适应A4纸
|
const scale = Math.min(a4Width / canvas.width, a4Height / canvas.height);
|
// 计算缩放后的宽高
|
const scaledWidth = canvas.width * scale;
|
const scaledHeight = canvas.height * scale;
|
// 将canvas元素转换为png,插入到PDF文档中
|
pdf.addImage(croppedImage, "PNG",0,0,scaledWidth,scaledHeight);
|
// 保存PDF文档
|
pdf.save("export.pdf");
|
},
|
},
|
components: {
|
VueOfficeExcel,
|
},
|
};
|
</script>
|
<style scoped lang="scss">
|
.vue-office-excel{
|
height: 1000px;
|
}
|
</style>
|