简体   繁体   中英

generate chinese character labels with python

I'm using Python pylabels https://pypi.python.org/pypi/pylabels/1.2.0 to generate labels. In particular I'm using the nametags.py example. The code works really well, except for when I use Chinese characters. nametags.py is copied below, with the Chinese characters inserted.

# This file is part of pylabels, a Python library to create PDFs for printing
# labels.
# Copyright (C) 2012, 2013, 2014 Blair Bonnett
#
# pylabels is free software: you can redistribute it and/or modify it under the
# terms of the GNU General Public License as published by the Free Software
# Foundation, either version 3 of the License, or (at your option) any later
# version.
#
# pylabels is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
# A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along with
# pylabels.  If not, see <http://www.gnu.org/licenses/>.

import labels
import os.path
from reportlab.pdfbase.ttfonts import TTFont
from reportlab.pdfbase.pdfmetrics import registerFont, stringWidth
from reportlab.graphics import shapes
from reportlab.lib import colors
import random
random.seed(187459)

# Create an A4 portrait (210mm x 297mm) sheets with 2 columns and 8 rows of
# labels. Each label is 90mm x 25mm with a 2mm rounded corner. The margins are
# automatically calculated.
specs = labels.Specification(210, 297, 2, 8, 90, 25, corner_radius=2)

# Get the path to the demos directory.
base_path = os.path.dirname(__file__)

# Add some fonts.
registerFont(TTFont('Judson Bold', os.path.join(base_path, 'Judson-Bold.ttf')))
registerFont(TTFont('KatamotzIkasi', os.path.join(base_path, 'KatamotzIkasi.ttf')))

# Create a function to draw each label. This will be given the ReportLab drawing
# object to draw on, the dimensions (NB. these will be in points, the unit
# ReportLab uses) of the label, and the name to put on the tag.
def write_name(label, width, height, name):
    # Write the title.

    ############# Chinese character inserted #############
    label.add(shapes.String(5, height-20, "你好, my name is",
                            fontName="Judson Bold", fontSize=20))
    ####################################################

    # Measure the width of the name and shrink the font size until it fits.
    font_size = 50
    text_width = width - 10
    name_width = stringWidth(name, "KatamotzIkasi", font_size)
    while name_width > text_width:
        font_size *= 0.8
        name_width = stringWidth(name, "KatamotzIkasi", font_size)

    # Write out the name in the centre of the label with a random colour.
    s = shapes.String(width/2.0, 15, name, textAnchor="middle")
    s.fontName = "KatamotzIkasi"
    s.fontSize = font_size
    s.fillColor = random.choice((colors.black, colors.blue, colors.red, colors.green))
    label.add(s)

# Create the sheet.
sheet = labels.Sheet(specs, write_name, border=True)
sheet.partial_page(1, ((1, 1), (2, 2), (4, 2)))

# Use an external file as the data source. NB. we need to remove the newline
# character from each line.
with open(os.path.join(base_path, "names.txt")) as names:
    sheet.add_labels(name.strip() for name in names)

# Save the file and we are done.
sheet.save('nametags.pdf')
print("{0:d} label(s) output on {1:d} page(s).".format(sheet.label_count, sheet.page_count))

The Chinese characters just renders as rectangular boxes. I've tried adding

# -*- coding: utf-8 -*-

to the beginning of the code, but it did not help. Also tried running both python2.7 and python 3.4 (which is supposed to make a strings unicode by default), also did not help. Any suggestions for how to get Chinese characters to display properly?

Thanks!

Default canvas_basefontname is "Helvetica" see in reportlab config doc . So change canvas_basefontname to your required font name. here is a code snippet you can add before registerFont() method in your code. I fount code sinppet here .

from reportlab import rl_config
rl_config._SAVED['canvas_basefontname'] = 'KatamotzIkasi'
rl_config._startUp()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM