前端引用printJS打印

1. 引入 PrintJS

  • 下载或 CDN 引入
    • CDN 方式 :在 HTML 文件的 <head> 标签中,通过 CDN 链接引入 PrintJS 的 CSS 和 JavaScript 文件。
html 复制代码
<head>
    <link href="https://printjs - 4de6.kxcdn.com/print.min.css" rel="stylesheet">
    <script src="https://printjs - 4de6.kxcdn.com/print.min.js"></script>
</head>
  • npm 安装 :如果使用构建工具(如 Webpack)管理项目,可通过 npm 安装 PrintJS。在项目根目录下执行:

    npm install printjs --save

安装完成后,在需要使用的模块中导入:

javascript 复制代码
import printJS from 'printjs';
import 'printjs/print.min.css';

2. 准备打印内容

  • HTML 元素 :在页面中定义要打印的 HTML 元素,例如一个包含报表、发票等内容的 <div> 元素。
html 复制代码
<div id="print - content">
    <h1>销售报表</h1>
    <table>
        <thead>
            <tr>
                <th>产品</th>
                <th>数量</th>
                <th>价格</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td>产品A</td>
                <td>10</td>
                <td>$100</td>
            </tr>
            <tr>
                <td>产品B</td>
                <td>5</td>
                <td>$200</td>
            </tr>
        </tbody>
    </table>
</div>
  • 图片 :准备要打印的图片,可以是本地图片(通过 file 输入框获取)或远程图片(通过 URL 指定)。
html 复制代码
<input type="file" id="image - input">
<img id="remote - image" src="https://example.com/image.jpg" alt="远程图片">
  • PDF 文件:如果要打印 PDF 文件,需确定 PDF 文件的 URL。
html 复制代码
<!-- 假设PDF文件在服务器上的路径 -->
<a href="https://example.com/report.pdf" target="_blank">PDF文件</a>

3. 调用 PrintJS 进行打印

  • 打印 HTML 元素 :创建一个按钮或其他触发机制,在点击事件中调用 printJS 打印指定的 HTML 元素。
html 复制代码
<button onclick="printHTML()">打印HTML内容</button>
<script>
    function printHTML() {
        printJS({
            printable: 'print - content',
            type: 'html',
            header: '销售报表',
            footer: '第 1 页',
            orientation: 'portrait',
            marginTop: 20,
            showModal: true
        });
    }
 // 打印HTML元素的函数
        function printHTML2() {
            printJS({
                // 要打印的HTML元素的ID
                printable: 'html - to - print',
                // 打印类型为HTML
                type: 'html',
                // 自定义页眉内容
                header: 'HTML打印示例',
                // 自定义页脚内容
                footer: '打印时间:' + new Date().toLocaleString(),
                // 打印方向为纵向
                orientation: 'portrait',
                // 上边距设置为15px
                marginTop: 15,
                // 显示打印预览模态框
                showModal: true
            });
        }

        // 打印图片的函数
        function printImage() {
            printJS({
                // 要打印的图片的URL,这里使用了图片元素的src属性值
                printable: document.getElementById('image - to - print').src,
                // 打印类型为图片
                type: 'image',
                // 图片最大宽度设置为250px
                maxWidth: 250,
                // 不扫描样式,保持图片原始样式
                scanStyles: false,
                // 自定义页眉内容
                header: '图片打印示例',
                // 自定义页脚内容
                footer: '示例图片',
                // 显示打印预览模态框
                showModal: true
            });
        }
</script>
  • 打印图片 :为打印图片创建触发事件,根据图片来源设置 printable 属性。
html 复制代码
<button onclick="printLocalImage()">打印本地图片</button>
<button onclick="printRemoteImage()">打印远程图片</button>
<script>
    function printLocalImage() {
        const fileInput = document.getElementById('image - input');
        if (fileInput.files && fileInput.files.length > 0) {
            const file = fileInput.files[0];
            const reader = new FileReader();
            reader.onloadend = function () {
                printJS({
                    printable: reader.result,
                    type: 'image',
                    maxWidth: 300,
                    scanStyles: false,
                    header: '本地图片',
                    showModal: true
                });
            };
            reader.readAsDataURL(file);
        }
    }

    function printRemoteImage() {
        const imageUrl = document.getElementById('remote - image').src;
        printJS({
            printable: imageUrl,
            type: 'image',
            maxWidth: 300,
            scanStyles: false,
            header: '远程图片',
            showModal: true
        });
    }
</script>
  • 打印 PDF 文件 :同样创建触发按钮,设置 printable 为 PDF 文件的 URL。
html 复制代码
<button onclick="printPDF()">打印PDF文件</button>
<script>
    function printPDF() {
        printJS({
            printable: 'https://example.com/report.pdf',
            type: 'pdf',
            header: 'PDF报表',
            showModal: true
        });
    }
</script>

4. 处理打印相关设置

  • 样式设置 :通过 PrintJS 的配置参数自定义打印样式。例如,设置页眉、页脚、边距、打印方向等。
javascript 复制代码
printJS({
    //...其他参数
    header: '自定义页眉',
    footer: '自定义页脚',
    marginTop: 10,
    marginBottom: 10,
    marginLeft: 10,
    marginRight: 10,
    orientation: 'landscape'
});
  • 打印预览 :使用 showModal 参数控制是否显示打印预览模态框。设置为 true 时,会弹出打印预览窗口,用户可以在打印前查看效果并进行调整。
javascript 复制代码
printJS({
    //...其他参数
    showModal: true
});
  • 错误处理 :虽然 PrintJS 相对稳定,但在实际应用中,建议添加错误处理逻辑,以处理可能出现的问题,如网络错误(在打印远程资源时)、文件读取错误(打印本地图片时)等。
javascript 复制代码
try {
    printJS({
        //...打印配置
    });
} catch (error) {
    console.error('打印过程中出现错误:', error);
    // 可以在这里向用户显示友好的错误提示
}

通过以上完整流程,你可以在前端项目中灵活应用 PrintJS 实现各种内容的打印功能,并根据项目需求进行定制化设置。

相关推荐
一 乐1 小时前
婚纱摄影网站|基于ssm + vue婚纱摄影网站系统(源码+数据库+文档)
前端·javascript·数据库·vue.js·spring boot·后端
C_心欲无痕2 小时前
ts - tsconfig.json配置讲解
linux·前端·ubuntu·typescript·json
清沫2 小时前
Claude Skills:Agent 能力扩展的新范式
前端·ai编程
yinuo2 小时前
前端跨页面通信终极指南:方案拆解、对比分析
前端
yinuo3 小时前
前端跨页面通讯终极指南⑨:IndexedDB 用法全解析
前端
xkxnq3 小时前
第二阶段:Vue 组件化开发(第 16天)
前端·javascript·vue.js
烛阴4 小时前
拒绝配置地狱!5 分钟搭建 Three.js + Parcel 完美开发环境
前端·webgl·three.js
xkxnq4 小时前
第一阶段:Vue 基础入门(第 15天)
前端·javascript·vue.js
anyup5 小时前
2026第一站:分享我在高德大赛现场学到的技术、产品与心得
前端·架构·harmonyos
BBBBBAAAAAi5 小时前
Claude Code安装记录
开发语言·前端·javascript