首页 > 解决方案 > jsPDF , TypeError: pdf.fromHTML is not a function in REACT

问题描述

我正在使用下一个代码使用 jsPDF 和一个简单的反应组件将 HTML 转换为 PDF。

import React from 'react';
import { renderToString } from 'react-dom/server';

import jsPDF from 'jspdf';

const styles = {
    fontFamily: 'sans-serif',
    textAlign: 'center',
};
const colstyle = {
    width: '30%',
};
const tableStyle = {
    width: '100%',
};

const Prints = () => (
    <div>
        <h3>Time & Materials Statement of Work (SOW)</h3>
        <h4>General Information</h4>
        <table id='tab_customers' class='table table-striped' style={tableStyle}>
            <colgroup>
                <col span='1' style={colstyle} />
                <col span='1' style={colstyle} />
            </colgroup>
            <thead>
                <tr class='warning'>
                    <th>SOW Creation Date</th>
                    <th>SOW Start Date</th>
                    <th>Project</th>
                    <th>Last Updated</th>
                    <th>SOW End Date</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td>Dec 13, 2017</td>
                    <td>Jan 1, 2018</td>
                    <td>NM Connect - NMETNMCM</td>
                    <td>Dec 13, 2017</td>
                    <td>Dec 31, 2018</td>
                </tr>
            </tbody>
        </table>
        <p>
            This is a Time and Materials Statement of Work between Northwestern Mutual Life
            Insurance Company and Infosys with all general terms and conditions as described
            in the current Master Agreement and its related documents
        </p>
    </div>
);

const print = () => {
    const string = renderToString(<Prints />);
    const pdf = new jsPDF('p', 'mm', 'a4');

    console.log(typeof pdf);
    pdf.fromHTML(string);
    pdf.save('pdf');
};

const Prescription = () => {
    return (
        <div>
            <h1>RECETA</h1>
            <div style={styles}>
                <h2>Start editing to see some magic happen {'\u2728'}</h2>
                <button onClick={print}>print</button>
            </div>
        </div>
    );
};

export default Prescription;

错误是:

TypeError: pdf.fromHTML 不是函数

如何修复错误?

我试图寻找“Typeof”,它显示“Object”。

我想在客户端将 REACT 组件中的 HTML 转换为可下载的 PDF。

标签: reactjsjspdf

解决方案


你的实现是完全正确的。这个问题是因为jspdf版本而发生的。不要使用最新版本,而是使用V1.4.1(请参阅随附的屏幕截图)。

工作演示 - https://codesandbox.io/s/fancy-platform-7f26p?file=/src/App.js

在此处输入图像描述


推荐阅读