我一直在构建一个轮询应用程序。人们能够创建他们的民意调查并获取有关他们提出的问题的数据。我想添加功能,以允许用户以PDF的形式下载结果。
例如,我有两个组件负责获取问题和数据。
<QuestionBox /> <ViewCharts />
我正在尝试将两个组件都输出到PDF文件中。然后,用户可以下载该PFD文件。我发现了一些允许在组件内部呈现PDF的软件包。但是,我找不到能从包含虚拟DOM的输入流中生成PDF的文件。如果我想从头开始实现此目标,应该采用哪种方法?
以pdf格式进行渲染通常是一件很痛苦的事情,但是可以使用画布解决它。
想法是转换:HTML->画布-> PNG(或JPEG)-> PDF
要实现上述目标,您需要:
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上的文本将无法选择。如果这是必需的,您可能会发现本文有所帮助。