html2canvas jspdf render vue component



我正在尝试将 vue 组件的模板渲染到画布,然后将其添加到 html 中,但我所拥有的只是空白图像。甚至可能吗?

我尝试将document.body渲染为图像,它非常完美(不使用组件,直接从父级(。然后我尝试将此.$refs.content设置为要捕获的元素,甚至从控制台.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>

我安装了vue-html2canvas。获得正确的画布,没有任何其他选项:

let el = this.$refs.print.$el;
this.output = (await html2canvas(el)).toDataURL(); 

$el 在调用 vue 组件的 ref 时是必然

相关内容

  • 没有找到相关文章

最新更新