0

I need to create a PDF with a mix of English and Arabic text, I was able to do that using below code, (download NotoSansArabic-Regular.ttf from Google Noto fonts). But the issue is Arabic text appears in left to right, but it should appear from right to left. For ex. it should be as 'مرحبا' and not 'ابحرم'. Any suggestions please

Below is the code to generate the PDF

from datetime import datetime
def getFileName():
    now=datetime.now()
    time = now.strftime('%d_%H_%M_%S')
    filename = "Test_UTF_"+time + ".pdf"
    return filename


from fpdf import FPDF

pdf = FPDF()
#Download NotoSansArabic-Regular.ttf from Google noto fonts
pdf.add_font("NotoSansArabic", style="", fname="./fonts/NotoSansArabic-Regular.ttf", uni=True)


pdf.add_page()

pdf.set_font('Arial', '', 12)
pdf.write(8, 'Hello World')
pdf.ln(8)

# مرحبا Marhaba in arabic 
pdf.set_font('NotoSansArabic', '', 12)
text = 'مرحبا'
pdf.write(8, text)
pdf.ln(8)

pdf.output(getFileName(), 'F')
akarahman
  • 235
  • 2
  • 15

1 Answers1

1

Working example using arabic reshaper and bidi


    from datetime import datetime
    import arabic_reshaper
    from bidi.algorithm import get_display
    
    def getFileName():
        now=datetime.now()
        time = now.strftime('%d_%H_%M_%S')
        filename = "Test_UTF_"+time + ".pdf"
        return filename
    
    
    from fpdf import FPDF
    
    pdf = FPDF()
    #Download NotoSansArabic-Regular.ttf from Google noto fonts
    pdf.add_font("NotoSansArabic", style="", fname="./fonts/NotoSansArabic-Regular.ttf", uni=True)
    
    
    pdf.add_page()
    
    pdf.set_font('Arial', '', 12)
    pdf.write(8, 'Hello World')
    pdf.ln(8)
    
    # مرحبا Marhaba in arabic 
    pdf.set_font('NotoSansArabic', '', 12)
    text = 'مرحبا'
    
    pdf.write(8, text)
    pdf.ln(8)
    
    reshaped_text = arabic_reshaper.reshape(text)
    print(reshaped_text)
    
    bidi_text = get_display(reshaped_text)
    
    print(bidi_text)
    
    pdf.write(8, reshaped_text)
    pdf.ln(8)
    
    pdf.write(8, bidi_text)
    pdf.ln(8)
    
    pdf.output(getFileName(), 'F')

akarahman
  • 235
  • 2
  • 15