从ReactJS创建pdf

问题描述 投票:0回答:1

我试图将ReactJS输出(包括可视化报告等)保存为PDF文件。

我使用html2canvas截取屏幕截图,然后使用jspdf将其转换为PDF。但问题是当屏幕尺寸减小时(或在移动视图中),即使屏幕截图尺寸较小,因为它使用DOM样式。因此,在全视图中应该看到PDF格式不正确。

reactjs jspdf html2canvas
1个回答
2
投票

您可以使用npm的dom-to-png插件先创建图像,然后将该图像放入PDF文件中。

像这样

export function printDetails(ref, fileName: string) {
    const pdf = new jsPDF('p', 'mm', 'a4');
    let height = pdf.internal.pageSize.height;
    let pageHeightInPixels = ref.clientHeight;
    let pageHeightInMM = pageHeightInPixels / 3.78;
    let pages = pageHeightInMM / height;
    const roundOff = Number(pages.toString().split('.')[1].substring(0, 1));
    const pageNo = (roundOff > 0 ? pages + 1 : pages);
    let pageCount = pages < 1 ? 1 : Math.trunc(pageNo);
    let imageHeight = height;
    domtoimage.toPng(ref, {
        height: ref.clientHeight,
        width: 665,
        style: {
            transform: 'unset',
            left: '0%',
            margin: 'unset',
            backgroundColor: 'white',
            maxHeight: '100%'
        },
    })
        .then(function (dataURL) {
            hidePrintPreviewModal();
            for (let i = 1; i <= pageCount; i++) {
                let pdfStartingHeight = height * (i - 1);
                pdf.addImage(dataURL, 'JPEG', 30, -pdfStartingHeight, 160, ref.clientHeight);
                if (i < pageCount) {
                    pdf.addPage();
                }
            }
            pdf.save(`${fileName}.pdf`);
        }).catch(function (error) {
            console.error('oops, something went wrong!', error);
        });
}

使用id

<html>
<body>
<div id="print">
{Whatever you want to print}
</div>
</body>
</html>

JS:

const ref = document.getElementById('print');
printDetails(ref, 'test')

使用ref

class Demo extends React.Component {

    refValue;

    printData = () => {
        const node = React.findDOMNode(this.refValue)
        printDetails(node, 'test');
    }

    render() {
        return (
            <div ref={(value) => { this.refValue = value }}>
                {Whatever you want to print}
    <button onClick={this.printData}>PRint</button>
            </div>

        )
    }
}

此函数使用dom to png和jspdf来打印文件。它还计算页面的数量,以便不遗漏任何内容。

你需要传递你可以通过ref或document.getElementById获得的html元素的节点,该函数将计算应用了高度和宽度的图像。

参考 - >

dom-to-image

jspdf

© www.soinside.com 2019 - 2024. All rights reserved.