Create pdf from ReactJS

前端 未结 1 1599
走了就别回头了
走了就别回头了 2021-01-17 01:48

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

I used html2canvas to take screenshot and then used jspdf f

相关标签:
1条回答
  • 2021-01-17 02:31

    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

    0 讨论(0)
提交回复
热议问题