html导出pdf

在最近做项目的时候,遇到一个需求需要能预览简历并导出成pdf,这里我记录下将html导出pdf的方法。

引入导出pdf需要用到的html2canvas与jspdf:

  • npm install html2canvas
  • npm install jspdf

这里我封装成一个方法在需要用到的地方直接调用就可以,下面直接上代码:

import html2Canvas from 'html2canvas';
import JsPDF from 'jspdf';

/**
 * 处理导出pdf
 * */
export const handleExportPdfByHtml = (selectors, title) => {
    html2Canvas(document.querySelector(selectors), {
        allowTaint: true,
    }).then(canvas => {
        // DOM生成base64图片
        const base64Image = canvas.toDataURL('image/jpeg', 1);
        // 图片的大小
        const contentWidth = canvas.width;
        const contentHeight = canvas.height;
        // 每一页的尺寸 - A1尺寸
        const pageWidth = 594;
        const pageHeight = 841;
        // DOM缩放比例后的高度
        const imageHeight = pageWidth / contentWidth * contentHeight;
        // 创建PDF对象
        const PDF = new JsPDF('p', 'pt', 'a4');
        // 当前高度只需要打印一页
        if (imageHeight < pageHeight) {
            PDF.addImage(base64Image, 'JPEG', 0, 0, pageWidth, imageHeight)
        }
        // 高度过高打印多页
        else {
            let tempHeight = imageHeight;
            for(let i = 0; tempHeight > 0; i++) {
                PDF.addImage(base64Image, 'JPEG', 0, -i * pageHeight, pageWidth, imageHeight);
                tempHeight -= pageHeight;
                if(tempHeight > 0) {
                    PDF.addPage();
                }
            }
        }
        PDF.save(title + '.pdf')
    });
}

 使用:

<template>
	<div style="width: 700px; margin: auto;">
		<div id="content" style="background: #0BB7AF;">
			<p v-for="(item, index) in 100" :key="index">内容{{index + 1}}</p>
		</div>

		<button @click="handleExportPdfByHtml('#content', '文件标题')">按钮</button>
	</div>
</template>

<script lang="ts">
import { defineComponent } from 'vue';
import { handleExportPdfByHtml } from '@/utils/common';

export default defineComponent({
	components: {},
	setup() {
		return {
			handleExportPdfByHtml,
		}
	}
});
</script>

效果:

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值