俗话说一包卡一天,真的是没谁了,今天终于把这个问题解决了,废话不多说,直接上代码。
第一步先下载俩个包。
// npm install html2canvas
// npm install jspdf --save
import html2canvas from 'html2canvas';
import JsPDF from 'jspdf'
在下载jspdf的时候会报错
PS E:\empss\empss-visualization-ui> npm install jspdf npm WARN registry Unexpected warning for https://registry.npmjs.org/: Miscellaneous Warning ECONNRESET: request to https://registry.npmjs.org/jspdf failed, reason: Client network socket disconnected before secure TLS connection was established
npm WARN registry Using stale data from https://registry.npmjs.org/ due to a request error during revalidation.
npm ERR! code ENOENT
npm ERR! syscall spawn git
npm ERR! path git
npm ERR! errno ENOENT
npm ERR! enoent Error while executing:
npm ERR! enoent undefined ls-remote -h -t ssh://git@github.com/eligrey/FileSaver.js.git
npm ERR! enoent
npm ERR! enoent
npm ERR! enoent spawn git ENOENT
npm ERR! enoent This is related to npm not being able to find a file.
npm ERR! enoent
npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\zhongruanxiaowu\AppData\Roaming\npm-cache\_logs\2020-07-23T07_29_00_408Z-debug.log
看见这么一大堆东西就烦,搞了一天,yang也用了,cnpm也用了,就是不行,问朋友说是网不好,最后我下载了一个git管理git下载地址,直接在里面运行npm install jspdf --save就可以使用了。代码部分已在底下显示。
// 生成PDF
onrendered = (canvasImage) => {
console.log(canvasImage)
canvasImage.id = "mycanvas";
//生成base64图片数据
// 在state里面定义的是个空字符串
this.state.dataUrl = canvasImage.toDataURL();
var newImage = document.createElement("img");
// console.log(newImage)
newImage.src = this.state.dataUrl;
// document.body.appendChild(newImage);
}
imageCode = () => {
// 这个是获取需要打印的pdf
const canvasData = document.getElementById("div_print");
html2canvas(canvasData).then((canvasImge) => {
// 这个是转为base64的代码
this.onrendered(canvasImge);
let contentWidth = canvasImge.width
let contentHeight = canvasImge.height
let pageHeight = contentWidth / 592.28 * 841.89
let leftHeight = contentHeight
let position = 0
let imgWidth = 595.28
let imgHeight = 592.28 / contentWidth * contentHeight
let pageData = canvasImge.toDataURL('image/jpeg', 1.0)
// document.body.appendChild(canvasImge);
let PDF = new JsPDF('', 'pt', 'a4');
if (leftHeight < pageHeight) {
PDF.addImage(pageData, 'JPEG', 0, 0, imgWidth, imgHeight)
} else {
while (leftHeight > 0) {
PDF.addImage(pageData, 'JPEG', 0, position, imgWidth, imgHeight)
leftHeight -= pageHeight
position -= 841.89
if (leftHeight > 0) {
PDF.addPage()
}
}
}
PDF.save(this.state.chartData.tilte + '.pdf')
});
};
几乎不用怎么修改就可以使用了。主要就是下载包的问题。