0

I'm trying to write some hebrew words to a PDF file using the PDF Library in Python

and I'm getting an error

UnicodeEncodeError: 'latin-1' codec can't encode characters in position 51-55: ordinal not in range(256) How can I fix that and write hebrew to the PDF file?

from fpdf import FPDF
pdf = FPDF()
pdf.add_page()
uni=True
pdf.set_font("Arial", size=15)
welcome=u"היייי"
pdf.cell(200, 10, txt=welcome, ln=1, align="C")
pdf.output("simple_demo.pdf")
  • 1
    In the interest of content quality, Stack Overflow doesn’t permit duplicative questions. In the future, please search your error messages on your preferred search engine before posting here. This is a clear duplicate of [UnicodeEncodeError: 'latin-1' codec can't encode character](https://stackoverflow.com/questions/3942888/unicodeencodeerror-latin-1-codec-cant-encode-character) – esqew Aug 16 '21 at 18:33
  • I don't understand why your code is doing `welcome=u"היייי"`. The `u` prefix is redundant in Python 3 and is only there for cross-compatibility with Python 2. Or are you working in Python 2? – BoarGules Aug 16 '21 at 19:01

1 Answers1

0

You can download DejaVuSans.ttf file from this link: https://sourceforge.net/projects/dejavu/

And once you download the file, unzip it and go to the folder named ttf, and find a file, for example, named DejaVuSans.ttf.

Now you can use this code:

from fpdf import FPDF
pdf = FPDF()
pdf.add_page()
pdf.add_font("DejaVu", '', '/path/to/your/ttf/DejaVuSans.ttf', uni=True)
pdf.set_font("DejaVu", size=15)
welcome=u"היייי"
pdf.cell(200, 10, txt=welcome, ln=1, align="C")
pdf.output("simple_demo.pdf")

(Make sure you replace '/path/to/your/ttf/DejaVuSans.ttf' with the actual path to your DejaVuSans.ttf file that you downloaded from the link)

Suneesh Jacob
  • 738
  • 1
  • 6
  • 14
  • hey ! raise RuntimeError("TTF Font file not found: %s" % fname) RuntimeError: TTF Font file not found: /path/to/your/ttf/DejaVuSerif-Bold.ttf. What should I do from here, I did exactly what you told. – Eyal Ben - Chaim Aug 18 '21 at 08:07
  • Hi, I had put `/path/to/your/ttf/DejaVuSerif-Bold.ttf` just to show that the path to your file needs to be inserted there. You should not enter it as it is. Instead, replace `/path/to/your/ttf/DejaVuSerif-Bold.ttf` with the actual path to the `DejaVuSerif-Bold.ttf` file that you have downloaded. – Suneesh Jacob Aug 18 '21 at 19:36
  • If my above comment is more confusing to you, then ignore it and just copy the `DejaVuSerif-Bold.ttf` file and add it to your current working directory, and replace `/path/to/your/ttf/DejaVuSans.ttf` with `DejaVuSans.ttf` in the code. In case you don't know what your working directory is, then you can use `import os;print(os.getcwd())` in the Python interpreter in order to print your current working directory. – Suneesh Jacob Aug 18 '21 at 19:41