当前位置:首页 > JavaScript

js实现打印图片

2026-04-04 10:29:41JavaScript

使用Canvas实现图片打印

通过Canvas将图片绘制到画布上,再通过浏览器打印功能输出

function printImage(imageUrl) {
  const canvas = document.createElement('canvas');
  const ctx = canvas.getContext('2d');
  const img = new Image();

  img.crossOrigin = 'Anonymous';
  img.onload = function() {
    canvas.width = img.width;
    canvas.height = img.height;
    ctx.drawImage(img, 0, 0);

    const dataUrl = canvas.toDataURL('image/png');
    const printWindow = window.open('', '_blank');
    printWindow.document.write(`<img src="${dataUrl}" style="max-width:100%">`);
    printWindow.document.close();
    printWindow.focus();
    printWindow.print();
  };
  img.src = imageUrl;
}

使用CSS媒体查询控制打印样式

通过CSS设置打印时的页面样式,隐藏不必要元素

function printImageWithCSS(imageUrl) {
  const printContent = `
    <style>
      @media print {
        body * { visibility: hidden; }
        .print-container, .print-container * { visibility: visible; }
        .print-container { position: absolute; left: 0; top: 0; }
      }
    </style>
    <div class="print-container">
      <img src="${imageUrl}" style="max-width:100%">
    </div>
  `;

  const printWindow = window.open('', '_blank');
  printWindow.document.write(printContent);
  printWindow.document.close();
  printWindow.focus();
  printWindow.print();
}

使用iframe实现静默打印

创建隐藏iframe加载图片后进行打印

js实现打印图片

function printImageViaIframe(imageUrl) {
  const iframe = document.createElement('iframe');
  iframe.style.display = 'none';
  document.body.appendChild(iframe);

  iframe.onload = function() {
    const content = `
      <img src="${imageUrl}" onload="window.print()" style="max-width:100%">
    `;
    iframe.contentDocument.write(content);
    iframe.contentDocument.close();
  };

  iframe.src = 'about:blank';
}

处理跨域图片打印

当图片存在跨域限制时的解决方案

function printCrossOriginImage(imageUrl) {
  fetch(imageUrl)
    .then(response => response.blob())
    .then(blob => {
      const reader = new FileReader();
      reader.onload = function() {
        const printWindow = window.open('', '_blank');
        printWindow.document.write(`<img src="${reader.result}">`);
        printWindow.document.close();
        printWindow.focus();
        printWindow.print();
      };
      reader.readAsDataURL(blob);
    })
    .catch(error => console.error('Error:', error));
}

多图片打印控制

批量打印多张图片的实现方法

js实现打印图片

function printMultipleImages(imageUrls) {
  const printWindow = window.open('', '_blank');
  let html = '<style>img { margin: 10px; max-width: 90%; }</style>';

  imageUrls.forEach(url => {
    html += `<img src="${url}">`;
  });

  printWindow.document.write(html);
  printWindow.document.close();
  printWindow.focus();

  // 添加延时确保图片加载完成
  setTimeout(() => {
    printWindow.print();
  }, 500);
}

注意事项

打印前确保图片已完全加载,避免空白或截断问题

对于大尺寸图片,建议在打印前进行适当缩放处理

某些浏览器可能阻止弹出窗口,需要用户允许弹出权限

考虑添加打印取消和重试的异常处理逻辑

标签: 图片js
分享给朋友:

相关文章

js实现跳转

js实现跳转

使用 window.location 跳转 通过修改 window.location.href 或直接使用 window.location 实现页面跳转,适用于普通跳转或带参数的 URL。 // 方…

js实现日历

js实现日历

实现日历的基本思路 使用JavaScript实现日历的核心是动态生成日期表格,并处理月份切换逻辑。需要计算当前月的天数、起始星期几,并动态渲染到页面上。 获取当前日期信息 通过Date对象获取当前年…

js防抖和节流实现

js防抖和节流实现

防抖(Debounce)的实现 防抖的核心思想是在事件被触发后,延迟执行回调函数。如果在延迟时间内再次触发事件,则重新计时。适用于输入框搜索、窗口大小调整等场景。 function debounce…

js实现图片滚动效果

js实现图片滚动效果

使用CSS动画实现图片滚动 通过CSS的@keyframes和animation属性实现无缝滚动效果。将图片容器设置为横向排列,通过动画平移位置。 <style> .scroll-c…

js实现游标

js实现游标

使用JavaScript实现游标 在JavaScript中,可以通过操作DOM元素的cursor样式属性来实现自定义游标效果。以下是几种常见的实现方法: 修改默认鼠标指针样式 通过CSS的curso…

js实现正交

js实现正交

正交的概念 正交在数学和计算机科学中通常指两个向量垂直或线性无关。在编程中,正交性常被用于设计模块化、低耦合的系统。 向量正交判断 判断两个向量是否正交可以通过点积是否为0来实现: functio…