Vue页面生成PDF后调起浏览器打印

一、安装依赖

首先,需要安装 html2canvas 和 jsPDF 库。

javascript 复制代码
npm install html2canvas jspdf

二、创建公共方法+引入

在utils文件夹下创建两个文件分别为pdfExport.js和printPDF.js,代码如下:

  • pdfExport.js
javascript 复制代码
import html2canvas from 'html2canvas';
import jsPDF from 'jspdf';

export const exportToPDF = async (elementId) => {
    console.log('Exporting PDF...');
    const content = document.getElementById(elementId);
    if (!content) {
        console.error(`Element with id ${elementId} not found.`);
        return;
    }

    try {
        const canvas = await html2canvas(content);
        const imgData = canvas.toDataURL('image/png');
        const pdf = new jsPDF({
            orientation: 'portrait',
            unit: 'mm',
            format: 'a4'
        });

        // 获取页面尺寸
        const pageWidth = pdf.internal.pageSize.getWidth();
        const pageHeight = pdf.internal.pageSize.getHeight();
        
        // 计算图片宽高比
        const imgWidth = pageWidth;
        const imgHeight = (canvas.height * imgWidth) / canvas.width;

        // 分页添加图片
        let position = 0;
        while (position < imgHeight) {
            pdf.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight);
            position += pageHeight;
            if (position < imgHeight) {
                pdf.addPage();
            }
        }

        // 将 PDF 转换为 Blob 对象
        const blob = pdf.output('blob');

        console.log('PDF Blob generated:', blob); // 打印生成的 Blob 对象信息

        return blob; // 返回生成的 Blob 对象,供后续使用
    } catch (error) {
        console.error('导出 PDF 失败:', error);
        throw error; // 抛出异常供调用者处理
    }
};
  • printPDF.js
javascript 复制代码
export const printPDF = (blob) => {
    try {
        const url = URL.createObjectURL(blob);
        console.log('PDF Blob URL:', url); // 打印生成的 Blob URL

        // 创建一个隐藏的 iframe
        const iframe = document.createElement('iframe');
        iframe.style.position = 'fixed';
        iframe.style.right = '0';
        iframe.style.bottom = '0';
        iframe.style.width = '0';
        iframe.style.height = '0';
        iframe.style.border = 'none';

        document.body.appendChild(iframe);

        // 设置 iframe 的 src 属性为 PDF 文件的 URL
        iframe.src = url;

        // 加载完成在进行打印操作,确保 PDF 加载完成
        iframe.onload = function() {
            iframe.contentWindow.focus();
            iframe.contentWindow.print();

            // 打印完成后移除 iframe 和释放 URL
            setTimeout(() => {
                // document.body.removeChild(iframe);
                URL.revokeObjectURL(url);
            }, 500)
        };
    } catch (error) {
        console.error('打印 PDF 出错:', error);
        throw error;
    }
};

创建好后在main.js中引入方法

javascript 复制代码
import { exportToPDF } from '../utils/pdfExport';
Vue.prototype.$exportToPDF = exportToPDF;

import { printPDF } from '../utils/printPDF';
Vue.prototype.$printPDF = printPDF;

三、使用

  • html
javascript 复制代码
<template>
	<div>
		<!-- 打印按钮 -->
		<span class="mr20" @click="printPageFn">打印页面</span>
		<!-- 需要打印的页面内容,可以是任意div,设置id就可以 -->
		<router-view id="contentToExport"/>
	</div>
</template>
  • Javascript
javascript 复制代码
// 打印页面
printPageFn(){
	//注意传入的id是否与页面设置的id一致
	this.$exportToPDF('contentToExport').then((blob) => {
		this.$printPDF(blob);
	});
},
相关推荐
10年前端老司机4 小时前
React无限级菜单:一个项目带你突破技术瓶颈
前端·javascript·react.js
前端小趴菜059 小时前
React - createPortal
前端·vue.js·react.js
晓13139 小时前
JavaScript加强篇——第四章 日期对象与DOM节点(基础)
开发语言·前端·javascript
烛阴10 小时前
JavaScript函数参数完全指南:从基础到高级技巧,一网打尽!
前端·javascript
chao_78911 小时前
frame 与新窗口切换操作【selenium 】
前端·javascript·css·selenium·测试工具·自动化·html
天蓝色的鱼鱼11 小时前
从零实现浏览器摄像头控制与视频录制:基于原生 JavaScript 的完整指南
前端·javascript
三原12 小时前
7000块帮朋友做了2个小程序加一个后台管理系统,值不值?
前端·vue.js·微信小程序
白仑色12 小时前
完整 Spring Boot + Vue 登录系统
vue.js·spring boot·后端
阳火锅13 小时前
Vue 开发者的外挂工具:配置一个 JSON,自动造出一整套页面!
javascript·vue.js·面试
每天吃饭的羊13 小时前
react中为啥使用剪头函数
前端·javascript·react.js