使用html2canvas和jspdf在React中从HTML生成PDF

8
我已经成功地使用React中的html2canvas和jspdf从HTML生成了PDF。但问题是,PDF中呈现的图像被拉伸了。请告诉我这种情况下最好的解决方法是什么?有没有可能直接将HTML呈现为PDF而不使用html2canvas? 以下是我的屏幕截图 输出截图PDF的截图 以下是我的代码
import React, { Component } from 'react';
import * as jsPDF from 'jspdf';
import * as html2canvas from 'html2canvas';


class Invoice extends Component {

handlePdf = () => {
    const input = document.getElementById('page');

    html2canvas(input)
        .then((canvas) => {
            const imgData = canvas.toDataURL('image/png');
            const pdf = new jsPDF('p', 'px', 'a4');
            var width = pdf.internal.pageSize.getWidth();
            var height = pdf.internal.pageSize.getHeight();

            pdf.addImage(imgData, 'JPEG', 0, 0, width, height);
            pdf.save("test.pdf");
        });
};

render() {

    const hrStyle = {
        border: '5px solid rgb(23, 162, 184)'
    };

    const subtotal = [0, ...this.props.inputs.totals];
    const add = (a, b) => a + b;
    const sum = subtotal.reduce(add);

    const tax = sum * 0.1;
    const total = sum + tax;

    return (
        <React.Fragment>
            <div className="col-12 col-lg-6" id="page">
                <div className="container-fluid bg-info text-white">
                    <div className="row">
                        <div className="col text-left m-2">
                            <p>Your Company Name</p>
                            <h2>Invoice</h2>
                        </div>
                        <div className="col text-right">
                            <p>22 Yusen St</p><br />
                            <p>borburn</p><br />
                            <p>WSN</p>
                        </div>
                    </div>
                </div>
                <div className="container-fluid">
                    <div className="row">
                        <div className="col-4">
                            <h5>Billed To</h5>
                            <p>{this.props.inputs.company}</p>
                            <p>{this.props.inputs.address}</p>
                            <p>{this.props.inputs.zip}</p>
                        </div>
                        <div className="col-4">
                            <div>
                                <h5>Invoive number</h5>
                                <p>Za{Math.floor((Math.random() * 100) + 1)}</p>
                            </div>
                            <div>
                                <h5>Date</h5>
                                <p>{this.props.inputs.date}</p>
                            </div>
                        </div>
                        <div className="col-4">
                            <div>
                                <h5>Invoice Totals</h5>
                                <p>${total}</p>
                            </div>
                        </div>
                    </div>
                </div>
                <hr style={hrStyle} />
                <div className="Invoices">
                    <table className="table">
                        <thead>
                            <tr>
                                <th>Description</th>
                                <th>Unit Price</th>
                                <th>Quantity</th>
                                <th>Total</th>
                            </tr>
                        </thead>
                        <tbody>
                            {this.props.inputs.invoices.map((invoice, index) => {
                                return (
                                    <tr key={index}>
                                        <td>{invoice.description}</td>
                                        <td>{invoice.unit}</td>
                                        <td>{invoice.quantity}</td>
                                        <td>{invoice.quantity * invoice.unit}</td>
                                    </tr>
                                )
                            })
                            }
                        </tbody>
                    </table>
                </div>
                <hr />
                <div className="col-12 text-right" >
                    <h5 className="m-2">
                        Subtotal<span className="m-2">${sum}</span>
                    </h5 >
                    <p>Tax(10%)<span className="m-2">${tax.toFixed(2)}</span></p>
                    <h2>Total<span className="m-2">${total}</span></h2>
                </div>
            </div>
            <button onClick={this.handlePdf} className="btn btn-primary btn-lg mx-auto">Generate PDF</button>

        </React.Fragment >
    );
}
}

export default Invoice;
2个回答

3
您可以使用优秀的React-pdf库。它具有良好的性能,并且如果打印文本,则可以进行搜索。
如果您需要在DOM中呈现页面以及PDF,我建议创建自己的primitives并使用这些替代dom标签(div、p等)。通过使用这些基元,您将能够在dom和pdf中呈现相同的组件。
以下是View原语的示例:
import React from 'react';
import { View as ViewPDF } from '@react-pdf/renderer';
import { RENDERING_CONTEXT, withRenderingContext } from '../RenderingContext';

class View extends React.Component {
  render() {
    const { renderingContext, children, className, style } = this.props;
    const isPdf = renderingContext === RENDERING_CONTEXT.PDF;
    return isPdf
      ? <ViewPDF className={className} style={style}>
          {children}
        </ViewPDF>
      : <div className={className} style {style}>
          {children}
        </div>;
  }
}
export default withRenderingContext(View);

RenderingContext是一个上下文,你可以在其中存储当前的渲染环境。然后,您只需要使用设置正确上下文的提供程序包装您的pdf页面。根据渲染上下文,将使用正确的组件(来自react-pdf或dom)。

在您的示例中,您可以简单地用这些基元替换发票中的dom元素。然后,您就可以在pdf文件或dom中呈现发票组件了。


请问您能帮我将我的代码转换成您的方式吗? - Mohamed Mubarak
请注意,使用此推荐库意味着您将不得不解决可能非常繁琐的CSP问题。 - Hawkzey

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接