1、需要安装print-js
2、canvas转成图片的实现
image.src = canvas.toDataURL("image/png");
3、打印的样式可以通过引入文件设置打印样式
css: ['../print.css']
import { Component, useRef } from 'react';
import { Layout, Button } from 'antd';
import print from 'print-js'
import '../print.less'
class ReactToPrintCpn extends Component {
constructor() {
super();
this.state = {
imgUrl: ""
}
}
componentDidMount() {
var img = document.createElement('img');
img.src = 'https://img2.baidu.com/it/u=2024118501,374488785&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=281' //此处自己替换本地图片的地址
img.crossOrigin = 'anonymous'
img.onload = () => {
var data = this.getBase64Image(img);
// var img1 = document.createElement('img');
// img1.src = data;
// document.getElementById('base_img').appendChild(img1);
// console.log(data);
}
console.log('componentDidMount==========');
}
printJS = () => {
print({ printable: 'base_img', type: 'html', header: 'PrintJS - Form Element Selection',css: ['../print.css'] })
}
getBase64Image = (img) => {
var canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0, img.width, img.height);
// var dataURL = canvas.toDataURL("image/png");
// this.setState({
let imgUrl = this.convertCanvasToImage(canvas);
// })
document.getElementById('base_img').appendChild(imgUrl);
// return dataURL
// return dataURL.replace("data:image/png;base64,", "");
}
convertCanvasToImage = (canvas) => {
var image = new Image();
image.src = canvas.toDataURL("image/png");
console.log('convertCanvasToImage==========', image);
return image;
}
render() {
console.log('render==========');
return (
<div>
<Button type="button" onClick={this.printJS}>
Print JSON Data
</Button>
<div id="base_img">
</div>
</div>
)
}
}
export default ReactToPrintCpn;