从 React Components 生成 PDF 文件 [英] Generating a PDF file from React Components

查看:33
本文介绍了从 React Components 生成 PDF 文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在构建一个投票应用程序.人们能够创建他们的民意调查并获取有关他们提出的问题的数据.我想添加让用户以 PDF 格式下载结果的功能.

例如,我有两个组件负责抓取问题和数据.

<视图图表/>

我正在尝试将两个组件输出到一个 PDF 文件中.然后用户可以下载这个 PFD 文件.我发现了一些允许在组件内呈现 PDF 的包.但是,我未能找到可以从包含虚拟 DOM 的输入流生成 PDF 的方法.如果我想从头开始实现这一目标,我应该遵循什么方法?

解决方案

将 react 渲染为 pdf 通常很痛苦,但有一种使用 canvas 的方法.

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

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

  1. html2canvas &
  2. jsPDF

从'react'导入React, {Component, PropTypes};//下载 html2canvas 和 jsPDF 并将文件保存在 app/ext 或其他地方//构建的版本可直接消费//从app/ext"导入 {html2canvas, jsPDF};导出默认类导出扩展组件{构造函数(道具){超级(道具);}打印文档(){const input = document.getElementById('divToPrint');html2canvas(输入).then((画布) => {const imgData = canvas.toDataURL('image/png');const pdf = 新的 jsPDF();pdf.addImage(imgData, 'JPEG', 0, 0);//pdf.output('dataurlnewwindow');pdf.save("下载.pdf");});}使成为() {返回 (<div><div className="mb5"><button onClick={this.printDocument}>打印</button>

<div id="divToPrint" className="mt4" {...css({背景颜色:'#f5f5f5',宽度:'210mm',最小高度:'297mm',marginLeft: '自动',marginRight: '自动'})}><div>注意:这里div的尺寸和A4一样</div><div>您可以在此处添加任何组件</div>

);}}

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

这个答案中使用了另一种方法,其中中间步骤被删除,您可以简单地从 HTML 转换为 PDF.jsPDF文档中也有这个选项,但是从个人观察,我觉得先把dom转成png,准确率更高.

更新 0:2018 年 9 月 14 日

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

I have been building a polling application. People are able to create their polls and get data regarding the question(s) they ask. I would like to add the functionality to let the users download the results in the form of a PDF.

For example I have two components which are responsible for grabbing the question and data.

<QuestionBox />
<ViewCharts />

I'm attempting to output both components into a PDF file. The user can then download this PFD file. I have found a few packages that permit the rendering of a PDF inside a component. However I failed to find one that can generate PDF from an input stream consisting of a virtual DOM. If I want to achieve this from scratch what approach should I follow ?

解决方案

Rendering react as pdf is generally a pain, but there is a way around it using canvas.

The idea is to convert : HTML -> Canvas -> PNG (or JPEG) -> PDF

To achieve the above, you'll need :

  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>);
  }
}

The snippet will not work here because the required files are not imported.

An alternate approach is being used in this answer, where the middle steps are dropped and you can simply convert from HTML to PDF. There is an option to do this in the jsPDF documentation as well, but from personal observation, I feel that better accuracy is achieved when dom is converted into png first.

Update 0: September 14, 2018

The text on the pdfs created by this approach will not be selectable. If that's a requirement, you might find this article helpful.

这篇关于从 React Components 生成 PDF 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
其他开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