Pyfpdf Turkish Character in Python - python

I want to create a pdf in my Python application using a text that contains Turkish characters, but I get an error. My codes are below. How can I fix this?
# -*- coding: utf-8 -*-
from fpdf import FPDF
import os
def add_image(image_path):
pdf = FPDF()
pdf.add_page()
epw = pdf.w - 2 * pdf.l_margin
pdf.set_font('Arial', 'B', 14.0)
txt = u'ATATÜRK LİSESİ 2019 2020 EĞİTİM ÖĞRETİM YILI 11C SINIFI'
stxt = txt.encode('iso-8859-9')
pdf.cell(epw, 0.0, stxt, align='C')
I get an 'UnicodeEncodeError: 'latin-1' codec can't encode character '\u0130' in position 60: ordinal not in range(256)' error if I use the codes below
epw = pdf.w - 2 * pdf.l_margin
pdf.set_font('Arial', 'B', 14.0)
txt = 'ATATÜRK LİSESİ 2019 2020 EĞİTİM ÖĞRETİM YILI 11C SINIFI'
#stxt = txt.encode('iso-8859-9')
pdf.cell(epw, 0.0, txt, align='C')

I downloaded 'tr-arial.ttf' font to the application folder and i found this solution:
epw = pdf.w - 2 * pdf.l_margin
txt = u'ATATÜRK LİSESİ 2019 2020 EĞİTİM ÖĞRETİM YILI 11C SINIFI'
pdf.add_font('tr-arial', '', 'tr-arial.ttf', uni=True)
pdf.set_font('tr-arial', '', 11)
pdf.cell(epw, 0.0, txt, align='C')

Related

convert text file to set of variables [duplicate]

This question already has answers here:
Best way to retrieve variable values from a text file?
(11 answers)
Closed 7 months ago.
Ok don't yell at me. I'm still learning.
Text file (file.txt, these are the entire contents):
pn = FZP16WHTEPE444
cp = custpart
pd = partdesc
bq = 11,000
co = color 02
ma = material 01
mo = 1234
ln = 2227011234
mb = 38
Python code:
print(str(pn))
print(str(cp))
print(str(pd))
print(str(bq))
print(str(co))
print(str(ma))
print(str(mo))
print(str(ln))
print(str(mb))
What do I do to make the python script call the strings from the text file so it'll display the following?:
FZP16WHTEPE444
custpart
partdesc
11,000
color 02
material 01
1234
2227011234
38
You can read content from file and split base = and store in dict and use dict for printing values.
dct = {}
with open('file.txt', 'r') as file:
for line in file:
k, v = line.split('=')
dct[k.strip()] = v.strip()
keys = ['pn' , 'cp' , 'pd', 'bq', 'co', 'ma', 'mo', 'ln', 'mb']
for k in keys:
print(dct[k])
FZP16WHTEPE444
custpart
partdesc
11,000
color 02
material 01
1234
2227011234
38
You can read the text file then create a dictionary with the values:
with open("file.txt", "r") as f:
f = f.read()
f = f.split("\n")
vals = dict(map(lambda val : val.split(" = "), f))
print(vals["pn"])
print(vals["cp"])
Here is one way:
test.txt
pn = FZP16WHTEPE444
cp = custpart
pd = partdesc
bq = 11,000
co = color 02
ma = material 01
mo = 1234
ln = 2227011234
mb = 38
test.py
with open("test.txt") as file:
dictionary = {}
for line in file:
entry = [x.strip() for x in line.split("=")]
dictionary[entry[0]] = entry[1]
print("{}".format(dictionary), flush=True)
$ python test.py
{'pn': 'FZP16WHTEPE444', 'cp': 'custpart', 'pd': 'partdesc', 'bq': '11,000', 'co': 'color 02', 'ma': 'material 01', 'mo': '1234', 'ln': '2227011234', 'mb': '38'}

UnicodeEncodeError: 'latin-1' codec can't encode character '\u2019'

