Skip to content
How to insert a barcode into a PDF

How to insert a barcode into a PDF

UniPDF does not generate barcodes. Generate the code as a Go image.Image with a barcode library, then hand that image to the creator. The examples use boombuler/barcode, which covers EAN, Code 128, QR and the rest.

bcode, err := ean.Encode("123456789012")
if err != nil {
    return err
}

// Rasterize at several pixels per point so the code stays sharp when zoomed.
bcodeImg, err := barcode.Scale(bcode, 5*int(math.Ceil(width)), 5*int(math.Ceil(width)))
if err != nil {
    return err
}

img, err := c.NewImageFromGoImage(bcodeImg)
if err != nil {
    return err
}
img.ScaleToWidth(width)
img.SetPos(xPos, yPos)

return c.Draw(img)

Rasterize before you scale. ScaleToWidth sets the size the image is drawn at and does not touch the pixel data, so a barcode encoded at 100 pixels and drawn 100 points wide is readable on screen and falls apart when a viewer zooms in or the page is printed. The examples rasterize at five pixels per point for that reason.

SetPos measures from the top left corner of the page with y growing downward, which is the creator’s convention rather than PDF’s. Stamping a code onto an existing document means reading the pages with model.PdfReader and adding each one with c.AddPage before drawing, otherwise the untouched pages are dropped from the output.

Two complete examples are in the examples repository: pdf_add_barcode.go for EAN and pdf_add_qr_code.go for QR codes. Scaling, positioning and encoders are covered in the images guides.

Last updated on