vue中将网页以pdf格式下载

 
 

1、下载 html2canvas和jspdf  两个插件

yarn add html2canvas jspdf

2、html2canvas 和 jspdf github地址

https://github.com/niklasvh/html2canvas

https://github.com/MrRio/jsPDF

html2canvas官方示例:http://html2canvas.hertzen.com/

3.pdf多页打印

 
 
<template>
    <div class="pdf-wrap" id="pdfWrap">
        <button v-on:click="getPdf">点击下载PDF</button>
        <div class="pdf-dom" id="pdfDom"></div>
    </div>
</template>
<style lang="scss" scoped>

</style>
<script type="text/ecmascript-6">
    import html2canvas from 'html2canvas'
 import JSPDF from 'jspdf'

 export default {
        name: 'home',

        components: {
            chead
        },
        data () {
            return {
                msg: 'home'
            }
        },
        methods: {
            getPdf: () => {
                let pdfDom = document.querySelector('#home')
                html2canvas(pdfDom, {
                    onrendered: function (canvas) {
                        let contentWidth = canvas.width
                        let contentHeight = canvas.height
                        let pageHeight = contentWidth / 592.28 * 841.89
                        let leftHeight = contentHeight
                        let position = 0
                        let imgWidth = 595.28
                        let imgHeight = 592.28 / contentWidth * contentHeight

                        let pageData = canvas.toDataURL('image/jpeg', 1.0)

                        let PDF = new JSPDF('', 'pt', 'a4')

                        if (leftHeight < pageHeight) {
                            PDF.addImage(pageData, 'JPEG', 0, 0, imgWidth, imgHeight)
                        } else {
                            while (leftHeight > 0) {
                                PDF.addImage(pageData, 'JPEG', 0, position, imgWidth, imgHeight)
                                leftHeight -= pageHeight
                                position -= 841.89
                                if (leftHeight > 0) {
                                    PDF.addPage()
                                }
                            }
                        }
                        PDF.save('123.pdf')
                    }
                })
                html2canvas()
            }
        }  
    }

</script>

猜你喜欢

转载自blog.csdn.net/qq_30227429/article/details/80581607