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

C# 基于ZXing.Net生成SVG二维码并实现无物理文件直接下载

解决方案

ZXing.NET的BarcodeWriterSvg.Write()方法返回的是SvgImage类型对象,你可以直接通过其ToString()方法获取完整的SVG格式XML文本,不需要像位图一样调用Save方法转流,直接把文本编码为字节数组写入响应即可,无需生成本地文件。

完整可用代码示例

Color barcodeColor = System.Drawing.ColorTranslator.FromHtml(colorHex);

BarcodeWriterSvg barcodeWriter = new BarcodeWriterSvg
{
    Format = BarcodeFormat.QR_CODE,
    Options = new EncodingOptions
    {
        Width = width,
        Height = height,
        PureBarcode = true
    },
    Renderer = new SvgRenderer
    {
        Foreground = barcodeColor
    }
};
// 生成SVG二维码对象
var svgQrCode = barcodeWriter.Write(qrContent);
// 将SVG文本转为UTF8编码的字节数组
byte[] svgBytes = System.Text.Encoding.UTF8.GetBytes(svgQrCode.ToString());

HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
response.Content = new ByteArrayContent(svgBytes);
// 设置正确的SVG媒体类型
response.Content.Headers.ContentType = new MediaTypeHeaderValue("image/svg+xml");
// 如需强制触发下载而非浏览器预览,添加以下配置
response.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
{
    FileName = "qrcode.svg"
};

return response;

注意事项

  • 如果不需要强制下载,仅需要浏览器直接预览SVG,删除ContentDisposition相关配置即可
  • 编码统一使用UTF8可避免SVG内特殊字符出现乱码
  • 若你使用的是旧版本ZXing.NET.Svg包,SvgImage可能需要通过Content属性获取XML文本,上述代码报错时将svgQrCode.ToString()替换为svgQrCode.Content即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 17:15:08