html导出PDF

一、说明

一、流程
HTML页面 ---> 转换图片 ----> 转换PDF
二、引入js
前提需引入 html2canvas.js jspdf.umd.js
三、导出问题说明
PC端可以正常导出
手机端需要后台中转一下
四、依赖 html2canvas.js jspdf.umd.js

二、方法使用

/**
 * html转pdf
 * @param  elementId 需要输出PDF的页面id
 * @param successCallback 函数成功回调
 * @param errorCallback 函数失败回调
 * @returns {Object}
 *      pdf {Object} - 返回选定PDFjs类
 *      canvas { Object} - 返回canvas 类
 *      canvasUrl {String} - 返回可预览的base64
 */
exportHtmlPDF('pdf-box',(res)=>{
        const { canvasUrl,pdf,canvas} = res
        // // 导出PDF  pdf.save(`报名表${this.htmlFormatDate(new Date())}`)
        // // console.log(canvas.toDataURL("image/png")) // 图片预览地址
        // // var pdfData = pdf.output('datauristring')//获取到base64 的pdf
        this.pdf = pdf
        this.canvasUrl = canvasUrl
 })

三、示例

<div id="pdf-box" class="bg-gray-50">
    <h2 class="text-3xl font-bold pb-8 text-center">{{title}}</h2>
    <table class="table-border w-full">
        <colgroup>
            <col class="w-1/12">
            <col class="w-1/12">
            <col class="w-1/12">
            <col class="w-1/12">
            <col class="w-1/12">
            <col class="w-1/12">
            <col class="w-1/12">
            <col class="w-1/12">
            <col class="w-1/12">
            <col class="w-1/12">
            <col class="w-1/12">
            <col class="w-1/12">
        </colgroup>
        <tbody>
        <tr>
            <td colspan="2">姓名:</td>
            <td colspan="4">{{ pdfInfo.name }}</td>
            <td colspan="2">日期:</td>
            <td colspan="4">{{ pdfInfo.idCard }}</td>
        </tr>
        <tr>
            <td colspan="2">职务:</td>
            <td colspan="4">{{ pdfInfo.sex }}</td>
            <td colspan="2">部门:</td>
            <td colspan="4"  >{{ pdfInfo.education }}</td>
        </tr>
        <tr>
            <td colspan="1"  class="text-lg font-bold" >工作汇总</td>
            <td colspan="11" class="text-left" style="text-align: left;">{{ pdfInfo.major }}</td>
        </tr>
        <tr>
            <td :rowspan="pdfInfo.logList.length" class="text-lg font-bold">日志内容</td>
            <td colspan="2">{{ pdfInfo.logList[0].type }}</td>
            <td colspan="9">
                <p v-for="(log, index2) in pdfInfo.logList[0].records" :key="index2" style="text-align: left">{{ log }}</p>
            </td>
        </tr>
 
        <tr v-for="(item, index) in pdfInfo.logList.slice(1)" :key="index">
            <td colspan="2">{{ item.type }}</td>
            <td colspan="9">
                <p v-for="(log, index2) in item.records" :key="index2" style="text-align: left">{{ index2 + 1 }}、{{ log }}</p>
            </td>
        </tr>
 
 
        </tbody>
    </table>
</div>

四、js方法

// 引入 html2canvas.js
// 引入 jspdf.umd.js
 
/**
 * html转pdf
 * @param  elementId 需要输出PDF的页面id
 * @param successCallback 函数成功回调
 * @param errorCallback 函数失败回调
 * @returns {Object}
 *      pdf {Object} - 返回选定PDFjs类
 *      canvas { Object} - 返回canvas 类
 *      canvasUrl {String} - 返回可预览的base64
 */
 
/**
 * PDF 下载
 * pdf.save(`报名表${this.htmlFormatDate(new Date())}`)
 */
function exportHtmlPDF(elementId, successCallback,errorCallback){
    /**
     * 是否是函数
     * @returns {Boolean}
     */
    function htmlIsFunction(fun){
        if (Object.prototype.toString.call(fun) === "[object Function]") {
            return true
        } else {
            return false
        }
    }
    const element = document.getElementById(elementId)
    html2canvas(element, {
        scale: 1,
        backgroundColor: '#ffffff',
        allowTaint: true,
        useCORS: true,
        scrollY: 0,
        scrollX: 0
    }).then((canvas) => {
        const pdf = new jspdf.jsPDF("p", "mm", "a4") // A4纸,纵向
        // const pdf = new jspdf.jsPDF("l", "mm", "a4") // A4纸,横向
        const ctx = canvas.getContext("2d")
        const a4w = 190;
        const a4h = 257 // A4大小,210mm x 297mm,四边各保留20mm的边距
        const imgHeight = Math.floor(a4h * canvas.width / a4w) // 按A4显示比例换算一页图像的像素高度
        let renderedHeight = 0
        // this.canvasUrl = canvas.toDataURL("image/png")
        while (renderedHeight < canvas.height) {
            const page = document.createElement("canvas")
            page.width = canvas.width
            page.height = Math.min(imgHeight, canvas.height - renderedHeight) // 可能内容不足一页
 
            // 用getImageData剪裁指定区域,并画到前面创建的canvas对象中
            page.getContext("2d").putImageData(ctx.getImageData(0, renderedHeight, canvas.width, Math.min(imgHeight, canvas.height - renderedHeight)), 0, 0)
            pdf.addImage(page.toDataURL("image/jpeg", 1.0), "JPEG", 10, 10, a4w, Math.min(a4h, a4w * page.height / page.width)) // 添加图像到页面,保留10mm边距
 
            renderedHeight += imgHeight
            if (renderedHeight < canvas.height) { pdf.addPage() } // 如果后面还有内容,添加一个空页
            // delete page;
        }
        if (successCallback && htmlIsFunction(successCallback)) {
            successCallback({pdf,canvas,canvasUrl:canvas.toDataURL("image/png"),});
        }
        // pdf.save(title + time)
    }).catch((error)=>{
        if (errorCallback && htmlIsFunction(errorCallback)) {
            errorCallback(error);
        }
    });
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值