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

Commit

Permalink
Escape special LaTeX chars in the cert holder name
Browse files Browse the repository at this point in the history
  • Loading branch information
mitio committed Nov 29, 2015
1 parent c004131 commit 0a3cb24
Showing 1 changed file with 28 additions and 1 deletion.
29 changes: 28 additions & 1 deletion certificates/generator.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
from os import unlink
from os.path import dirname
from os.path import realpath
import re

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

with open(generic_template_path) as template:
personalized_certificate_content = template.read().replace(
'<CERTIFICATE_HOLDER_NAME>', name_of_certificate_holder)
'<CERTIFICATE_HOLDER_NAME>', tex_escape(name_of_certificate_holder))

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

return resulting_certificate_path

def tex_escape(text):
"""
Escapes special chars in a text to be safely included in a LaTeX document.
See: http://stackoverflow.com/a/25875504/75715
:param text: a plain text message
:return: the message escaped to appear correctly in LaTeX
"""
conv = {
'&': r'\&',
'%': r'\%',
'$': r'\$',
'#': r'\#',
'_': r'\_',
'{': r'\{',
'}': r'\}',
'~': r'\textasciitilde{}',
'^': r'\^{}',
'\\': r'\textbackslash{}',
'<': r'\textless',
'>': r'\textgreater',
}
replacements = (re.escape(unicode(key)) for key in sorted(conv.keys(), key = lambda item: - len(item)))

regex = re.compile('|'.join(replacements))
return regex.sub(lambda match: conv[match.group()], text)

0 comments on commit 0a3cb24

Please sign in to comment.