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

求助:如何实现无线标签打印机直接打印指定DIV内容

解决PHP页面DIV内容打印到62mm无线标签打印机的方案

Hey there, I feel your pain—spending a whole day stuck on a printing issue is such a frustrating grind. Let’s break this down into actionable, tested steps that should get your QR code and extra info onto that 62mm continuous label printer.

方案1:浏览器端打印(最简单直接,优先尝试)

Most wireless label printers play nicely with browser-based printing if you nail the paper size and styling. Here’s how to target just your #unique_name div and format it perfectly for 62mm width:

第一步:添加打印专用CSS

Drop this into your page’s stylesheet to hide non-print content and force the div to fit the label size:

/* 全局打印样式重置 */
@media print {
  body * {
    visibility: hidden;
  }
  #unique_name, #unique_name * {
    visibility: visible;
  }
  #unique_name {
    position: absolute;
    left: 0;
    top: 0;
    width: 62mm; /* 精确匹配打印机纸张宽度 */
    margin: 0;
    padding: 4mm; /* 可选:加内边距避免内容贴标签边缘 */
  }
  /* 设置打印页面为连续纸模式 */
  @page {
    size: 62mm auto; /* auto让高度自适应内容,适配连续纸 */
    margin: 0;
  }
}

第二步:添加打印触发按钮/JS

Add a simple button to trigger the print dialog, and ensure styles apply correctly:

<button onclick="printLabel()">打印标签</button>

<script>
function printLabel() {
  // 强制浏览器聚焦,避免样式不生效
  window.focus();
  // 打开系统打印对话框
  window.print();
}
</script>

关键注意事项:

  • When the print dialog pops up, make sure you select your wireless label printer and set the paper size to "Custom" or explicitly 62mm width.
  • If your QR code looks blurry, use a vector SVG version instead of a raster PNG—this scales perfectly for printing.

方案2:PHP直接发送打印指令(适合后台触发或精准控制)

If browser printing fails (e.g., the printer doesn’t show up in the dialog, or you need to print without user input), you can convert the div to an image and send it directly to the printer using the ESC/POS protocol (supported by almost all label printers).

第一步:将DIV内容转为图片

Use frontend JS to turn the #unique_name div into a canvas/image, then send it to your PHP backend:

function convertDivToImage() {
  const div = document.getElementById('unique_name');
  html2canvas(div).then(canvas => {
    // 把canvas转成base64格式的图片
    const imgData = canvas.toDataURL('image/png');
    // 发送到PHP接口
    fetch('print_label.php', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
      },
      body: 'image=' + encodeURIComponent(imgData)
    });
  });
}

Note: You’ll need the html2canvas library for this—just include it via a script tag in your page (no external links needed, download it locally if preferred).

第二步:PHP后端发送到打印机

In print_label.php, process the image, resize it to fit 62mm (based on your printer’s DPI), and send ESC/POS commands to the printer’s IP:

<?php
// 获取前端传来的图片数据
$imgData = $_POST['image'];
$imgData = str_replace('data:image/png;base64,', '', $imgData);
$imgData = base64_decode($imgData);

// 保存为临时图片文件
$tempFile = tempnam(sys_get_temp_dir(), 'label');
file_put_contents($tempFile, $imgData);

// 打印机配置:替换为你的打印机IP和端口(通常是9100)
$printerIp = '192.168.1.100';
$printerPort = 9100;
// 打印机DPI:常见值为203或300,根据你的设备调整
$printerDpi = 203;
// 62mm转像素:1mm = DPI / 25.4
$labelWidthPx = round(62 * ($printerDpi / 25.4));

// 建立socket连接到打印机
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if (socket_connect($socket, $printerIp, $printerPort)) {
  // 初始化打印机
  socket_write($socket, "\x1B\x40");
  // 打印后走纸到下一个标签(调整数值控制走纸长度)
  socket_write($socket, "\x1B\x64\x06");

  // 推荐用专门的ESC/POS库处理图片打印(比如php-escpos)
  // 以下是简化示例,实际使用库会更可靠
  $img = imagecreatefrompng($tempFile);
  imagefilter($img, IMG_FILTER_GRAYSCALE);
  // 这里需要根据打印机DPI调整图片尺寸并转为位图数据
  // 用php-escpos的话一行代码就能搞定:$printer->bitImage($img);

  socket_close($socket);
}

// 删除临时文件
unlink($tempFile);
?>

关键注意事项:

  • Find your printer’s IP address via its settings page or companion app, and confirm it’s on the same network as your server/PC.
  • Use a dedicated ESC/POS library like php-escpos to avoid low-level command errors—it handles image resizing and printer compatibility way better than writing raw commands.
  • Double-check your printer’s DPI: using the wrong value will make content too big or too small.

常见排查点

  • If the printer doesn’t respond: Verify network connectivity, ensure port 9100 isn’t blocked by a firewall, and confirm the printer is set to accept network printing.
  • If content is cut off: Adjust padding/margins in the CSS or image resize logic to fit exactly within 62mm width.
  • Blurry QR code: Use a vector SVG or generate a high-resolution PNG (matching your printer’s DPI).

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 09:12:26