Skip to content

Commit

Permalink
start progress adding test for fonts
Browse files Browse the repository at this point in the history
  • Loading branch information
alexanderankin committed Dec 1, 2020
1 parent 06134df commit 0da34c0
Show file tree
Hide file tree
Showing 7 changed files with 106 additions and 5 deletions.
22 changes: 20 additions & 2 deletions fpdf/errors.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,14 @@
def fpdf_error(message):
raise RuntimeError('FPDF error: ' + message)

def argument_representation(inputs):
return ', '.join(list(map(lambda x: repr(x), inputs)))

class FPDFException(Exception):
pass

class FPDFPageFormatException(FPDFException):
# """Error is thrown when a bad page format is given"""
"""Error is thrown when a bad page format is given"""
def __init__(self, argument, unknown=False, one=False):
super(FPDFPageFormatException, self).__init__()

Expand All @@ -34,7 +37,7 @@ def format_one(self, a):

def __repr__(self):
inputs = [self.argument, self.unknown, self.one]
arguments = ', '.join(list(map(lambda x: repr(x), inputs)))
arguments = argument_representation(inputs)
return ''.join(['FPDFPageFormatException(', arguments, ')'])

def __str__(self):
Expand All @@ -45,3 +48,18 @@ def __str__(self):
else:
return self._f(self.argument)

class FPDFUndefinedFontException(FPDFException):
"""Error is thrown when set_font called on font which is not added"""
def __init__(self, family, style):
super(FPDFUndefinedFontException, self).__init__()
self.family = family
self.style = style

def __repr__(self):
arguments = argument_representation([self.family, self.style])
return 'FPDFUndefinedFontException({})'.format(arguments)

def __str__(self):
style = ' ' + self.style if self.style and len(self.style) else ''
return 'Undefined font: {}{}'.format(self.family, style)

10 changes: 8 additions & 2 deletions fpdf/fpdf.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,8 @@
from .errors import (
fpdf_error,
FPDFException,
FPDFPageFormatException
FPDFPageFormatException,
FPDFUndefinedFontException
)
from .fonts import fpdf_charwidths
from .image_parsing import (
Expand Down Expand Up @@ -173,6 +174,7 @@ def __init__(self, orientation = 'P', unit = 'mm', format = 'A4'):
'timesBI': 'Times-BoldItalic',
'symbol': 'Symbol', 'zapfdingbats': 'ZapfDingbats'}
self.core_fonts_encoding = "latin-1"
self.unifontsubset = True

# Scale factor
if unit == "pt":
Expand Down Expand Up @@ -220,6 +222,8 @@ def __init__(self, orientation = 'P', unit = 'mm', format = 'A4'):
self.set_compression(1) # Enable compression
self.pdf_version = '1.3' # Set default PDF version No.

self.set_font('arial', '', 12)

def check_page(fn):
"Decorator to protect drawing methods"
@wraps(fn)
Expand Down Expand Up @@ -549,6 +553,7 @@ def add_font(self, family, style = '', fname = None, uni = False):
if (style == 'IB'): style = 'BI'
fontkey = family + style

print(fontkey, fontkey in self.fonts, uni, 'looking in', fname, os.path.join(FPDF_FONT_DIR, fname))
# Font already added!
if fontkey in self.fonts: return
if (uni):
Expand Down Expand Up @@ -710,7 +715,7 @@ def set_font(self, family, style='', size=0):
'cw' : fpdf_charwidths[fontkey]
}
else:
fpdf_error('Undefined font: ' + family + ' ' + style)
raise FPDFUndefinedFontException(family, style)

# Select it
self.font_family = family
Expand Down Expand Up @@ -919,6 +924,7 @@ def cell(self, w, h = 0, txt = '', border = 0, ln = 0, align = '',
s += ' ET'
else:
if (self.unifontsubset):
#
txt2 = escape_parens(UTF8ToUTF16BE(txt, False))
for uni in UTF8StringToArray(txt):
self.current_font['subset'].append(uni)
Expand Down
3 changes: 2 additions & 1 deletion fpdf/util/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,8 @@ def textstring(s):

def escape(s):
"Add \ before \, ( and )"
return s.replace('\\', '\\\\') \
# return s.replace('\\', '\\\\') \
return str(s).replace('\\', '\\\\') \

This comment has been minimized.

Copy link
@alexanderankin

alexanderankin Dec 1, 2020

Author

🥴

.replace(')', '\\)') \
.replace('(', '\\(') \
.replace('\r', '\\r')
Expand Down
Binary file added test/fonts/NotoSansShavian-Regular.ttf
Binary file not shown.
4 changes: 4 additions & 0 deletions test/fonts/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
"""This package contains font tests
fonts from https://filesamples.com/formats/ttf
"""
72 changes: 72 additions & 0 deletions test/fonts/respect_user_path.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
"""respect_user_path.py"""

import fpdf
import os
import pathlib
import six
import shutil
import sys
import traceback
import unittest


# python -m unittest test.fonts.respect_user_path.UserPathTest

from test.utilities import relative_path_to, set_doc_date_0

class UserPathTest(unittest.TestCase):
def test_regular_add_font_dir(self):
pdf = fpdf.FPDF()
set_doc_date_0(pdf)
pdf.add_page()

with self.assertRaises(fpdf.errors.FPDFUndefinedFontException) as raised:
pdf.set_font('abc')

ex = raised.exception
self.assertEqual(str(ex), 'Undefined font: abc')
self.assertEqual(repr(ex), "FPDFUndefinedFontException('abc', '')")

def test_regular_add_font_dir(self):
# where fpdf will try to look
dn, join = os.path.dirname, os.path.join
font_tests = dn(os.path.abspath(__file__))
repo = dn(dn(font_tests))
regular_folder = join(repo, 'fpdf', 'font')

os.mkdir(regular_folder)
testing_output = relative_path_to('test_regular_add_font_dir.pdf')

def cp_to_regular_folder(f):
shutil.copyfile(join(font_tests, f), join(regular_folder, f))


try:
cp_to_regular_folder('slick.ttf')
pdf = fpdf.FPDF()
set_doc_date_0(pdf)
pdf.add_page()
pdf.add_font('slick', '', 'slick.ttf', True)
pdf.set_font('slick', '', 12)
pdf.write(12, 'hello world hello world hello world hello world')
pdf.output(testing_output)

try:
os.system('ls -la ' + regular_folder)
os.system('file ' + regular_folder)
os.system('evince {}'.format(testing_output))
except Exception as e:
print('os system errors')
except Exception as e:
traceback.print_exc()
# (''.join(traceback.format_stack()))
finally:
try:
shutil.rmtree(regular_folder)
os.unlink(testing_output)
except Exception as e:
print('\n\nproblems unlinking\n\n')


os.system('ls -la ' + regular_folder)

Binary file added test/fonts/slick.ttf
Binary file not shown.

1 comment on commit 0da34c0

@alexanderankin
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

#14 needs tests, this is clearly not the completely correct approach...

Please sign in to comment.