Created
March 21, 2018 14:08
-
-
Save nngogol/6e19b97ce3f6e06b21a1add1a196ce3b to your computer and use it in GitHub Desktop.
How to write russian text in reportlab in python. Also, download 'DejaVuSerif.ttf' from internet.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
#-*- coding: UTF-8 -*- | |
from reportlab.lib import colors | |
from reportlab.platypus import Paragraph, SimpleDocTemplate, Table, TableStyle | |
from reportlab.lib.styles import getSampleStyleSheet | |
from reportlab.lib.pagesizes import A4 | |
from reportlab.pdfbase import pdfmetrics | |
from reportlab.pdfbase.ttfonts import TTFont | |
styles = getSampleStyleSheet() # дефолтовые стили | |
def StringGuy(text): | |
return f'<font name="DejaVuSerif">{text}</font>' | |
def ParagGuy(text, style=styles['Normal']): | |
return Paragraph(StringGuy(text), styles['Normal']) | |
pdfmetrics.registerFont(TTFont('DejaVuSerif','DejaVuSerif.ttf', 'UTF-8')) | |
doc=SimpleDocTemplate('test.pdf', | |
pagesize = A4, | |
title='Basic thing', | |
author='Gogol') | |
story=[] # словарь документа | |
# текст | |
story.append(ParagGuy('Привет мир!')) | |
story.append(ParagGuy('Привет мир!', styles['Heading1'])) | |
for i in range(5): | |
story.append(Paragraph("Тест простой " ,styles["Normal"])) | |
story.append(Paragraph('<font name="DejaVuSerif">Тест золотой </font>',styles["Normal"])) | |
# таблица | |
t = Table( | |
[ | |
['123', 'english text', 'still english'], | |
['heeeelo', '4324', '5346'], | |
['231', '4324', '5346'] | |
] | |
) | |
t.setStyle(TableStyle([('ALIGN',(1,1),(-2,-2),'RIGHT'), | |
('INNERGRID', (0,0), (-1,-1), 0.25, colors.black), | |
('BOX', (0,0), (-1,-1), 0.25, colors.black), | |
])) | |
story.append(t) | |
# таблица русская | |
t2 = Table( | |
[ | |
['123', 'english text', 'still english'], | |
['heeeelo', ParagGuy('русский'), '5346'], | |
['231', '4324', '5346'] | |
] | |
) | |
t2.setStyle(TableStyle([('ALIGN',(1,1),(-2,-2),'RIGHT'), | |
('INNERGRID', (0,0), (-1,-1), 0.25, colors.black), | |
('BOX', (0,0), (-1,-1), 0.25, colors.black), | |
])) | |
story.append(t2) | |
doc.build(story) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Here's an easier way