codebude / QRCoder

A pure C# Open Source QR Code implementation
MIT License
4.66k stars 1.11k forks source link

I want to make each cell a rect when outputting SVG #580

Closed yuya-tani closed 2 months ago

yuya-tani commented 2 months ago

I want to create a QR code in SVG, but if I create it as is, it will bleed when printed, so as a countermeasure, I would like to make each cell smaller so that they are not directly adjacent, but it seems there is no option to do so.

As a solution to this, for example, if a rect is created for each cell when outputting in SVG, I think it would be good to be able to make the cells smaller by specifying "scale(0.9)" or something similar after outputting in SVG.

However, at the moment, if there are adjacent cells, a merged rect is created, so I don't think it's possible to do it simply with scale.

The above two points

Would it be difficult to do either of the above?

Best regards.

yuya-tani commented 2 months ago

I was able to solve the problem by adding a custom method to create cells myself from ModuleMatrix like this. Sorry for the trouble.


public static string GenerateQrCodeSvg(QRCodeData qrCodeData, int width, int height)
{
    var moduleCount = qrCodeData.ModuleMatrix.Count;
    var moduleSize = Math.Min((double)width / moduleCount, (double)height / moduleCount);

    var svgBuilder = new StringBuilder();
    svgBuilder.AppendLine($"<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"{width}\" height=\"{height}\" viewBox=\"0 0 {width} {height}\">");

    for (var y = 0; y < moduleCount; y++)
    {
        for (var x = 0; x < moduleCount; x++)
        {
            var isBlackCell = qrCodeData.ModuleMatrix[y][x];
            var color = isBlackCell ? "#000000" : "#FFFFFF";
            svgBuilder.AppendLine($"<rect x=\"{x * moduleSize}\" y=\"{y * moduleSize}\" width=\"{moduleSize}\" height=\"{moduleSize}\" fill=\"{color}\" />");
        }
    }

    svgBuilder.AppendLine("</svg>");
    return svgBuilder.ToString();
}