我一直在开发一个投票应用程序.他们可以创建关于他们的问题的调查数据.我想添加功能,让用户下载PDF格式的结果.

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

<QuestionBox />
<ViewCharts />

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

推荐答案

渲染pdf通常是一件痛苦的事情,但有一种方法可以通过使用画布来解决.

The idea is to convert : HTML -> Canvas -> PNG (or 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>);
  }
}

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

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

Update 0: September 14, 2018

通过这种方法创建的PDF上的文本将不可 Select .如果这是一个要求,你可能会发现this article个有用的.

Reactjs相关问答推荐

使用React.lazy组件防止 children 在数据更改时重新加载

react-native-markdown-显示样式表

如何在没有 node 模块的情况下利用外部Java脚本文件制作OWL carousel

如何将图像(在代码中称为自己)定位在蓝色圈内的点上?我正在使用material UI和Reaction

为多租户SSO登录配置Azure AD应用程序

svg每条路径上的波浪动画

React,当我调用handleSubmit()函数时,我正在将application/json和multiform/data中的数据发送到后端,但student_image中没有数据:null

生产部署:控制台中 Firebase 无效 api 密钥错误

我无法通过 useContext 显示值

修改React数据表扩展组件

Reactjs:MUI5:MobileDateTimePicker API:如何自定义日历中的文本

useMemo 依赖项的行为

React - 如何重定向页面以显示数据修改?

如何渲染子路径并触发react 路由父加载器?

如何在不重新加载页面的情况下加载新添加的数据?

next js 13 在获取中使用标头时动态渲染而不是静态渲染?

在 Reactjs 中状态发生变化时渲染一个新组件而不替换旧组件

react-query、react-hook-form 和表单验证

在 React 中,为什么不能向空片段添加键(短语法)?

设置 Material UI 表格默认排序