Search code examples
pythonpython-3.xarabicreportlabbidi

Arabic text is revering lines in reportlab


In reportLab, I need to display an arabic paragraph. I am using arabic-resharper and bidi-algorithm. The problem appears in the algorithm that reverses lines.

My code is:

def format_arabic_paragraph(arabic_text: str, paragraph_style: ParagraphStyle):
        reshaped_text = arabic_reshaper.reshape(arabic_text)
        bidirectional_text = algorithm.get_display(reshaped_text)
        formatted_paragraph = Paragraph(bidirectional_text, paragraph_style)
        return formatted_paragraph

arabic_text='وحدة1 وحدة2'

Here's the output:
وحدة2
وحدة1

Here's what I expected:
وحدة1
وحدة2


Solution

  • Reportlab has partial bidirectional support using Fribidi. It is disabled by default. There is an option rtlSupport in reportlab/rl_settings. See user guide section on site configuration. In my installation, I added a file ~/.reportlab_settings and added the line rtlSupport=1.

    In ParagraphStyle() set wordWrap="RTL".

    An example:

    from reportlab.platypus import Paragraph
    from reportlab.lib.enums import TA_RIGHT
    from reportlab.pdfbase import pdfmetrics
    from reportlab.pdfbase.ttfonts import TTFont
    from reportlab.lib.pagesizes import LETTER
    from reportlab.lib.styles import ParagraphStyle, getSampleStyleSheet
    from reportlab.platypus.doctemplate import SimpleDocTemplate
    
    pdfmetrics.registerFont(TTFont("Arial Unicode", "Arial Unicode.ttf"))
    
    arabic_text='وحدة1 وحدة2'
    
    doc = SimpleDocTemplate(
        "repro_ar.pdf",
        pagesize=LETTER,
        rightMargin=280,
        leftMargin=280,
        topMargin=72,
        bottomMargin=72,
    )
    styles = getSampleStyleSheet()
    normal_arabic = ParagraphStyle(
        parent=styles["Normal"],
        name="NormalArabic",
        wordWrap="RTL",
        alignment=TA_RIGHT,
        fontName="Arial Unicode",
        fontSize=14,
        leading=16
    )
    
    flowables = [Paragraph(arabic_text, normal_arabic)]
    doc.build(flowables)
    

    This gives me:

    enter image description here