栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

从React Components生成PDF文件

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

从React Components生成PDF文件

以pdf格式进行渲染通常是一件很痛苦的事情,但是可以使用画布解决它。

想法是转换:HTML->画布-> PNG(或JPEG)-> PDF

要实现上述目标,您需要:

  1. html2canvas和
  2. 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上的文本将无法选择。如果这是必需的,您可能会发现本文有所帮助。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/394662.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号