以pdf格式进行渲染通常是一件很痛苦的事情,但是可以使用画布解决它。
想法是转换:HTML->画布-> PNG(或JPEG)-> PDF
要实现上述目标,您需要:
- html2canvas和
- jsPDF
import React, {Component, PropTypes} from 'react'; // download html2canvas and jsPDF and save the files in app/ext, or somewhere else // the built versions are directly consumable // import {html2canvas, jsPDF} from 'app/ext'; export default class Export extends Component { constructor(props) { super(props); } printdocument() { const input = document.getElementById('divToPrint'); html2canvas(input) .then((canvas) => { const imgData = canvas.toDataURL('image/png'); const pdf = new jsPDF(); pdf.addImage(imgData, 'JPEG', 0, 0); // pdf.output('dataurlnewwindow'); pdf.save("download.pdf"); }) ; } render() { return (<div> <div className="mb5"> <button onClick={this.printdocument}>Print</button> </div> <div id="divToPrint" className="mt4" {...css({ backgroundColor: '#f5f5f5', width: '210mm', minHeight: '297mm', marginLeft: 'auto', marginRight: 'auto' })}> <div>Note: Here the dimensions of div are same as A4</div> <div>You Can add any component here</div> </div> </div>); } }由于无法导入所需文件,因此该代码段在这里无法正常工作。
此答案)中使用了一种替代方法,其中删除了中间步骤,您可以简单地从HTML转换为PDF。jsPDF文档中也可以选择执行此操作,但是从个人观察,我认为将dom首先转换为png时可以实现更好的准确性。
更新0:2018年9月14日
用这种方法创建的pdf上的文本将无法选择。如果这是必需的,您可能会发现本文有所帮助。



