使用canvas
HTML5 的 canvas 元素使用 JavaScript 在网页上绘制图像。
画布是一个矩形区域,你可以控制其每一像素。
canvas 拥有多种绘制路径、矩形、圆形、字符以及添加图像的方法。
<template>
<div>
<a-card style="margin-bottom: 30px">
<a-row style="margin-bottom: 10px">
<a-button type="primary" @click="toPdfAndDownload">下载pdf</a-button>
</a-row>
<a-row>
<a-col :span="24">
<canvas id="testCanvas" width="1450px" height="1600px"
style="border:1px solid #cccccc;"></canvas>
</a-col>
</a-row>
</a-card>
</div>
</template>
绘图
可以对canvas的基础函数进行封装,然后方便调用绘图,例如
drawLine(beginX, beginY, beginX,beginY - 100, 0.6, '#000')
drawFraction('N**', 'P**', beginX, beginY - 140,'#000', '16pt 微软雅黑')
drawArc(beginX, beginY - 240, 10, 0, 360,true, false, '#000','','#000')
drawRect2(beginX, beginY, params.width[j], bottomHeight, '#000', '')
drawText('143/476', beginX + params.width[j] + 48, beginY + bottomHeight / 2,'#000000', '', 'center')
导出pdf
使用html2canvas组件对canvas进行截图,然后利用jsPdf组件将截图放入pdf文件中,并导出pdf。这样我们可以点击按钮,立即实现这一过程,然后下载得到pdf文件。
import html2canvas from 'html2canvas'
import jsPDF from 'jspdf'
toPdfAndDownload() {
let uuid = this.uuid()
// 截图区域是testCanvas
html2canvas(document.getElementById('testCanvas'), {
background: "#ffffff",
useCORS: true,
}).then(function (canvas) {
let contentWidth = canvas.width;
let contentHeight = canvas.height;
let imgWidth = 595.28;
let imgHeight = 592.28 / contentWidth * contentHeight;
let pageData = canvas.toDataURL('image/jpeg', 1.0);
let pdf = new jsPDF('', 'pt', 'a4');
pdf.addImage(pageData, 'JPEG', 0, 0, imgWidth, imgHeight)
pdf.save(uuid + '**************.pdf');
})
},
uuid() {
var s = [];
var hexDigits = "0123456789abcdef";
for (var i = 0; i < 36; i++) {
s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
}
s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
s[8] = s[13] = s[18] = s[23] = "-";
return s.join("");
},
效果示例
如果觉得比较模糊,可以画得大一些,然后缩小成A4大小,放入pdf,这样就看起来尚可。