You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用JavaScript实现Div的打印与图片下载功能?

实现Div打印与转图片下载功能

完整代码示例

<div class="canvas" id="canvas">stackoverflow</div>

<button onclick="printDiv()">Print</button>
<button onclick="downloadAsImage()">Download</button>

<!-- 引入html2canvas库,用于将Div转为图片 -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>
<script>
// 打印目标Div的函数
function printDiv() {
  const targetDiv = document.getElementById('canvas');
  // 创建临时窗口专门用于打印
  const printWindow = window.open('', '_blank');
  // 把目标Div的内容和样式写入新窗口
  printWindow.document.write(`
    <html>
      <head>
        <title>Print Div</title>
        <style>
          ${getComputedStyle(targetDiv).cssText}
        </style>
      </head>
      <body>${targetDiv.innerHTML}</body>
    </html>
  `);
  printWindow.document.close();
  // 内容加载完成后触发打印,打印完自动关闭窗口
  printWindow.onload = function() {
    printWindow.print();
    printWindow.close();
  };
}

// 将Div转为图片并下载的函数
function downloadAsImage() {
  const targetDiv = document.getElementById('canvas');
  // 用html2canvas把Div渲染成canvas
  html2canvas(targetDiv).then(canvas => {
    // 把canvas转为PNG格式的图片链接
    const imageUrl = canvas.toDataURL('image/png');
    // 创建隐藏的a标签触发下载
    const downloadLink = document.createElement('a');
    downloadLink.href = imageUrl;
    downloadLink.download = 'div-screenshot.png';
    downloadLink.click();
    // 清理临时链接,释放内存
    URL.revokeObjectURL(imageUrl);
  });
}
</script>

功能说明

1. 打印功能

  • 特意把函数名改成printDiv(),避免和浏览器原生的window.print()冲突(原生print会打印整个页面,不符合只打印目标Div的需求)
  • 核心逻辑是创建一个临时新窗口,只放入目标Div的内容和对应的样式,这样打印出来的内容和页面上的Div样式完全一致,不会包含页面上的按钮等无关元素

2. 转图片下载功能

  • 依赖html2canvas库实现HTML元素转图片,这是前端实现这类需求最常用的工具
  • 流程:捕获Div生成canvas画布 → 把画布转成PNG格式的临时链接 → 通过创建隐藏a标签触发浏览器下载 → 最后清理临时链接避免内存浪费

注意事项

  • 如果你的Div包含复杂样式(比如阴影、渐变、跨域图片),可能需要调整html2canvas的配置参数来优化渲染效果
  • 代码里用的是稳定版的html2canvas CDN链接,直接复制就能运行,不需要额外安装

内容的提问来源于stack exchange,提问作者me makky

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 10:52:21