def makeTestDoc(fontNames): filename = outputfile('test_pdfbase_pdfmetrics.pdf') c = Canvas(filename) c.bookmarkPage('Glyph Width Tests') c.showOutline() c.addOutlineEntry('Glyph Width Tests', 'Glyph Width Tests', level=0) if verbose: print() # get it on a different line to the unittest log output. for fontName in fontNames: if verbose: print('width test for', fontName) makeWidthTestForAllGlyphs(c, fontName) c.showPage() c.save() if verbose: if verbose: print('saved', filename)
def makeTestDoc(fontNames): filename = outputfile("test_pdfbase_pdfmetrics.pdf") c = Canvas(filename) c.bookmarkPage("Glyph Width Tests") c.showOutline() c.addOutlineEntry("Glyph Width Tests", "Glyph Width Tests", level=0) if verbose: print # get it on a different line to the unittest log output. for fontName in fontNames: if verbose: print "width test for", fontName makeWidthTestForAllGlyphs(c, fontName) c.showPage() c.save() if verbose: if verbose: print "saved", filename
def makeTestDoc(fontNames): filename = outputfile('test_pdfbase_pdfmetrics.pdf') c = Canvas(filename) c.bookmarkPage('Glyph Width Tests') c.showOutline() c.addOutlineEntry('Glyph Width Tests', 'Glyph Width Tests', level=0) if verbose: print() # get it on a different line to the unittest log output. for fontName in fontNames: if verbose: print('width test for', fontName) makeWidthTestForAllGlyphs(c, fontName) c.showPage() c.save() if verbose: if verbose: print('saved',filename)
def _doTest(self, filename, mode, desc): "A generic method called by all test real methods." filename = outputfile(self.baseFileName + filename) c = Canvas(filename) # Handle different modes. if mode == 'FullScreen': c.showFullScreen0() elif mode == 'Outline': c.bookmarkPage('page1') c.addOutlineEntry('Token Outline Entry', 'page1') c.showOutline() elif mode == 'UseNone': pass c.setFont('Helvetica', 20) c.drawString(100, 700, desc) c.save() assert fileDoesExist(filename)
def test(srcFiles, values={}, passwd='C2014', outfile=None): srcFiles = sorted(srcFiles, key=basename) registerFont(UnicodeCIDFont('STSong-Light')) from reportlab.pdfbase import ttfonts # font = ttfonts.TTFont('MyFont', r'C:\Windows\Fonts\simhei.ttf') font = ttfonts.TTFont('MyFont', r'msyhbd.ttf') # font = ttfonts.TTFont('MyFont', 'msyhbd.ttf') registerFont(font) user = values.get('user', '') if user: user = user.encode('utf8') name = values.get('name', '').encode('utf8') password = values.get('passwd', '') if password.strip(): passwd = password.encode('utf8') #? if values.get('lab', '') != '': labv = int(values.get('lab', '0')) else: labv = 0 if 0 < labv < 20: lab = ('Lab%d' % labv).encode('utf8') else: lab = u'' # if user.startswith('10132130') and 0<labv<20: # 2013.10.10 if user.startswith('101') and len(user) == 11 and 0 < labv < 20: # 2013.10.10 # outfile = (os.getcwd()+'/'+user.encode('utf8')+'_'+'%02d.c'%labv).encode('utf8') #? outfile = (os.getcwdu() + u'/' + user.encode('utf8') + u'_' + u'%02d.PDF' % labv) if outfile == None: # if srcFiles[0].rfind('.')!=-1: # pdffile = srcFiles[0][:srcFiles[0].rfind('.')] # else: pdffile = srcFiles[0] # 2013.10.10 bname = basename(srcFiles[0]) if bname.rfind('.') != -1: pdffile = bname[:bname.rfind('.')] else: pdffile = bname pdffile = os.getcwd() + '/' + pdffile # 2013.10.10 pdffile = unicode(pdffile.decode('utf8')) #? else: if outfile.rfind('.') != -1: pdffile = outfile[:outfile.rfind('.')] else: pdffile = outfile # 2013.10.10 # pdffile --> pdffile.encode('gbk') if passwd == "C2014": c = Canvas(pdffile.encode('utf8') + '.pdf') else: c = Canvas(pdffile.encode('utf8')+'.pdf',\ encrypt=pdfencrypt.StandardEncryption\ (passwd,ownerPassword='******',canPrint=0,canCopy=0)) # c = Canvas(pdffile+'.pdf') c.showOutline() c.setAuthor(u"LU") c.setTitle(u"2014级程序设计原理与C语言作业") c.setSubject(u"作业") c.setCreator(u"C2PDF") c.setKeywords(['C语言', '程序设计', '作业', '2014级']) blank = "", "" line1 = u"课程名", u"2014级程序设计原理与C语言" + ' ' + u"Principles of Programming & C" chost = u"机器名", wx.GetHostName() cuser = u"用户名", wx.GetUserName() ID = u"学号", user USER = u"姓名", name grade = u"成绩", u" " labName = u"作业名", lab lines = (line1, chost, cuser, ID, USER, blank, labName, grade) c.setFont("MyFont", 12) x, y, delta = 50, 800, 20 for line in lines: c.drawString(x, y, line[0]) from reportlab.lib.colors import pink, black, red, blue, green if line[0] == u"成绩": # c.saveState() c.setFillColor(red) c.setFont("MyFont", 20) y -= 15 c.drawString(x + 70, y, line[1]) c.setFont("MyFont", 12) c.setFillColor(black) # c.restoreState() else: c.drawString(x + 70, y, line[1]) y -= delta filelist = srcFiles s0 = "Table of Contents" c.bookmarkPage(s0, 'FitH') c.addOutlineEntry(s0, s0) for no, f in enumerate(filelist): # c.addOutlineEntry(basename(f),f) # 2013.10.10 c.addOutlineEntry(basename(f).decode('utf8'), f) #? y -= delta # c.drawString(x, y, "%2d: %s"%(no+1,f)) # 2013.10.10 c.drawString(x, y, "%2d: %s" % (no + 1, f.decode('utf8'))) #? c.linkRect("", f, (x, y + delta - 5, x + 400, y - 5), Border='[0 0 0]') t = time.localtime() ctime = '%04d-%02d-%02d %02d:%02d:%02d' % (t.tm_year, t.tm_mon, t.tm_mday, t.tm_hour, t.tm_min, t.tm_sec) c.drawString(x + 70, y - 2 * delta, ctime) c.showPage() for no, f in enumerate(filelist): outOneFile(f, c, no + 1) """ from reportlab.lib.styles import getSampleStyleSheet from reportlab.platypus import Paragraph, Frame styles = getSampleStyleSheet() toc = TableOfContents() PS = ParagraphStyle toc.levelStyles = [ PS(fontName='Times-Bold', fontSize=14, name='TOCHeading1',\ leftIndent=20, firstLineIndent=-20, spaceBefore=5, leading=16), PS(fontSize=12, name='TOCHeading2',\ leftIndent=40, firstLineIndent=-20, spaceBefore=0, leading=12) ] styleN = styles['Normal'] styleH = styles['Heading1'] styleH2 = styles['Heading2'] story = [ ] story.append(Paragraph("This is a Heading<font size=54> abc[α] <greek>e</greek> <greek>p</greek> </font>",styleH)) story.append(Spacer(inch,inch)) story.append(Paragraph("This is a paragraph in <i>Normal</i> style.", styleN)) story.append(Paragraph("This is a Heading2 style.", styleH2)) toc.addEntry(0, 'txt', 1) toc.addEntry(1, 'txt1', 2) story.append(toc) f = Frame(inch, inch, 6*inch, 9*inch, showBoundary=1) f.addFromList(story,c) """ c.save() # print 'saved PDF file for '+pdffile return pdffile + u'.pdf'
def compile_PDF(request, book, PDF_file, size=None): print "The selected size pre is:" print size if size is None: size = request.REQUEST.get('size',None) limit = request.REQUEST.get('limit',None) if limit: limit = int(limit) print "The selected size post is:" print size canvas = Canvas(PDF_file, pagesize=letter) canvas.setAuthor(book.creator) canvas.setTitle(book.title) djatokaArgs = {'svc.scale':'612,792'} imageArgs = {'x': 0, 'y': 0, 'height': letter[1], 'width': letter[0], 'preserveAspectRatio': False, 'anchor': 'c'} try: page = book.pages.get(internal=False,title='front',jp2__isnull=False) set_image_params(page.jp2, djatokaArgs, imageArgs, size) canvas.drawImage(get_djatoka_url(page.jp2, **djatokaArgs), **imageArgs) canvas.showPage() except Page.DoesNotExist: pass pages = book.pages.filter(internal=True).order_by('sequence') if limit and len(pages) > limit: pages = pages[:limit] start = None length = 1 count = 0 for page in pages: if page.jp2: if start is not None: add_blank_page_range(canvas, book, start, length) start = None ''' print "In pdf.py, here are the djatokaArgs:" for x in djatokaArgs.items(): print x print "In pdf.py, here are the imageArgs:" for x in imageArgs.items(): print x ''' count += 1 print count '''print page.jp2 print get_djatoka_url(page.jp2, **djatokaArgs) metadata = get_djatoka_metadata(page.jp2) height = int(metadata['height']) width = int(metadata['width'])''' set_image_params(page.jp2, djatokaArgs, imageArgs, size) #height_prime = int(djatokaArgs['svc.scale'].split(',')[1]) print "width:height prime is:" print imageArgs['width'] print imageArgs['height'] #imageArgs['width'] = int((width * height_prime) / height) #imageArgs['height'] = height_prime canvas.setPageSize((imageArgs['width'], imageArgs['height'])) canvas.drawImage(get_djatoka_url(page.jp2, **djatokaArgs), **imageArgs) for annotation in book.annotations.filter(offset=page.sequence): canvas.bookmarkPage(str(annotation.pk)) canvas.showPage() else: if start is None: start = page.sequence length = 1 else: length += 1 if start is not None: add_blank_page_range(canvas, book, start, length) if limit: for annotation in book.annotations.filter(offset__gt=limit): canvas.bookmarkPage(str(annotation.pk)) for external in ('back', 'top', 'bottom', 'side', 'spine', ): try: page = book.pages.get(internal=False, title=external,jp2__isnull=False) canvas.drawImage(get_djatoka_url(page.jp2, **djatokaArgs), **imageArgs) canvas.showPage() except Page.DoesNotExist: pass for annotation in book.top_level_structure: add_annotation(canvas, book, annotation) canvas.save() PDF_file.seek(0) # Once completed send out the completion emails # Rename file to .pdf os.rename(PDF_file.name, PDF_file.name + ".pdf") uid = request.session.get('_auth_user_id') if uid is not None: user = User.objects.get(pk=uid) print user.username, user.get_full_name(), user.email send_mail('PDF Compilation completed', 'Dear ' + user.get_full_name() + ',\n\nYour PDF has been completed and is now available here: \n\n' + request.build_absolute_uri(), '*****@*****.**', [user.email], fail_silently=True)