最佳体验请使用Chrome67及以上版本、火狐、Edge、Safari浏览器 ×

创建银行
创建开票

    golang中条码的生成

    作者:曾浩@云商软件 阅读572 2022/08/29 13:19:18 文章 原创 公开

    golang里条码生成可以调用

    "github.com/boombuler/barcode/code128"实现,实例代码如下:


    比如在gin方法中实现如下

    {

    code, err := code128.Encode("123abc") //根据字符串123abc生成条码

    if err != nil {

    ginplus.ResponseError(c, err)

    return

    }

    codeScale, err := barcode.Scale(code, 350, 70)  //生成一个宽为350,高为70的条码

    img := subtitleBarcode(codeScale)   //这个函数的作用是生成条码下面的数字

    c.Header("Content-Type", "image/png")

    png.Encode(c.Writer, img)

    }


    func subtitleBarcode(bc barcode.Barcode) image.Image {

    fontFace := basicfont.Face7x13

    fontColor := color.RGBA{0, 0, 0, 255}

    margin := 5 // Space between barcode and text


    // Get the bounds of the string

    bounds, _ := font.BoundString(fontFace, bc.Content())


    widthTxt := int((bounds.Max.X - bounds.Min.X) / 64)

    heightTxt := int((bounds.Max.Y - bounds.Min.Y) / 64)


    // calc width and height

    width := widthTxt

    if bc.Bounds().Dx() > width {

    width = bc.Bounds().Dx()

    }

    height := heightTxt + bc.Bounds().Dy() + margin


    // create result img

    img := image.NewRGBA(image.Rect(0, 0, width, height))

    // draw the barcode

    draw.Draw(img, image.Rect(0, 0, bc.Bounds().Dx(), bc.Bounds().Dy()), bc, bc.Bounds().Min, draw.Over)


    // TextPt

    offsetY := bc.Bounds().Dy() + margin - int(bounds.Min.Y/64)

    offsetX := (width - widthTxt) / 2


    point := fixed.Point26_6{

    X: fixed.Int26_6(offsetX * 64),

    Y: fixed.Int26_6(offsetY * 64),

    }


    d := &font.Drawer{

    Dst:  img,

    Src:  image.NewUniform(fontColor),

    Face: fontFace,

    Dot:  point,

    }

    d.DrawString(bc.Content())

    return img

    }


    前端调用后效果如下:

    image.png

    大功告成@@@


    声明:本网站部分内容来源于网络,版权归原权利人所有,其观点不代表本网站立场;本网站视频或图片制作权归当前商户及其作者,涉及未经授权的制作均须标记“样稿”。如内容侵犯了您相关权利,请及时通过邮箱service@ichub.com与我们联系。
     0  0

    微信扫一扫:分享

    微信里点“+”,扫一扫二维码

    便可将本文分享至朋友圈。

      
    
    
    分享
     0
      验证