word-wrapreportlabcyrillic

Python Reportlab: wrap cyrillic text into table cell


I have problem to wrap cyrillic text into table cell. I use pdfmetrics.registerFont to set font who display cyrillic symbols, but when the text is longer than the width of the cell it is not wrapped. I try to use getSampleStyleSheet and then the text is wrapped into the cell, but I get black boxes instead of cyrillic symbols. Here is an example of my code:

from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import A4
from reportlab.lib.units import cm
from reportlab.platypus import Table, TableStyle
from reportlab.lib import colors


def coord(x, y, unit=1):
    x, y = x * unit, height - h - y * unit
    return x, y


width, height = A4

pdfmetrics.registerFont(TTFont('bold', 'Lora-Bold.ttf'))
pdfmetrics.registerFont(TTFont('regular', 'Lora-Regular.ttf'))

file_name = 'Report2.pdf'
title = 'ПРОТОКОЛ'

new_incidents = [('къс текст', 'къс текст', 'къс текст', 'дълъг текст', 'дълъг текст'),
                 ('къс текст', 'къс текст', 'къс текст', 'дъъъъъллъъгггггг текстттттттттт',
                  'дъъъъъллъъгггггг текстттттттттт')]

pdf = canvas.Canvas(file_name)

table1 = Table(new_incidents, colWidths=[1.6 * cm, 2.8 * cm, 2.8 * cm, 2.5 * cm, 2.5 * cm])

table1.setStyle(TableStyle([('ALIGN', (0, 1), (-1, -1), 'LEFT'),
                            ('ALIGN', (0, 0), (-1, 0), 'CENTER'),
                            ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
                            ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
                            ('FONT', (0, 0), (-1, 0), 'bold', 9),
                            ('FONT', (0, 1), (-1, -1), 'regular', 8)
                            ]))

elems = []
elems.append(table1)

w, h = table1.wrap(width, height)

table1.wrapOn(pdf, 550, 840)
x, y = coord(1.5, 6, cm)
table1.drawOn(pdf, x, y)

pdf.save()

Solution

  • To wrap the text, you must use the Paragraph.

    First you need to connect styles:

    styles = getSampleStyleSheet()
    styles["Normal"].fontName = 'regular'
    styleN = styles["Normal"]
    

    and then wrap the cell's text with Paragraph:

    new_incidents = [('къс текст', 'къс текст', 'къс текст', 'дълъг текст', 'дълъг текст'),
                     ('къс текст', 'къс текст', 'къс текст', Paragraph('дъъъъъллъъгггггг текстттттттттт', styleN),
                      Paragraph('дъъъъъллъъгггггг текстттттттттт', styleN))]
    

    Result