我正在尝试将vue组件的模板渲染到画布上,然后将其添加到html中,但是我所拥有的只是空白图像。甚至有可能吗?
我尝试将document.body渲染为图像,这非常完美(无需使用组件,直接从父级开始)。然后,我尝试将this。$ refs.content设置为要捕获的元素,甚至从console.log获得正确的输出,但是我只有白色的空白图片。现在,我决定将此逻辑包装在组件中。要捕获的所需div位于页面底部,您需要滚动很多才能到达它。也许有问题吗?任何建议都将受到高度赞赏。
这里的组件模板:
<template>
<div>
<button @click="download" class="btn">PDF Download</button>
<div class="A4" ref="content">
<div class="col s12">
<h5 style="text-align: center">
<strong>Load Confirmation & Rate Agreement</strong>
</h5>
</div>
<div class="col s12">
<div class="col s2">
<img style="width: 110px" :src="logo" alt="logo" />
</div>
<div class="col s4">
<h6>
<strong>{{ companyName.toUpperCase() }}</strong>
</h6>
<p style="margin-top: 0px;">We make it move!</p>
</div>
</div>
</div>
</div>
</template>
这是组件的脚本部分:
<script>
import jsPDF from 'jspdf';
import html2canvas from 'html2canvas';
export default {
data: () => ({
logo: '',
companyName: ''
}),
methods: {
download() {
let self = this;
console.log(self);
return new Promise((resolve, reject) => {
let windowHeight = self.$refs.content.offsetHeight;
let windowWidth = self.$refs.content.offsetWidth;
let pdfName = 'results';
var doc = new jsPDF('p', 'mm', 'a4');
var canvasElement = document.createElement('canvas');
canvasElement.width = windowWidth;
canvasElement.height = windowHeight;
html2canvas(self.$refs.content, {
canvas: canvasElement,
width: windowWidth,
height: windowHeight
})
.then(function(canvas) {
let ratio = canvas.width / canvas.height;
let PDFwidth = doc.internal.pageSize.getWidth();
let PDFheight = PDFwidth / ratio;
const img = canvas.toDataURL('image/jpeg', 1);
doc.addImage(img, 'JPEG', 0, 0, PDFwidth, PDFheight);
doc.save('sample.pdf');
resolve();
})
.catch(err => {
reject(err);
});
});
}
},
async mounted() {
this.logo = (await this.$store.dispatch('fetchLogo')).logo;
this.companyName = await this.$store.dispatch('fetchCompanyName');
}
};
</script>
和样式:
<style scoped>
.A4 {
border: 1px solid black;
background-color: lightgoldenrodyellow;
height: 297mm;
width: 210mm;
padding: 5mm;
}
</style>
答案 0 :(得分:0)
我改为安装了vue-html2canvas。得到了正确的画布,没有任何其他选项:
let el = this.$refs.print.$el;
this.output = (await html2canvas(el)).toDataURL();
在调用作为vue组件的ref时,必须使用$ el