前端实现html
转canvas
,html
转img
,html
转pdf
最近项目上有一个需求就是由纯前端html
转化生成PDF
,开始也是一脸蒙蔽的,但是咱也不能说不会做啊是吧,毕竟现在找份满意的工作也不容易😂
想要实现这个功能需要借助两个包
html2canvas
jspdf
我的实现思路如下
-
利用
dangerouslySetInnerHTML
可以吧后端返回的html
字符串模板渲染,如果不懂可以看我的另外一篇文章总结dangerouslySetInnerHTML的用法 -
利用``html2canvas
把
html模板转化成
canvas` -
利用
canvas
的方法toDataURL()
,该方法返回一个图片URL
路径 -
利用
jspdf
把第三步生成的图片转化成pdf
一:html转化成canvas
import React, {
Component, } from 'react';
import {
Button } from 'antd';
import html2canvas from 'html2canvas';
const jsPDF = require('jspdf');
// 这个是html渲染模板
const HtmlTem = '<div id=domTem style=background-color:pink;width:200px;height:100px>我是Html</div>'
export default class Home extends Component{
htmlToCanvas = () => {
//获取模板HtmlTem的唯一id
const domTem = document.getElementById('domTem');
const createdCanvas = document.createElement('canvas');
const scale = 3;
// canvas整个画布的实际宽高,它与canvas.style.width/height是有区别的,后者是指的浏览器的渲染宽/高
createdCanvas.width= 200 *scale ;
createdCanvas.height = 100 *scale;
createdCanvas.style.marginTop= '150px';
html2canvas(domTem,{
canvas:createdCanvas,
scale, // 生成的canvas在浏览器渲染显示宽高 = 需要转化的html模板的width/height * scale(这里是600px,300px)
}).then(function(canvas) {
// 生成的canvas展示在body
domTem.appendChild(canvas);
});
}
render() {
return(
<div style={
{
width:'600px',height:'600px',border:"1px solid"}