调用系统 打印操作
这里写一个打印二维码的示例
代码结构
const printQRCode = () => {
// 获取二维码数据
const qrCodeData = qrCodeDataURL.value;
// 打开一个新的窗口
const printWindow = window.open('', '_blank');
// 打开文档以写入内容
printWindow.document.open();
// 写入 HTML 文档的头部
printWindow.document.write('<html><head><title> </title>');
printWindow.document.write('<style>');
// 添加打印样式
printWindow.document.write('@media print {');
printWindow.document.write(' body, html { margin: 0; padding: 0; height: 100%; }');
printWindow.document.write(' img { width: 100%; height: 100%; object-fit: contain; }');
printWindow.document.write(' @page { margin: 0; }');
printWindow.document.write(' @bottom-left { content: ""; }');
printWindow.document.write(' @bottom-right { content: ""; }');
printWindow.document.write('}');
// 结束样式和头部
printWindow.document.write('</style></head><body>');
// 写入二维码图像
printWindow.document.write(`<img id="qrCodeImage" src="${qrCodeData}" />`);
printWindow.document.write('</body></html>');
// 关闭文档以完成写入
printWindow.document.close();
// 当二维码图像加载完成后,打印并关闭窗口
printWindow.document.getElementById('qrCodeImage').onload = function () {
printWindow.print();
printWindow.close();
}
}
详细解读
-
获取二维码数据:
const qrCodeData = qrCodeDataURL.value;这里假设
qrCodeDataURL是一个包含二维码数据的变量(例如,Base64 编码的图像数据)。value属性用于获取该数据。 -
打开新窗口:
const printWindow = window.open('', '_blank');使用
window.open创建一个新的浏览器窗口或标签页。_blank表示在新窗口中打开。 -
文档写入:
printWindow.document.open();这行代码打开新窗口的文档,以便可以开始写入 HTML 内容。
-
写入 HTML 头部和样式:
printWindow.document.write('<html><head><title> </title>'); printWindow.document.write('<style>');开始写入 HTML 文档的头部,包括标题和样式部分。
-
添加打印样式:
printWindow.document.write('@media print { ... }');使用
@media print来定义打印时的样式:body, html { margin: 0; padding: 0; height: 100%; }: 去掉边距和内边距,使内容充满整个页面。img { width: 100%; height: 100%; object-fit: contain; }: 使图像在打印时适应页面,保持比例。@page { margin: 0; }: 设置打印页面的边距为零。@bottom-left和@bottom-right: 这些规则在某些打印机上可能用于设置页脚内容,但这里没有实际内容。
-
结束文档写入:
printWindow.document.write('</style></head><body>');结束样式部分并开始写入文档主体。
-
写入二维码图像:
printWindow.document.write(`<img id="qrCodeImage" src="${qrCodeData}" />`);将二维码图像插入到文档中,使用变量
qrCodeData作为图像的源。 -
关闭文档:
printWindow.document.close();关闭文档,表示所有内容已写入并可以开始渲染。
-
图像加载完成后打印:
printWindow.document.getElementById('qrCodeImage').onload = function () { printWindow.print(); printWindow.close(); }这个部分设置了一个事件处理器,当二维码图像加载完成时,自动调用
printWindow.print()打印窗口内容,然后关闭窗口。
总结
这个 printQRCode 函数的主要功能是创建一个新的浏览器窗口,生成一个包含二维码的 HTML 文档,并在二维码图像加载完成后自动打印该文档。通过使用 CSS 媒体查询,确保打印输出的样式符合预期。