react html div导出pdf,从React组件生成PDF文件

Shivek Khura..

66

渲染反应因为pdf通常很痛苦,但是有一种方法可以使用canvas.

想法是转换: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 (

Print

backgroundColor: '#f5f5f5',

width: '210mm',

minHeight: '297mm',

marginLeft: 'auto',

marginRight: 'auto'

})}>

Note: Here the dimensions of div are same as A4
You Can add any component here
);

}

}

该片段在此处不起作用,因为未导入所需的文件.

在这个答案中使用了另一种方法,其中中间步骤被删除,您可以简单地从HTML转换为PDF.在jsPDF文档中也可以选择这样做,但是从个人观察来看,我觉得当dom首先转换为png时可以获得更好的准确性.

更新0:2018年9月14日

此方法创建的pdf上的文本将无法选择.如果这是一项要求,您可能会发现本文很有帮助.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值