2
2
from os import unlink
3
3
from os .path import dirname
4
4
from os .path import realpath
5
+ import re
5
6
6
7
def generate_certificate_for (event_id , certificate_name , name_of_certificate_holder ):
7
8
resources_path = dirname (realpath (__file__ )) + '/resources/'
@@ -13,7 +14,7 @@ def generate_certificate_for(event_id, certificate_name, name_of_certificate_hol
13
14
14
15
with open (generic_template_path ) as template :
15
16
personalized_certificate_content = template .read ().replace (
16
- '<CERTIFICATE_HOLDER_NAME>' , name_of_certificate_holder )
17
+ '<CERTIFICATE_HOLDER_NAME>' , tex_escape ( name_of_certificate_holder ) )
17
18
18
19
with open (personalized_template_path , 'w' ) as personalized_template :
19
20
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
30
31
return False
31
32
32
33
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