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

求助:React Native中打印react-native-qrcode-svg生成的二维码(非Expo)

打印react-native-qrcode-svg生成的二维码(Android原生开发)

可以通过将SVG二维码转为图片,再使用打印库实现打印,以下是可行方案:

步骤1:安装依赖

需要两个库:捕获视图生成图片的react-native-view-shot,以及处理打印的react-native-print:

npm install react-native-view-shot react-native-print --save
# 或用yarn
yarn add react-native-view-shot react-native-print

步骤2:Android配置

在AndroidManifest.xml中添加必要权限:

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

同步Gradle确保依赖正确链接。

步骤3:实现打印逻辑

通过捕获QRCode组件生成图片,再用HTML包裹图片调用打印API:

import React, { useRef } from 'react';
import { View, Button } from 'react-native';
import QRCode from 'react-native-qrcode-svg';
import { captureRef } from 'react-native-view-shot';
import RNPrint from 'react-native-print';

const QRCodePrinter = () => {
  const qrRef = useRef(null);

  const printQR = async () => {
    try {
      // 捕获二维码组件为PNG图片
      const imgUri = await captureRef(qrRef, {
        format: 'png',
        quality: 1.0,
      });

      // 构造打印用的HTML,可自定义样式
      const printHtml = `
        <html>
          <body style="display: flex; justify-content: center; align-items: center; height: 100vh; margin: 0;">
            <img src="${imgUri}" style="width: 200px; height: 200px;" />
          </body>
        </html>
      `;

      // 触发打印
      await RNPrint.print({
        html: printHtml,
      });
    } catch (err) {
      console.error('打印出错:', err);
    }
  };

  return (
    <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
      <QRCode
        ref={qrRef}
        value="你的二维码内容"
        size={200}
      />
      <Button title="打印二维码" onPress={printQR} />
    </View>
  );
};

export default QRCodePrinter;

备选方案:直接用SVG的toDataURL

如果不想用react-native-view-shot,可以利用react-native-qrcode-svg的原生SVG引用获取base64:

// 替换捕获逻辑
const svgRef = useRef(null);

const printQR = async () => {
  try {
    const dataUrl = await svgRef.current.toDataURL();
    const printHtml = `
      <html>
        <body style="display: flex; justify-content: center; align-items: center; height: 100vh;">
          <img src="${dataUrl}" style="width: 200px; height: 200px;" />
        </body>
      </html>
    `;
    await RNPrint.print({ html: printHtml });
  } catch (err) {
    console.error(err);
  }
};

// 组件部分
<QRCode ref={svgRef} value="你的内容" size={200} />

注意事项

  • 确保测试设备/模拟器已连接可用打印机(Android模拟器可使用虚拟打印机)
  • 可自定义HTML样式调整二维码大小、添加说明文字等
  • 如果捕获图片失败,可将QRCode包裹在一个<View>中,捕获该View的引用

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 16:15:31