I'm dealing with this error I don't know what's the problem I have already added the font Arial and I've also tried to use the function Unicode() but nothing the same error appears
UnicodeEncodeError: 'latin-1' codec can't encode character '\u2019' in position 59: ordinal not in range(256)
p.s: I'm using mac os
and this is the code
import numpy as np
import pandas as pd
from fpdf import FPDF
from PyPDF2 import *
from time import *
import matplotlib.pyplot as plt
#function to convert minutes to date string
def Minutes_To_Date(date_minutes):
if date_minutes>0:
Secondes = int(date_minutes*60)
else :
Secondes = 0
series_format=strftime('%H:%M:%S', gmtime(Secondes))
return series_format
#function to make the data frame into a table in pdf
def output_df_to_pdf(pdf,df):
table_cell_width = 25 # set the height of the cell and the width
table_cell_height = 6
pdf.add_font("Arial", "", "arial.ttf", uni=True)
pdf.set_font("Arial", "B", 8)
cols = df.columns
#type the first row (name of columns)
for col in cols:
pdf.cell(table_cell_width, table_cell_height, col, align = 'C', border = 1)
pdf.ln(table_cell_height)
pdf.set_font("Arial", "", 10)
#type the rows
for row in df.itertuples():
for col in cols :
value = str(getattr(row,col))
pdf.cell(table_cell_width, table_cell_height, value, align = "C", border=1)
pdf.ln(table_cell_height)
#the path of our data
path = r"/Users/mac/Desktop/data_test.xlsx"
#load the data into data frame
df = pd.read_excel(path, sheet_name='Feuil1')
#add the hours columns to the dataframe
df["heure"] = (df["Date dernier envoi"].dt.hour)
#add the "delai de validation " columns to dataframe
df["Délai de validation"] = (df["Date action"] - df["Date dernier envoi"])/np.timedelta64(1, 'm') #calculate period in minutes
#create 2 pivot table one to be seen and the other to make graphs
df_pivot = pd.pivot_table(df, values="Délai de validation", index="heure", columns="Nom Service", aggfunc = "mean" , margins=True)
df_pivot_seen = pd.pivot_table(df, values="Délai de validation", index="heure", columns="Nom Service", aggfunc = "mean")
date_minutes_1 = list(df_pivot_seen["AMPE"]) #convert the data frame column to list
date_minutes_2 = list(df_pivot_seen["AMPI"])
#convert the number of minutes to string in form of date
for i in range(len(date_minutes_1)):
date_minutes_1[i] = Minutes_To_Date(date_minutes_1[i])
date_minutes_2[i] = Minutes_To_Date(date_minutes_2[i])
#convert to data frame
df_pivot_seen["AMPE"] = pd.DataFrame(date_minutes_1)
df_pivot_seen["AMPI"] = pd.DataFrame(date_minutes_2)
#create a diagram
df_pivot.plot()
plt.savefig("chart.png")
#create fpdf object with default values page:A4 and mesure will be in millimeters
pdf = FPDF()
pdf.add_font("Arial", "", "arial.ttf", uni=True)
pdf.add_page()
pdf.set_font("Arial","B", 16)
pdf.cell(40,10,"Rapport d’activité Import/Export de la semaine S52")
pdf.ln(20)
pdf.image("chart.png")
pdf.ln(20)
output_df_to_pdf(pdf, df_pivot_seen)
pdf.output("/Users/mac/Desktop/report.pdf", "F")
print(df_pivot_seen)
UnicodeEncodeError Traceback (most recent call last)
/var/folders/yv/yjnc8p5j64s70dv3dfh9td600000gn/T/ipykernel_76346/884241888.py in <module>
83
84
---> 85 pdf.output("/Users/mac/Desktop/report.pdf")
86
87
~/opt/anaconda3/lib/python3.9/site-packages/fpdf/fpdf.py in output(self, name, dest)
1063 #Finish document if necessary
1064 if(self.state<3):
-> 1065 self.close()
1066 dest=dest.upper()
1067 if(dest==''):
~/opt/anaconda3/lib/python3.9/site-packages/fpdf/fpdf.py in close(self)
244 self._endpage()
245 #close document
--> 246 self._enddoc()
247
248 def add_page(self, orientation=''):
~/opt/anaconda3/lib/python3.9/site-packages/fpdf/fpdf.py in _enddoc(self)
1634 def _enddoc(self):
1635 self._putheader()
-> 1636 self._putpages()
1637 self._putresources()
1638 #Info
~/opt/anaconda3/lib/python3.9/site-packages/fpdf/fpdf.py in _putpages(self)
1168 if self.compress:
1169 # manage binary data as latin1 until PEP461 or similar is implemented
-> 1170 p = self.pages[n].encode("latin1") if PY3K else self.pages[n]
1171 p = zlib.compress(p)
1172 else:
UnicodeEncodeError: 'latin-1' codec can't encode character '\u2019' in position 59: ordinal not in range(256)
I solved this by changing the font. The original font (Arial only allowed latin-1.

How to display non Latin character on output text console correctly?

I'm new in Python. I'm experimenting to make "IDE" to run Python script that display non-Latin character, especially Indonesian local scripts (Javanese, Balinese, Buginese etc.) that have been included in the Unicode Standard. Please consider installing the Indonesian Unicode fonts to render the characters correctly.
Here is the code:
from tkinter import *
from tkinter.filedialog import asksaveasfilename, askopenfilename
import subprocess
compiler = Tk()
compiler.title ('ᮊᮧᮙ᮪ᮕᮤᮜᮨᮁ ᮞᮥᮔ᮪ᮓ')
file_path = ''
def set_file_path(path):
global file_path
file_path = path
def save_as():
if file_path == '':
path = asksaveasfilename(filetypes=[('Python Files', '*.py')])
else:
path = file_path
with open(path, 'w') as file:
code = editor.get('1.0', END)
file.write(code)
set_file_path(path)
def open_file():
path = askopenfilename(filetypes=[('Python Files', '*.py')])
with open(path, 'r') as file:
code =file.read()
editor.delete('1.0', END)
editor.insert('1.0', code)
set_file_path(path)
def run():
if file_path == '':
save_prompt = Toplevel()
text = Label(save_prompt, text='ᮞᮤᮙ᮪ᮕᮨᮔ᮪ ᮠᮩᮜ ᮊᮧᮓᮩ ᮃᮔ᮪ᮏᮩᮔ᮪')
text.pack()
return
command = f'python {file_path}'
process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
output, error = process.communicate()
code_output.insert('1.0', output)
code_output.insert('1.0', error)
menu_bar = Menu(compiler)
file_menu = Menu(menu_bar, tearoff=0)
file_menu.add_command(label='ᮘᮥᮊ', command=open_file)
file_menu.add_command(label='ᮞᮤᮙ᮪ᮕᮨᮔ᮪', command=save_as)
file_menu.add_command(label='ᮞᮤᮙ᮪ᮕᮨᮔ᮪ ᮔᮥ ᮞᮦᮏᮦᮔ᮪', command=save_as)
file_menu.add_command(label='ᮊᮜᮥᮃᮁ', command=exit)
menu_bar.add_cascade(label='ᮘᮨᮁᮊᮞ᮪', menu=file_menu)
run_bar = Menu(menu_bar, tearoff=0)
run_bar.add_command(label='ᮏᮜᮔ᮪ᮊᮩᮔ᮪', command=run)
menu_bar.add_cascade(label='ᮏᮜᮔ᮪ᮊᮩᮔ᮪', menu=run_bar)
compiler.config(menu=menu_bar)
editor = Text()
editor.pack()
code_output = Text(height=10)
code_output.pack()
compiler.mainloop()
I want to print the non-Latin characters, for example:
print('Sundanese script')
print('ᮃᮊ᮪ᮞᮛ ᮞᮥᮔ᮪ᮓ')
unfortunately the result shows this:
Sundanese script
ᮃᮊ᮪ᮞᮛ ᮞᮥᮔ᮪ᮓ
or the code like this:
import unicodedata
u = chr(233) + chr(0x03B2) + chr(0xA991) + chr(0x1B11) + chr(0x1B91) + chr(0x1BE1)
for i, c in enumerate(u):
print(i, '%04x' % ord(c), unicodedata.category(c), u[i], end=" ")
print(unicodedata.name(c))
will display this:
0 00e9 Ll é LATIN SMALL LETTER E WITH ACUTE
1 03b2 Ll β GREEK SMALL LETTER BETA
2 a991 Lo ꦑ JAVANESE LETTER KA MURDA
3 1b11 Lo ᬑ BALINESE LETTER OKARA
4 1b91 Lo ᮑ SUNDANESE LETTER NYA
5 1be1 Lo ᯡ BATAK LETTER CA
But the import unicodedata script could be displayed well on the terminal:
>>> import unicodedata
>>>
>>> u = chr(233) + chr(0x03B2) + chr(0xA991) + chr(0x1B11) + chr(0x1B91) + chr(0x1BE1)
>>>
>>> for i, c in enumerate(u):
... print(i, '%04x' % ord(c), unicodedata.category(c), u[i], end=" ")
... print(unicodedata.name(c))
...
0 00e9 Ll é LATIN SMALL LETTER E WITH ACUTE
1 03b2 Ll β GREEK SMALL LETTER BETA
2 a991 Lo ꦑ JAVANESE LETTER KA MURDA
3 1b11 Lo ᬑ BALINESE LETTER OKARA
4 1b91 Lo ᮑ SUNDANESE LETTER NYA
5 1be1 Lo ᯡ BATAK LETTER CA
Can anyone point out the problem?

How I can print characters from various alphabets in python 3?

I am trying to work with cyrillic alphabet and latin alphabet with central european characters, however I am not able to print cyrillic characters. Take a look at the sample code below.
# -*- coding: utf-8 -*-
print("ň")
print("ф")
I've been able to output "ň", once I have set "encoding": "cp1250" in Python.sublime-settings, but unfortunately I have not found any means of displaying cyrillic character.
Thanks for any help.
------------------------Edit--------------------------
meanwhile I've put together code, that works in Ubuntu 13.04 environment but throwing exception in Win 7.
Exception:
Traceback (most recent call last):
File "C:\Users\branislavs\docs\personal\scripts\playground.py", line 6, in <module>
for line in data:
File "C:\Python34\lib\encodings\cp1250.py", line 23, in decode
return codecs.charmap_decode(input,self.errors,decoding_table)[0]
UnicodeDecodeError: 'charmap' codec can't decode byte 0x81 in position 51: character maps to <undefined>
Environment:
Win 7
Python 3.4,
Sublime Text 2,
I am trying to output it on windows console.
What should in win to make it work?
I am pasting the code as well:
import sys
char_mapping = ("абвгґдезіийклмнопрстуфъыьцчжшАБВГҐДЕЗIИЙКЛМНОПРСТУФЪЫЬЦЧЖШ",
"abvhgdeziyjklmnoprstuf'ŷ'cčžšABVHGDEZIYJKLMNOPRSTUF'Ŷ'cČŽŠ")
syllable_mapping = {
"special": { #di ti ni li, da ta na la, cja, cji, sja, sji, rja, rji
"ďi": "дї",
"Ďi": "Дї",
"ťi": "тї",
"Ťi": "Тї",
"ňi": "нї",
"Ňi": "Нї",
"ľi": "лї",
"Ľi": "Лї",
"ďa": "дя",
"Ďa": "Дя",
"ťa": "тя",
"Ťa": "Тя",
"ňa": "ня",
"Ňa": "Hя",
"ľa": "ля",
"Ľa": "Ля",
"c'a": "ця",
"c'a": "Ця",
"c'i": "цї",
"C'i": "Цї",
"c'o": "цё",
"C'o": "Цё",
"s'a": "ся",
"S'a": "Ся",
"s'i": "сї",
"S'i": "Сї",
"s'o": "сё",
"S'o": "Сё",
"r'a": "ря",
"R'a": "Ря",
"r'i": "рї",
"R'i": "Рї",
"r'o": "рё",
"R'o": "Рё",
"z'a": "зя",
"Z'a": "Зя",
"z'i": "зї",
"Z'i": "Зї",
"z'o": "зё",
"Z'o": "Зё",
},
"carons": {
"ď": "дь",
"Ď": "Дь",
"ť": "ть",
"Ť": "Ть",
"ň": "нь",
"Ň": "Нь",
"ľ": "ль",
"Ľ": "Ль",
},
"basic" : {
"ja": "я",
"Ja": "Я",
"ju": "ю",
"Ju": "Ю",
"je": "є",
"Je": "Є",
"ch": "х",
"Ch": "X",
"'o": "ё",
"'O": "Ë",
"x": "кc",
"X": "Кc",
"šč": "щ",
"Šč": "Щ",
"ji": "ї",
"c'" : "ць",
"C'" : "Ць",
"s'" : "сь",
"S'" : "Сь",
"r'" : "рь",
"R'" : "Рь",
"z'" : "зь",
"Z'" : "Зь",
}
}
tr_azb_lat = {ord(a):ord(b) for a, b in zip(*char_mapping)}
tr_lat_azb = {ord(b):ord(a) for a, b in zip(*char_mapping)}
def map_syllables_azb_lat(string, mapping_option):
for rule in syllable_mapping[mapping_option]:
string = string.replace(syllable_mapping[mapping_option][rule], rule)
return string
def translit_azb_lat(string):
string = map_syllables_azb_lat(string, 'special')
string = map_syllables_azb_lat(string, 'carons')
string = map_syllables_azb_lat(string, 'basic')
return string.translate(tr_azb_lat).encode('utf-8').decode(sys.stdout.encoding)
def map_syllables_lat_azb(string, mapping_option):
for rule in syllable_mapping[mapping_option]:
string = string.replace(rule, syllable_mapping[mapping_option][rule])
return string
def translit_lat_azb(string):
string = map_syllables_lat_azb(string, 'special')
string = map_syllables_lat_azb(string, 'carons')
string = map_syllables_lat_azb(string, 'basic')
return string.translate(tr_lat_azb).encode('utf-8').decode(sys.stdout.encoding)

python error FPDF object has no attribute 'y'

I try to make save as button in plugin QGIS Dufour 2.01 and want to save it as pdf file
when i try save my file ( open file destination and then click save ) i got a error message
This code i wrote
def _save(self, simpan):
import fpdf
# Portrait, millimeter units, A4 page size
pdf=fpdf.FPDF("P", "mm", "A4")
# Set font: Times, normal, size 10
pdf.set_font('Times','', 12)
# Layout cell: 0 x 5 mm, text, no border, Left
pdf.cell(0,5,'Input 1 : ' + self.ui.lineInput1.text(),border=0,align="L")
pdf.cell(0,5,'Input 2 : ' + self.ui.lineInput2.text(), border=0,align="L")
pdf.cell(0,5,'Recomendation : ' + self.ui.textRec2.toPlainText(), border=0, align="L")
pdf.cell(0,5,'Data 1 :' + self.ui.lineCond1.text(), border=0, align="L" )
pdf.cell(0,5,'Data 2 :' + self.ui.lineCond2.text(), border=0, align="L" )
pdf.output( simpan+'.pdf','F')
Error message i get
File "C:\PROGRA~1\QGISDU~1\apps\Python27\lib\site-packages\fpdf\fpdf.py", line 615, in cell
if(self.y+h>self.page_break_trigger and not self.in_footer and self.accept_page_break()):
AttributeError: 'FPDF' object has no attribute 'y'
Python version:
2.7.4 (default, Apr 6 2013, 19:54:46) [MSC v.1500 32 bit (Intel)]
i use fpdf 1.7 and install it with .msi installer
It seems you have not added a page to your pdf, before populating it with cells.
Try calling pdf.add_page() just after pdf=fpdf.FPDF("P", "mm", "A4")
add a page
def _save(self, simpan):
import fpdf
# Portrait, millimeter units, A4 page size
pdf=fpdf.FPDF("P", "mm", "A4")
# add a page
pdf.add_page()
# Set font: Times, normal, size 10
pdf.set_font('Times','', 12)
# Layout cell: 0 x 5 mm, text, no border, Left
pdf.cell(0,5,'Input 1 : ' + self.ui.lineInput1.text(),border=0,align="L")
pdf.cell(0,5,'Input 2 : ' + self.ui.lineInput2.text(), border=0,align="L")
pdf.cell(0,5,'Recomendation : ' + self.ui.textRec2.toPlainText(), border=0, align="L")
pdf.cell(0,5,'Data 1 :' + self.ui.lineCond1.text(), border=0, align="L" )
pdf.cell(0,5,'Data 2 :' + self.ui.lineCond2.text(), border=0, align="L" )
pdf.output( simpan+'.pdf','F')`

Categories

Resources