Create pdf from ReactJS

百般思念 提交于 2019-12-19 11:46:13

问题


I am trying to Save ReactJS output(includes visual reports etc..) as PDF file.

I used html2canvas to take screenshot and then used jspdf for converting that to PDF. But the problem is when screen size is reduced(or in mobile view) even screenshots are of small size as it uses DOM styling. So PDF is not properly generated as it should be seen in Full View.


回答1:


You can use dom-to-png plugin by npm to create your image first and then just put that image in your PDF File.

like this

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

Using id

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

JS:

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

Using 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>

        )
    }
}

This function is using the dom to png and jspdf both to print the file. It is also calculating the no of pages so that nothing is missed.

You need to pass the node of your html element which you can get by ref or document.getElementById and that function will calculate the image with the height and width applied.

reference ->

dom-to-image

jspdf



来源:https://stackoverflow.com/questions/47989089/create-pdf-from-reactjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!