前端引用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 实现各种内容的打印功能,并根据项目需求进行定制化设置。

相关推荐
xinyu_Jina8 小时前
PaperStudio:WYSIWYG文档的Web实现——从CSS Print到客户端PDF生成的技术解析
前端·css·pdf
默默学前端8 小时前
html列表标签及css列表属性
前端·css·html5
天天扭码17 小时前
如何实现流式输出?一篇文章手把手教你!
前端·aigc·ai编程
前端 贾公子17 小时前
vue移动端适配方案 === postcss-px-to-viewport
前端·javascript·html
GISer_Jing18 小时前
AI营销增长:4大核心能力+前端落地指南
前端·javascript·人工智能
明远湖之鱼19 小时前
一种基于 Service Worker 的渐进式渲染方案的基本原理
前端
前端小端长19 小时前
Vue 中 keep-alive 组件的原理与实践详解
前端·vue.js·spring
FeelTouch Labs19 小时前
Nginx核心架构设计
运维·前端·nginx