Skip to content
This repository was archived by the owner on Sep 19, 2018. It is now read-only.

Commit 0a3cb24

Browse files
committed
Escape special LaTeX chars in the cert holder name
1 parent c004131 commit 0a3cb24

File tree

1 file changed

+28
-1
lines changed

1 file changed

+28
-1
lines changed

certificates/generator.py

+28-1
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
from os import unlink
33
from os.path import dirname
44
from os.path import realpath
5+
import re
56

67
def generate_certificate_for(event_id, certificate_name, name_of_certificate_holder):
78
resources_path = dirname(realpath(__file__)) + '/resources/'
@@ -13,7 +14,7 @@ def generate_certificate_for(event_id, certificate_name, name_of_certificate_hol
1314

1415
with open(generic_template_path) as template:
1516
personalized_certificate_content = template.read().replace(
16-
'<CERTIFICATE_HOLDER_NAME>', name_of_certificate_holder)
17+
'<CERTIFICATE_HOLDER_NAME>', tex_escape(name_of_certificate_holder))
1718

1819
with open(personalized_template_path, 'w') as personalized_template:
1920
personalized_template.write(personalized_certificate_content.encode('utf-8'))
@@ -30,3 +31,29 @@ def generate_certificate_for(event_id, certificate_name, name_of_certificate_hol
3031
return False
3132

3233
return resulting_certificate_path
34+
35+
def tex_escape(text):
36+
"""
37+
Escapes special chars in a text to be safely included in a LaTeX document.
38+
See: http://stackoverflow.com/a/25875504/75715
39+
:param text: a plain text message
40+
:return: the message escaped to appear correctly in LaTeX
41+
"""
42+
conv = {
43+
'&': r'\&',
44+
'%': r'\%',
45+
'$': r'\$',
46+
'#': r'\#',
47+
'_': r'\_',
48+
'{': r'\{',
49+
'}': r'\}',
50+
'~': r'\textasciitilde{}',
51+
'^': r'\^{}',
52+
'\\': r'\textbackslash{}',
53+
'<': r'\textless',
54+
'>': r'\textgreater',
55+
}
56+
replacements = (re.escape(unicode(key)) for key in sorted(conv.keys(), key = lambda item: - len(item)))
57+
58+
regex = re.compile('|'.join(replacements))
59+
return regex.sub(lambda match: conv[match.group()], text)

0 commit comments

Comments
 (0)