4

I am trying to convert text file into pdf in Python but I am getting error. Why is it happening and how can I fix it?

Here my code:

import fpdf
from fpdf import FPDF

pdf = FPDF()
pdf.add_page()
pdf.set_font("Arial", size=15)
f = open("textfile.txt", "r")
for i in f:
    pdf.cell(200, 10, txt=i, ln = 1, align = 'C')
pdf.output("Output.pdf")

Output: Error

    p = self.pages[n].encode("latin1") if PY3K else self.pages[n] 
UnicodeEncodeError: 'latin-1' codec can't encode character '\u2013' in position 88: ordinal not in range(256)
wjandrea
  • 28,235
  • 9
  • 60
  • 81
Mr X
  • 51
  • 1
  • 5
  • You're trying to encode a unicode character into latin-1 - that can't be done. You'll have to replace it first. – fredrik Apr 16 '21 at 18:39

3 Answers3

1

All the standard fonts in fpdf use latin-1 encoding. If you want to write characters that aren't in the latin-1 set, you'll need to use set_font to specify an external font.

Reference: https://pyfpdf.readthedocs.io/en/latest/reference/set_font/index.html

Otherwise you'll have to convert your string to latin-1 (using the encode method) and specify whether to ignore or replace the bad characters (i.e. the ones that don't exist in latin-1).

Chad S.
  • 6,252
  • 15
  • 25
  • my text file have this type of content. [{'id': 0, 'title': 'VOF-Verfahren – Ingenieurdienstleistungen für Technische Ausrüstung ELT (Anlagengruppe 4, 5, 6) gem § 53 HOAI, in Verbindung mit § 55 HOAI Leistungsphase 1-9 für den Neubau der Realschule Freising mit 2-fach Schulsporthalle.'}, {'id': 27, 'title': 'VOF-Verfahren – Ingenieurdienstleistungen für Technische Ausrüstung ELT (Anlagengruppe 4, 5, 6) gem § 53 HOAI, in Verbindung mit § 55 HOAI Leistungsphase 1-9 für den Neubau der Realschule Freising mit 2-fach Schulsporthalle.'}] – Mr X Apr 16 '21 at 18:51
0

I suggest you to change your code as below since it worked for me very NICE:

for i in f:
    pdf.cell(200, 10, txt=i.encode('utf-8').decode('latin-1'), ln = 1, align = 'C')
abbas abaei
  • 65
  • 3
  • 3
  • 8
-1

It's because the default fonts for pyfpdf are latin-1 encoded.

You will need to download a utf-8 encoded font like Arial (https://www.freefontspro.com/14454/arial.ttf), place it in the same directory as the python file, and add the font using

fpdf.add_font("Arial", "", "arial.ttf", uni=True)

when you set the font use 'Arial'

wjandrea
  • 28,235
  • 9
  • 60
  • 81
jbengineer
  • 19
  • 2