<template>
|
<div>
|
|
<!-- <button @click="cropAndDownload">截取图片</button> -->
|
<!-- 显示裁剪后的图片 -->
|
<!-- <div style="width: 800px;">
|
<img style="width: 100%;" id="export-pdf" v-if="croppedImage" :src="croppedImage" alt="Cropped Image" />
|
</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:'',
|
cutAfterWidth:0,
|
// croppedImage: null, // 图片
|
};
|
},
|
computed: {
|
},
|
created() {
|
this.excel=this.$route.query.url;
|
this.cutAfterWidth=this.$route.query.cutAfterWidth
|
},
|
mounted() {
|
},
|
watch: {
|
},
|
methods: {
|
rendered(){
|
console.log("渲染完成")
|
if(this.$route.query.url){
|
this.excel=this.$route.query.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=croppedCanvas.width/100*this.cutAfterWidth,
|
// croppedCanvas.width-=croppedCanvas.width/100*46.7, // 裁剪后的宽度 入库单保留原图宽度53.3%
|
// croppedCanvas.width-=croppedCanvas.width/100*49.2, // 裁剪后的宽度 出库单保留原图宽度50.8%
|
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);
|
|
// (可选)你也可以将裁剪后的图片保存为文件
|
// this.saveCroppedImageToFile(croppedImage);
|
// 保存PDF文档
|
pdf.save("export.pdf");
|
},
|
// (可选)保存裁剪后的图片为文件
|
saveCroppedImageToFile(dataUrl) {
|
const link = document.createElement("a");
|
link.href = dataUrl;
|
link.download = "cropped_image.png";
|
link.click();
|
},
|
},
|
components: {
|
VueOfficeExcel,
|
},
|
};
|
</script>
|
<style scoped lang="scss">
|
.vue-office-excel{
|
height: 1000px;
|
}
|
</style>
|