在前端开发过程中,将html页面下载为pdf文件的思路:使用html2canvas
和jsPDF
两个库,大致流程就是首先使用html2canvas库将组件内容转换为图像,然后使用jsPDF库将图像生成为PDF文件。
安装html2canvas库
npm install html2canvas
安装jsPDF库
npm install jsPDF
以下代码展示了,在React框架下,将子组件的HTML内容转换为PDF文件的代码
- 父组件代码:
import React, { Component } from 'react';
import ReactDOM from "react-dom";
import ChildComponent from "./ChildComponent";
import html2canvas from "html2canvas";
import jsPDF from "jspdf";
import {Button} from "antd";
class MyDemo extends Component {
downloadPDF = () => {
const html = ReactDOM.findDOMNode(this.childRef);
//使用html2canvas将子组件内容转换为图像
html2canvas(html, {allowTaint:true, scale: 2, dpi: 500}).then((canvas) => {
const imgData = canvas.toDataURL('src/images/pdfFile.png');
//创建一个新的jsPDF实例
const pdf = new jsPDF({
orientation: 'portrait',
unit: 'mm',
format: 'a4',
});
const contentWidth = canvas.width;
const contentHeight = canvas.height;
const pageHeight = (contentWidth / 592.28) * 841.89
const imgWidth = 595.28
const imgHeight = (592.28 / contentWidth) * contentHeight
//将图像添加到PDF中
pdf.addImage(imgData, 'PNG', 0, 0, imgWidth, imgHeight);
//保存PDF文件
pdf.save('PDF文件名.pdf');
})
}
render() {
return (
<div>
<ChildComponent
ref={(ref) => this.childRef = ref}
/>
<Button onClick={this.downloadPDF}>下载PDF文件</Button>
</div>
);
}
}
export default MyDemo;
- 子组件代码:
import React, { Component } from 'react';
class ChildComponent extends Component {
constructor(props) {
super(props);
}
render() {
return (
<div style={{padding: 50}}>
<div>子组件</div>
<div>子组件</div>
<div>子组件</div>
<div>子组件</div>
</div>
)
}
}
export default ChildComponent
PDF文件下载效果