So I made a Python program that will add text to a PDF template but I have a problem with showing chars like č,ć,š,ž,đ etc.
That text is firstly put on canvas:
packet = io.BytesIO()
can = canvas.Canvas(packet, pagesize=A4)
then you put the packet into a new PDF:
can.drawString(100, 100, "Kopačka")
can.save()
packet.seek(0)
new_pdf = PdfFileReader(packet)
and after that I merged the the empty PDF template and the new PDF with the critical text.
The problem is that the special diacritic chars are showing as black boxes like this: ⬛
I tried adding UTF-8 encoding to the definition function:
def __init__(self, e='utf-8')
and in the drawString function like this:
can.drawString(100, 100, "Kopačka".encode('utf-8'))
but it's still not showing correctly.
Is there a way to show those special characters in some other way?
Scripts that use UTF-8 encoding should start with this comment:
# -*- coding: utf-8 -*-
Also you can setup usage of utf-8 this way:
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
In your script unicode strings can be defined with 'u' prefix
can.drawString(100, 100, u"Kopačka")
So I found out the solution:
I added the comment as @Aleksey said: # -*- coding: utf-8 -*-
And I changed the font from Arial to Calibri as @usr2564301 suggested like this:
First, imported modules:
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
Then I downloaded Calibri Regualr.ttf in the folder and registered it in the app:
pdfmetrics.registerFont(TTFont('Calibri', 'Calibri Regular.ttf'))
And then changed the font in the canvas:
can.setFont("Calibri", 11)
Other than that, I left the UTF-8 encoding in the definition function and the drawString function.
Thank you all for the help!
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.