Search code examples
pythonqtprintingpyqtcode128

PyQt4: printing Code 128 barcode fonts


I'm trying to write a text in code128 and a printer also ends in a picture, but it does not work in either of the two ways, I looked at the official documentation and other forum questions but it does not print in code128

from PyQt4.QtGui import QApplication,QImage,QFont
from PyQt4.QtCore import QSizeF
import sys,time
app = QApplication(sys.argv)
image = QImage(640,100,QImage.Format_Mono)
image.fill(1)
font = QFont('code128',32,QFont.Normal)
painter = QPainter()
painter.begin(image)
painter.setFont(font)
text = "\xccasdfsf\xce"
painter.drawText(10,90,text)
painter.end()
image.save('test.png')

and also in my thermal printer

from PyQt4.QtGui import QApplication,QImage,QFont,QPrinter
from PyQt4.QtCore import QSizeF
import sys,time
app = QApplication(sys.argv)
printer = QPrinter('POS-58(copy of 1)')
font = QFont('code128',32,QFont.Normal)
painter = QPainter()
painter.begin(printer)
painter.setFont(font)
text = "\xccasdfsf\xce"
painter.drawText(10,90,text)
painter.end()

Neither of these two works for me and I find a solution for this, what could be happening?

The actual output is thisenter image description here

I am using PyQt4 in windows 10 with python 2.7


Solution

  • From your comments, it is clear that the Code 128 font has not been installed properly on your system, so it is falling back to MS Shell Dlg 2 as a default.

    To see exactly which fonts are available to Qt on your system, you can do this:

    >>> fd = QtGui.QFontDatabase()         
    >>> len(fd.families())
    209
    >>> for f in sorted(fd.families()): print(f)
    ... 
    Adobe Courier
    Adobe Helvetica
    Adobe New Century Schoolbook
    Adobe Times
    Adobe Utopia
    Arabic Newspaper
    B&H Lucida
    B&H LucidaBright
    B&H LucidaTypewriter
    Bitstream Charter
    Bitstream Terminal
    Bitstream Vera Sans
    Bitstream Vera Sans Mono
    Bitstream Vera Serif
    C059
    Cantarell
    Code 128
    Code 128 low
    Code 2 of 5 interleaved
    Code 3 de 9
    Code Datamatrix
    Code EAN13
    Code PDF417
    D050000L
    ...
    

    If the Code 128 font doesn't appear in this list, it has definitely not been installed properly. There are plenty of free versions of this font available online (e.g. Free Barcode Font), so I suggest you try installing some of those instead.

    If these fonts still don't show up in Qt's list of font families, you can try adding them explicitly, like this:

    >>> QtGui.QFontDatabase.addApplicationFont('C:\\MyFonts\\code128.ttf')
    

    To check that the newly installed font is valid, use QFontInfo:

    >>> font = QtGui.QFont('Code 128')
    >>> info = QtGui.QFontInfo(font)
    >>> info.family()
    'Code 128'
    

    (NB: checking font.family() is not sufficient here, because that will only return what was requested, rather than what was actually found).