forked from openedx-unsupported/edx-certificates
-
Notifications
You must be signed in to change notification settings - Fork 1
/
gen_cert.py
1901 lines (1586 loc) · 76 KB
/
gen_cert.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
import copy
import datetime
import gnupg
import math
import os
import re
import shutil
import StringIO
import uuid
from reportlab.platypus import Paragraph
from PyPDF2 import PdfFileWriter, PdfFileReader
from reportlab.lib import colors
from reportlab.lib.enums import TA_CENTER, TA_LEFT, TA_RIGHT
from reportlab.lib.fonts import addMapping
from reportlab.lib.pagesizes import A4, letter, landscape
from reportlab.lib.styles import ParagraphStyle
from reportlab.lib.units import mm
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
from reportlab.pdfgen import canvas
from reportlab.pdfbase.pdfmetrics import stringWidth
from glob import glob
from HTMLParser import HTMLParser
from reportlab.pdfbase.ttfonts import TTFont
import settings
import collections
import itertools
import logging.config
import reportlab.rl_config
import tempfile
import boto.s3
from boto.s3.key import Key
from bidi.algorithm import get_display
import arabic_reshaper
from opaque_keys.edx.keys import CourseKey
reportlab.rl_config.warnOnMissingFontGlyphs = 0
RE_ISODATES = re.compile("(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2})")
TEMPLATE_DIR = settings.TEMPLATE_DIR
BUCKET = settings.CERT_BUCKET
CERT_KEY_ID = settings.CERT_KEY_ID
logging.config.dictConfig(settings.LOGGING)
log = logging.getLogger('certificates.' + __name__)
S3_CERT_PATH = 'downloads'
S3_VERIFY_PATH = getattr(settings, 'S3_VERIFY_PATH', 'cert')
TARGET_FILENAME = getattr(settings, 'CERT_FILENAME', 'Certificate.pdf')
TMP_GEN_DIR = getattr(settings, 'TMP_GEN_DIR', '/var/tmp/generated_certs')
CERTS_ARE_CALLED = getattr(settings, 'CERTS_ARE_CALLED', 'certificate')
CERTS_ARE_CALLED_PLURAL = getattr(settings, 'CERTS_ARE_CALLED_PLURAL', 'certificates')
# reduce logging level for gnupg
l = logging.getLogger('gnupg')
l.setLevel('WARNING')
# Register all fonts in the fonts/ dir; there are likely more fonts here than
# we need, but the performance hit is minimal -- especially since we only do
# this at import time.
#
# While registering fonts, build a table of the Unicode code points in each
# for use in font_for_string().
FONT_CHARACTER_TABLES = {}
for font_file in glob('{0}/fonts/*.ttf'.format(TEMPLATE_DIR)):
font_name = os.path.basename(os.path.splitext(font_file)[0])
ttf = TTFont(font_name, font_file)
FONT_CHARACTER_TABLES[font_name] = ttf.face.charToGlyph.keys()
pdfmetrics.registerFont(TTFont(font_name, font_file))
# These are small, so let's just load them at import time and keep them around
# so we don't have to keep doing the file I/o
BLANK_PDFS = {
'landscape-A4': PdfFileReader(file("{0}/blank.pdf".format(TEMPLATE_DIR), "rb")),
'landscape-letter': PdfFileReader(file("{0}/blank-letter.pdf".format(TEMPLATE_DIR), "rb")),
'portrait-A4': PdfFileReader(file("{0}/blank-portrait-A4.pdf".format(TEMPLATE_DIR), "rb")),
}
def prettify_isodate(isoformat_date):
"""Convert a string like '2012-02-02' to one like 'February 2nd, 2012'"""
m = RE_ISODATES.match(isoformat_date)
if not m:
raise TypeError("prettify_isodate called with incorrect date format: %s" % isoformat_date)
day_suffixes = {'1': 'st', '2': 'nd', '3': 'rd', '21': 'st', '22': 'nd', '23': 'rd', '31': 'st'}
months = ['January', 'February', 'March', 'April', 'May', 'June', 'July',
'August', 'September', 'October', 'November', 'December']
date = {'year': '', 'month': '', 'day': '', 'suffix': 'th'}
date['year'] = m.group('year')
date['month'] = months[int(m.group('month')) - 1]
date['day'] = m.group('day').lstrip('0')
date['suffix'] = day_suffixes.get(date['day'], 'th')
return "%(month)s %(day)s%(suffix)s, %(year)s" % date
def get_cert_date(calling_date_parameter, configured_date_parameter):
"""Get pertinent date for display on cert
- If cert passes a set date in 'calling_date_parameter', format that
- If using the "ROLLING" certs feature, use today's date
- If all else fails use 'configured_date_parameter' for date
"""
if calling_date_parameter:
date_value = prettify_isodate(calling_date_parameter)
elif configured_date_parameter == "ROLLING":
generate_date = datetime.date.today().isoformat()
date_value = prettify_isodate(generate_date)
else:
date_value = configured_date_parameter
date_string = u"{0}".format(date_value)
return date_string
def font_for_string(fontlist, ustring):
"""Determine the best font to render a string.
Given a list of fonts in priority order (that is, prettiest-first) and a
string which may or may not contain Unicode characters, test the string's
codepoints for glyph entries in the font, failing if any are missing and
returning the font name if it succeeds.
Font list a list of tuples where the first two items are the
human-readable font name, the on-disk filename, and one or more ignored
fields, e.g.:
[('font name', 'filename.ttf', 'ignored value', [...]), ...]
"""
# TODO: There's probably a way to do this by consulting reportlab that
# doesn't require re-loading the font files at all
ustring = unicode(ustring)
if fontlist and not ustring:
return fontlist[0]
for fonttuple in fontlist:
fonttag = fonttuple[0]
codepoints = FONT_CHARACTER_TABLES.get(fonttag, [])
if not codepoints:
warnstring = "Missing or invalid font specification {fonttag} " \
"rendering string '{ustring}'.\nFontlist: {fontlist}".format(
fonttag=fonttag,
ustring=ustring.encode('utf-8'),
fontlist=fontlist,
)
log.warning(warnstring)
continue
OK = reduce(lambda x, y: x and y, (ord(c) in codepoints for c in ustring))
if OK:
return fonttuple
# No font we tested supports this string, throw an exception.
# Then a human can and should install better fonts
raise ValueError("Nothing in fontlist supports string '{0}'. Fontlist: {1}".format(
ustring.encode('utf-8'),
repr(fontlist),
))
def autoscale_text(page, string, max_fontsize, max_leading, max_height, max_width, style):
"""Calculate font size and text placement given some base values
These values passed by reference are modified in this function, and not passed back:
- style.fontSize
- style.leading
"""
width = max_width + 1
height = max_height + 1
fontsize = max_fontsize
leading = max_leading
# Loop while size of text bigger than max allowed size as passed through
while width > max_width or height > max_height:
style.fontSize = fontsize
style.leading = leading
paragraph = Paragraph(string, style)
width, height = paragraph.wrapOn(page, max_width, max_height)
fontsize -= 1
leading -= 1
return paragraph
class CertificateGen(object):
"""Manages the pdf, signatures, and S3 bucket for course certificates."""
def __init__(self, course_id, template_pdf=None, aws_id=None, aws_key=None,
dir_prefix=None, long_org=None, long_course=None, issued_date=None):
"""Load a pdf template and initialize
Multiple certificates can be generated and uploaded for a single course.
course_id - Full course_id (ex: course-v1:MITx+6.00x+1T2015)
course_name - Human readable course title (ex: Introduction to Curling)
dir_prefix - Temporary directory for file generation. Ceritificates
and signatures are copied here temporarily before they
are uploaded to S3
template_pdf - (optional) Template (filename.pdf) to use for the
certificate generation.
aws_id - necessary for S3 uploads
aws_key - necessary for S3 uploads
course_id is used to look up extra data from settings.CERT_DATA,
including (but not necessarily limited to):
* LONG_ORG - long name for the organization
* ISSUED_DATE - month, year that corresponds to the
run of the course
* TEMPLATEFILE - the template pdf filename to use, equivalent to
template_pdf parameter
"""
if dir_prefix is None:
self._ensure_dir(TMP_GEN_DIR)
dir_prefix = tempfile.mkdtemp(prefix=TMP_GEN_DIR)
self._ensure_dir(dir_prefix)
self.dir_prefix = dir_prefix
self.aws_id = str(aws_id)
self.aws_key = str(aws_key)
cert_data = settings.CERT_DATA.get(course_id, {})
self.cert_data = cert_data
def interstitial_factory():
""" Generate default values for interstitial_texts defaultdict """
return itertools.repeat(cert_data.get('interstitial', {}).get('Pass', '')).next
# lookup long names from the course_id
try:
self.long_org = long_org or cert_data.get('LONG_ORG', '').encode('utf-8') or settings.DEFAULT_ORG
self.long_course = long_course or cert_data.get('LONG_COURSE', '').encode('utf-8')
self.issued_date = issued_date or cert_data.get('ISSUED_DATE', '').encode('utf-8') or 'ROLLING'
self.interstitial_texts = collections.defaultdict(interstitial_factory())
self.interstitial_texts.update(cert_data.get('interstitial', {}))
except KeyError:
log.critical("Unable to lookup long names for course {0}".format(course_id))
raise
# if COURSE or ORG is set in the configuration attempt to parse.
# This supports both new and old style course keys.
course_key = CourseKey.from_string(course_id)
self.course = cert_data.get('COURSE', course_key.course)
self.org = cert_data.get('ORG', course_key.org)
# get the template version based on the course settings in the
# certificates repo, with sensible defaults so that we can generate
# pdfs differently for the different templates
self.template_version = cert_data.get('VERSION', 1)
self.template_type = 'honor'
# search for certain keywords in the file name, we'll probably want to
# be better at parsing this later
# If TEMPLATEFILE is set in cert-data.yml, this value has top priority.
# Else if a value is passed in to the constructor (eg, from xqueue), it is used,
# Else, the filename is calculated from the version and course_id.
template_pdf = cert_data.get('TEMPLATEFILE', template_pdf)
template_prefix = '{0}/v{1}-cert-templates'.format(TEMPLATE_DIR, self.template_version)
template_pdf_filename = "{0}/certificate-template-{1}-{2}.pdf".format(template_prefix, self.org, self.course)
if template_pdf:
template_pdf_filename = "{0}/{1}".format(template_prefix, template_pdf)
if 'verified' in template_pdf:
self.template_type = 'verified'
try:
self.template_pdf = PdfFileReader(file(template_pdf_filename, "rb"))
except IOError as e:
log.critical("I/O error ({0}): {1} opening {2}".format(e.errno, e.strerror, template_pdf_filename))
raise
self.cert_label_singular = cert_data.get('CERTS_ARE_CALLED', CERTS_ARE_CALLED)
self.cert_label_plural = cert_data.get('CERTS_ARE_CALLED_PLURAL', CERTS_ARE_CALLED_PLURAL)
self.course_association_text = cert_data.get('COURSE_ASSOCIATION_TEXT', 'a course of study')
def delete_certificate(self, delete_download_uuid, delete_verify_uuid):
# TODO remove/archive an existing certificate
raise NotImplementedError
def create_and_upload(
self,
name,
upload=settings.S3_UPLOAD,
cleanup=True,
copy_to_webroot=settings.COPY_TO_WEB_ROOT,
cert_web_root=settings.CERT_WEB_ROOT,
grade=None,
designation=None,
):
"""
name - Full name that will be on the certificate
upload - Upload to S3 (defaults to True)
set upload to False if you do not want to upload to S3,
this will also keep temporary files that are created.
returns a tuple containing the UUIDs for download, verify and
the full download URL. If upload is set to False
download_url in the return will be None
return (download_uuid, verify_uuid, download_url)
verify_uuid will be None if there is no verification signature
"""
download_uuid = None
verify_uuid = None
download_url = None
s3_conn = None
bucket = None
certificates_path = os.path.join(self.dir_prefix, S3_CERT_PATH)
verify_path = os.path.join(self.dir_prefix, S3_VERIFY_PATH)
(download_uuid, verify_uuid, download_url) = self._generate_certificate(student_name=name,
download_dir=certificates_path,
verify_dir=verify_path,
grade=grade,
designation=designation,)
# upload generated certificate and verification files to S3,
# or copy them to the web root. Or both.
my_certs_path = os.path.join(certificates_path, download_uuid)
my_verify_path = os.path.join(verify_path, verify_uuid)
if upload:
s3_conn = boto.connect_s3(settings.CERT_AWS_ID, settings.CERT_AWS_KEY)
bucket = s3_conn.get_bucket(BUCKET)
if upload or copy_to_webroot:
for subtree in (my_certs_path, my_verify_path):
for dirpath, dirnames, filenames in os.walk(subtree):
for filename in filenames:
local_path = os.path.join(dirpath, filename)
dest_path = os.path.relpath(local_path, start=self.dir_prefix)
publish_dest = os.path.join(cert_web_root, dest_path)
if upload:
try:
key = Key(bucket, name=dest_path)
key.set_contents_from_filename(local_path, policy='public-read')
except:
raise
else:
log.info("uploaded {local} to {s3path}".format(local=local_path, s3path=dest_path))
if copy_to_webroot:
try:
dirname = os.path.dirname(publish_dest)
if not os.path.exists(dirname):
os.makedirs(dirname)
shutil.copy(local_path, publish_dest)
except:
raise
else:
log.info("published {local} to {web}".format(local=local_path, web=publish_dest))
if cleanup:
for working_dir in (certificates_path, verify_path):
if os.path.exists(working_dir):
shutil.rmtree(working_dir)
return (download_uuid, verify_uuid, download_url)
def _generate_certificate(
self,
student_name,
download_dir,
verify_dir,
filename=TARGET_FILENAME,
grade=None,
designation=None,
):
"""Generate a certificate PDF, signature and validation html files.
return (download_uuid, verify_uuid, download_url)
"""
versionmap = {
1: self._generate_v1_certificate,
2: self._generate_v2_certificate,
'MIT_PE': self._generate_mit_pe_certificate,
'stanford': self._generate_stanford_SOA,
'3_dynamic': self._generate_v3_dynamic_certificate,
'stanford_cme': self._generate_stanford_cme_certificate,
}
# TODO: we should be taking args, kwargs, and passing those on to our callees
return versionmap[self.template_version](
student_name,
download_dir,
verify_dir,
filename,
grade,
designation,
)
def _generate_v1_certificate(
self,
student_name,
download_dir,
verify_dir,
filename=TARGET_FILENAME,
grade=None,
designation=None,
):
# A4 page size is 297mm x 210mm
verify_uuid = uuid.uuid4().hex
download_uuid = uuid.uuid4().hex
download_url = "{base_url}/{cert}/{uuid}/{file}".format(
base_url=settings.CERT_DOWNLOAD_URL,
cert=S3_CERT_PATH, uuid=download_uuid, file=filename)
filename = os.path.join(download_dir, download_uuid, filename)
# This file is overlaid on the template certificate
overlay_pdf_buffer = StringIO.StringIO()
c = canvas.Canvas(overlay_pdf_buffer, pagesize=landscape(A4))
# 0 0 - normal
# 0 1 - italic
# 1 0 - bold
# 1 1 - italic and bold
pdfmetrics.registerFont(TTFont('Roboto', '/edx/app/certs/certificates/fonts/roboto/Roboto-Regular.ttf'))
pdfmetrics.registerFont(TTFont('Roboto-Thin', '/edx/app/certs/certificates/fonts/roboto/Roboto-Thin.ttf'))
addMapping('Roboto', 0, 0, 'Roboto')
addMapping('Roboto', 0, 1, 'Roboto')
addMapping('Roboto', 1, 0, 'Roboto')
addMapping('Roboto-Thin', 0, 0, 'Roboto-Thin')
addMapping('Roboto-Thin', 0, 1, 'Roboto-Thin')
addMapping('Roboto-Thin', 1, 0, 'Roboto-Thin')
addMapping('OpenSans-Light', 0, 0, 'OpenSans-Light')
addMapping('OpenSans-Light', 0, 1, 'OpenSans-LightItalic')
addMapping('OpenSans-Light', 1, 0, 'OpenSans-Bold')
addMapping('OpenSans-Regular', 0, 0, 'OpenSans-Regular')
addMapping('OpenSans-Regular', 0, 1, 'OpenSans-Italic')
addMapping('OpenSans-Regular', 1, 0, 'OpenSans-Bold')
addMapping('OpenSans-Regular', 1, 1, 'OpenSans-BoldItalic')
styleArial = ParagraphStyle(name="arial", leading=10, fontName='Arial Unicode')
styleOpenSans = ParagraphStyle(name="opensans-regular", leading=10, fontName='OpenSans-Regular')
styleOpenSansLight = ParagraphStyle(name="opensans-light", leading=10, fontName='OpenSans-Light')
styleRoboto = ParagraphStyle(name="roboto", leading=10, fontName='Roboto')
styleRobotoThin = ParagraphStyle(name="roboto-thin", leading=10, fontName='Roboto-Thin')
# Text is overlayed top to bottom
# * Issued date (top right corner)
# * "This is to certify that"
# * Student's name
# * "successfully completed"
# * Course name
# * "a course of study.."
# * honor code url at the bottom
WIDTH = 297 # width in mm (A4)
HEIGHT = 210 # hight in mm (A4)
LEFT_INDENT = 49 # mm from the left side to write the text
RIGHT_INDENT = 49 # mm from the right side for the CERTIFICATE
# CERTIFICATE
styleOpenSansLight.fontSize = 19
styleOpenSansLight.leading = 10
styleOpenSansLight.textColor = colors.Color(0.302, 0.306, 0.318)
styleOpenSansLight.alignment = TA_LEFT
#Fecha Curso
paragraph_string = ""
# Right justified so we compute the width
width = stringWidth(
paragraph_string,
'Roboto-Thin',
19,
) / mm
paragraph = Paragraph("{0}".format(
paragraph_string), styleRobotoThin)
paragraph.wrapOn(c, WIDTH * mm, HEIGHT * mm)
paragraph.drawOn(c, (WIDTH - RIGHT_INDENT - width) * mm, 163 * mm)
# Issued ..
styleRobotoThin.fontSize = 12
styleRobotoThin.leading = 10
#styleOpenSansLight.textColor = colors.Color(0.302, 0.306, 0.318)
styleOpenSansLight.alignment = TA_LEFT
paragraph_string = "{0}".format(self.issued_date)
# Right justified so we compute the width
width = stringWidth(
paragraph_string,
'Roboto-Thin',
20,
) / mm
paragraph = Paragraph("{0}".format(
paragraph_string), styleRobotoThin)
paragraph.wrapOn(c, WIDTH * mm, HEIGHT * mm)
paragraph.drawOn(c, 214.30 * mm, 57 * mm)
# Student name
# default is to use the DejaVu font for the name,
# will fall back to Arial if there are
# unusual characters
#style = styleOpenSans
style = styleRoboto
style.leading = 10
width = stringWidth(student_name.decode('utf-8'), 'Roboto', 14) / mm
paragraph_string = "{0}".format(student_name)
if self._use_unicode_font(student_name):
style = styleArial
style = styleMiso
width = stringWidth(student_name.decode('utf-8'), 'Roboto', 14) / mm
# There is no bold styling for Arial :(
paragraph_string = "<b>{0}</b>".format(student_name)
# We will wrap at 200mm in, so if we reach the end (200-47)
# decrease the font size
if width > 153:
style.fontSize = 18
nameYOffset = 121.55
else:
style.fontSize = 18
nameYOffset = 121.55
style.textColor = colors.HexColor('#d2191a')
#style.textColor = colors.Color(
# 0,0.128,.128 )
style.alignment = TA_CENTER
paragraph = Paragraph(paragraph_string, style)
paragraph.wrapOn(c, WIDTH * mm, HEIGHT * mm)
paragraph.drawOn(c, 0 * mm, nameYOffset * mm)
# Course name
style.textColor = colors.HexColor('#000000')
# styleOpenSans.fontName = 'OpenSans-BoldItalic'
styleRoboto.fontSize = 17
styleRoboto.leading = 10
#styleOpenSans.textColor = colors.Color(
# 0, 0.624, 0.886)
styleOpenSans.textColor = colors.HexColor('#5d5e5e')
styleOpenSans.alignment = TA_CENTER
paragraph_string = u"<b><i>{1}</i></b>".format(
self.course, self.long_course.decode('utf-8'))
paragraph = Paragraph(paragraph_string, styleRoboto)
# paragraph.wrapOn(c, WIDTH * mm, HEIGHT * mm)
paragraph.wrapOn(c, WIDTH * mm, HEIGHT * mm)
paragraph.drawOn(c, 0 * mm, 94.60 * mm)
# Honor code
styleOpenSansLight.fontSize = 7
styleOpenSansLight.leading = 10
styleOpenSansLight.textColor = colors.Color(
0.302, 0.306, 0.318)
styleOpenSansLight.alignment = TA_CENTER
paragraph_string = "<br/>" \
"*La Autenticidad de este certificado puede ser verificado en " \
"<a href='{verify_url}/{verify_path}/{verify_uuid}/valid.html'>" \
"{verify_url}/{verify_path}/{verify_uuid}</a>"
paragraph_string = paragraph_string.format(
verify_url=settings.CERT_VERIFY_URL,
verify_path=S3_VERIFY_PATH,
verify_uuid=verify_uuid)
paragraph = Paragraph(paragraph_string, styleOpenSansLight)
paragraph.wrapOn(c, WIDTH * mm, HEIGHT * mm)
paragraph.drawOn(c, 0 * mm, 8 * mm)
c.showPage()
c.save()
# Merge the overlay with the template, then write it to file
output = PdfFileWriter()
overlay = PdfFileReader(overlay_pdf_buffer)
# We need a page to overlay on.
# So that we don't have to open the template
# several times, we open a blank pdf several times instead
# (much faster)
final_certificate = copy.copy(BLANK_PDFS['landscape-A4']).getPage(0)
final_certificate.mergePage(self.template_pdf.getPage(0))
final_certificate.mergePage(overlay.getPage(0))
output.addPage(final_certificate)
self._ensure_dir(filename)
outputStream = file(filename, "wb")
output.write(outputStream)
outputStream.close()
self._generate_verification_page(
student_name,
filename,
verify_dir,
verify_uuid,
download_url
)
return (download_uuid, verify_uuid, download_url)
def _generate_v2_certificate(
self,
student_name,
download_dir,
verify_dir,
filename=TARGET_FILENAME,
grade=None,
designation=None,
):
"""
We have a new set of certificates that we want to generate which means brand new generation of certs
"""
# 8.5x11 page size 279.4mm x 215.9mm
WIDTH = 279 # width in mm (8.5x11)
HEIGHT = 216 # height in mm (8.5x11)
verify_uuid = uuid.uuid4().hex
download_uuid = uuid.uuid4().hex
download_url = "{base_url}/{cert}/{uuid}/{file}".format(
base_url=settings.CERT_DOWNLOAD_URL,
cert=S3_CERT_PATH, uuid=download_uuid, file=filename
)
filename = os.path.join(download_dir, download_uuid, filename)
# This file is overlaid on the template certificate
overlay_pdf_buffer = StringIO.StringIO()
c = canvas.Canvas(overlay_pdf_buffer, pagesize=landscape(letter))
styleOpenSans = ParagraphStyle(name="opensans-regular", leading=10,
fontName='OpenSans-Regular')
styleArial = ParagraphStyle(name="arial", leading=10,
fontName='Arial Unicode')
# Text is overlayed top to bottom
# * Issued date (top right corner)
# * "This is to certify that"
# * Student's name
# * "successfully completed"
# * Course name
# * "a course of study.."
# * honor code url at the bottom
# New things below
# STYLE: typeface assets
addMapping('AvenirNext-Regular', 0, 0, 'AvenirNext-Regular')
addMapping('AvenirNext-DemiBold', 1, 0, 'AvenirNext-DemiBold')
# STYLE: grid/layout
LEFT_INDENT = 23 # mm from the left side to write the text
MAX_WIDTH = 150 # maximum width on the content in the cert, used for wrapping
# STYLE: template-wide typography settings
style_type_metacopy_size = 13
style_type_metacopy_leading = 10
style_type_footer_size = 8
style_type_name_size = 36
style_type_name_leading = 53
style_type_name_med_size = 28
style_type_name_med_leading = 41
style_type_name_small_size = 22
style_type_name_small_leading = 27
style_type_course_size = 24
style_type_course_leading = 28
style_type_course_small_size = 16
style_type_course_small_leading = 20
# STYLE: template-wide color settings
style_color_metadata = colors.Color(0.541176, 0.509804, 0.560784)
style_color_name = colors.Color(0.000000, 0.000000, 0.000000)
# STYLE: positioning
pos_metacopy_title_y = 120
pos_metacopy_achivement_y = 88
pos_metacopy_org_y = 50
pos_name_y = 94
pos_name_med_y = 95
pos_name_small_y = 95
pos_name_no_wrap_offset_y = 2
pos_course_y = 68
pos_course_small_y = 66
pos_course_no_wrap_offset_y = 5
pos_footer_url_x = 83
pos_footer_url_y = 20
pos_footer_date_x = LEFT_INDENT
pos_footer_date_y = 20
# STYLE: verified settings
v_style_color_course = colors.Color(0.701961, 0.231373, 0.400000)
# HTML Parser ####
# Since the final string is HTML in a PDF we need to un-escape the html
# when calculating the string width.
html = HTMLParser()
# ELEM: Metacopy
styleAvenirNext = ParagraphStyle(name="avenirnext-regular", fontName='AvenirNext-Regular')
styleAvenirNext.alignment = TA_LEFT
styleAvenirNext.fontSize = style_type_metacopy_size
styleAvenirNext.leading = style_type_metacopy_leading
styleAvenirNext.textColor = style_color_metadata
# ELEM: Metacopy - Title: This is to certify that
if self.template_type == 'verified':
y_offset = pos_metacopy_title_y
paragraph_string = 'This is to certify that'
paragraph = Paragraph(paragraph_string, styleAvenirNext)
paragraph.wrapOn(c, WIDTH * mm, HEIGHT * mm)
paragraph.drawOn(c, LEFT_INDENT * mm, y_offset * mm)
# ELEM: Student Name
# default is to use Avenir for the name,
# will fall back to Arial if there are
# unusual characters
y_offset_name = pos_name_y
y_offset_name_med = pos_name_med_y
y_offset_name_small = pos_name_small_y
styleAvenirStudentName = ParagraphStyle(name="avenirnext-demi", fontName='AvenirNext-DemiBold')
styleAvenirStudentName.leading = style_type_name_small_size
style = styleAvenirStudentName
html_student_name = html.unescape(student_name)
larger_width = stringWidth(html_student_name.decode('utf-8'),
'AvenirNext-DemiBold', style_type_name_size) / mm
smaller_width = stringWidth(
html_student_name.decode('utf-8'),
'AvenirNext-DemiBold', style_type_name_small_size) / mm
# TODO: get all strings working reshaped and handling bi-directional strings
paragraph_string = arabic_reshaper.reshape(student_name.decode('utf-8'))
paragraph_string = get_display(paragraph_string)
# Avenir only supports Latin-1
# Switch to using OpenSans if we can
if self._use_non_latin(student_name):
style = styleOpenSans
larger_width = stringWidth(html_student_name.decode('utf-8'),
'OpenSans-Regular', style_type_name_size) / mm
# if we can't use OpenSans, use Arial
if self._use_unicode_font(student_name):
style = styleArial
larger_width = stringWidth(html_student_name.decode('utf-8'),
'Arial Unicode', style_type_name_size) / mm
# if the name is too long, shrink the font size
if larger_width < MAX_WIDTH:
style.fontSize = style_type_name_size
style.leading = style_type_name_leading
y_offset = y_offset_name
elif smaller_width < MAX_WIDTH:
y_offset = y_offset_name_med + pos_name_no_wrap_offset_y
style.fontSize = style_type_name_med_size
style.leading = style_type_name_med_leading
else:
y_offset = y_offset_name_small
style.fontSize = style_type_name_small_size
style.leading = style_type_name_small_leading
style.textColor = style_color_name
style.alignment = TA_LEFT
paragraph = Paragraph(paragraph_string, style)
paragraph.wrapOn(c, MAX_WIDTH * mm, HEIGHT * mm)
paragraph.drawOn(c, LEFT_INDENT * mm, y_offset * mm)
# ELEM: Metacopy - Achievement: successfully completed and received a passing grade in
y_offset = pos_metacopy_achivement_y
paragraph_string = 'successfully completed and received a passing grade in'
paragraph = Paragraph("{0}".format(paragraph_string), styleAvenirNext)
paragraph.wrapOn(c, WIDTH * mm, HEIGHT * mm)
paragraph.drawOn(c, LEFT_INDENT * mm, y_offset * mm)
# ELEM: Course Name
y_offset_larger = pos_course_y
y_offset_smaller = pos_course_small_y
styleAvenirCourseName = ParagraphStyle(name="avenirnext-demi", fontName='AvenirNext-DemiBold')
styleAvenirCourseName.textColor = style_color_name
if self.template_type == 'verified':
styleAvenirCourseName.textColor = v_style_color_course
paragraph_string = u"{0}: {1}".format(self.course, self.long_course)
html_paragraph_string = html.unescape(paragraph_string)
larger_width = stringWidth(html_paragraph_string.decode('utf-8'),
'AvenirNext-DemiBold', style_type_course_size) / mm
smaller_width = stringWidth(html_paragraph_string.decode('utf-8'),
'AvenirNext-DemiBold', style_type_course_small_size) / mm
if larger_width < MAX_WIDTH:
styleAvenirCourseName.fontSize = style_type_course_size
styleAvenirCourseName.leading = style_type_course_leading
y_offset = y_offset_larger
elif smaller_width < MAX_WIDTH:
styleAvenirCourseName.fontSize = style_type_course_small_size
styleAvenirCourseName.leading = style_type_course_small_leading
y_offset = y_offset_smaller + pos_course_no_wrap_offset_y
else:
styleAvenirCourseName.fontSize = style_type_course_small_size
styleAvenirCourseName.leading = style_type_course_small_leading
y_offset = y_offset_smaller
styleAvenirCourseName.alignment = TA_LEFT
paragraph = Paragraph(paragraph_string, styleAvenirCourseName)
paragraph.wrapOn(c, MAX_WIDTH * mm, HEIGHT * mm)
paragraph.drawOn(c, LEFT_INDENT * mm, y_offset * mm)
# ELEM: Metacopy - Org: a course of study...
y_offset = pos_metacopy_org_y
paragraph_string = "{2} offered by {0}" \
", an online learning<br /><br />initiative of " \
"{1} through edX.".format(
self.org, self.long_org.decode('utf-8'), self.course_association_text)
paragraph = Paragraph(paragraph_string, styleAvenirNext)
paragraph.wrapOn(c, WIDTH * mm, HEIGHT * mm)
paragraph.drawOn(c, LEFT_INDENT * mm, y_offset * mm)
# ELEM: Footer
styleAvenirFooter = ParagraphStyle(name="avenirnext-demi", fontName='AvenirNext-DemiBold')
styleAvenirFooter.alignment = TA_LEFT
styleAvenirFooter.fontSize = style_type_footer_size
# ELEM: Footer - Issued on Date
x_offset = pos_footer_date_x
y_offset = pos_footer_date_y
paragraph_string = "{0}".format(self.issued_date)
# Right justified so we compute the width
paragraph = Paragraph("{0}".format(
paragraph_string), styleAvenirFooter)
paragraph.wrapOn(c, WIDTH * mm, HEIGHT * mm)
paragraph.drawOn(c, LEFT_INDENT * mm, y_offset * mm)
# ELEM: Footer - Verify Authenticity URL
y_offset = pos_footer_url_y
x_offset = pos_footer_url_x
paragraph_string = "<a href='https://{bucket}/{verify_path}/{verify_uuid}'>" \
"https://{bucket}/{verify_path}/{verify_uuid}</a>"
paragraph_string = paragraph_string.format(bucket=BUCKET,
verify_path=S3_VERIFY_PATH,
verify_uuid=verify_uuid)
paragraph = Paragraph(paragraph_string, styleAvenirFooter)
paragraph.wrapOn(c, WIDTH * mm, HEIGHT * mm)
paragraph.drawOn(c, x_offset * mm, y_offset * mm)
c.showPage()
c.save()
# Merge the overlay with the template, then write it to file
output = PdfFileWriter()
overlay = PdfFileReader(overlay_pdf_buffer)
# We need a page to overlay on.
# So that we don't have to open the template
# several times, we open a blank pdf several times instead
# (much faster)
final_certificate = copy.copy(BLANK_PDFS['landscape-letter']).getPage(0)
final_certificate.mergePage(self.template_pdf.getPage(0))
final_certificate.mergePage(overlay.getPage(0))
output.addPage(final_certificate)
self._ensure_dir(filename)
outputStream = file(filename, "wb")
output.write(outputStream)
outputStream.close()
self._generate_verification_page(
student_name,
filename,
verify_dir,
verify_uuid,
download_url
)
return (download_uuid, verify_uuid, download_url)
def _generate_mit_pe_certificate(
self,
student_name,
download_dir,
verify_dir,
filename=TARGET_FILENAME,
grade=None,
designation=None,
):
"""
Generate the BigDataX certs
"""
# 8.5x11 page size 279.4mm x 215.9mm
WIDTH = 279 # width in mm (8.5x11)
HEIGHT = 216 # height in mm (8.5x11)
download_uuid = uuid.uuid4().hex
verify_uuid = uuid.uuid4().hex
download_url = "{base_url}/{cert}/{uuid}/{file}".format(
base_url=settings.CERT_DOWNLOAD_URL,
cert=S3_CERT_PATH, uuid=download_uuid, file=filename
)
filename = os.path.join(download_dir, download_uuid, filename)
# This file is overlaid on the template certificate
overlay_pdf_buffer = StringIO.StringIO()
c = canvas.Canvas(overlay_pdf_buffer)
c.setPageSize((WIDTH * mm, HEIGHT * mm))
# STYLE: grid/layout
LEFT_INDENT = 10 # mm from the left side to write the text
MAX_WIDTH = 260 # maximum width on the content in the cert, used for wrapping
# STYLE: template-wide typography settings
style_type_name_size = 36
style_type_name_leading = 53
style_type_name_med_size = 22
style_type_name_med_leading = 27
style_type_name_small_size = 18
style_type_name_small_leading = 21
# STYLE: template-wide color settings
style_color_name = colors.Color(0.000000, 0.000000, 0.000000)
# STYLE: positioning
pos_name_y = 137
pos_name_med_y = 142
pos_name_small_y = 140
pos_name_no_wrap_offset_y = 2
# HTML Parser
# Since the final string is HTML in a PDF we need to un-escape the html
# when calculating the string width.
html = HTMLParser()
# ELEM: Student Name
# default is to use Garamond for the name,
# will fall back to Arial if there are
# unusual characters
y_offset_name = pos_name_y
y_offset_name_med = pos_name_med_y
y_offset_name_small = pos_name_small_y
styleUnicode = ParagraphStyle(name="arial", leading=10, fontName='Arial Unicode')
styleGaramondStudentName = ParagraphStyle(name="garamond", fontName='Garamond-Bold')
styleGaramondStudentName.leading = style_type_name_small_size
style = styleGaramondStudentName
html_student_name = html.unescape(student_name)
larger_width = stringWidth(html_student_name.decode('utf-8'),
'Garamond-Bold', style_type_name_size) / mm
smaller_width = stringWidth(html_student_name.decode('utf-8'),
'Garamond-Bold', style_type_name_small_size) / mm
paragraph_string = arabic_reshaper.reshape(student_name.decode('utf-8'))
paragraph_string = get_display(paragraph_string)
# Garamond only supports Latin-1
# if we can't use it, use Arial
if self._use_unicode_font(student_name):
style = styleUnicode
larger_width = stringWidth(html_student_name.decode('utf-8'),
'Arial Unicode', style_type_name_size) / mm
# if the name is too long, shrink the font size
if larger_width < MAX_WIDTH:
style.fontSize = style_type_name_size
style.leading = style_type_name_leading
y_offset = y_offset_name
elif smaller_width < MAX_WIDTH:
y_offset = y_offset_name_med + pos_name_no_wrap_offset_y
style.fontSize = style_type_name_med_size
style.leading = style_type_name_med_leading
else:
y_offset = y_offset_name_small