def add_font(fontname, path=None): FONTNAME = fontname.upper() if FONTNAME not in fontnames: if path is None: print path def addit(args, d, names): # if 'CustomerFonts' in d: # return ## skip proprietary fonts for fn in names: FN = fn.upper() if FN[:-4] == FONTNAME and FN[-4:] == '.TTF': pdfmetrics.registerFont(TTFont(FN[:-4], os.path.join(d, fn))) fontnames.append(FONTNAME) if not os.path.exists(os.path.join('/home/justin/Dropbox/WyoLumCode/fonts/', fn)): shutil.copy(os.path.join(d, fn), os.path.join('/home/justin/Dropbox/WyoLumCode/fonts/', fn)) break for fontdir in fontpath: os.path.walk(fontdir, addit, ()) if FONTNAME in fontnames: break else: path = '%s/%s.ttf' % (path, fontname) pdfmetrics.registerFont(TTFont(FONTNAME, path)) fontnames.append(FONTNAME) return FONTNAME in fontnames
def load_invisible_font(self): font = """ eJzdlk1sG0UUx/+zs3btNEmrUKpCPxikSqRS4jpfFURUagmkEQQoiRXgAl07Y3vL2mvt2ml8APXG hQPiUEGEVDhWVHyIC1REPSAhBOWA+BCgSoULUqsKcWhVBKjhzfPU+VCi3Flrdn7vzZv33ryZ3TUE gC6chsTx8fHck1ONd98D0jnS7jn26GPjyMIleZhk9fT0wcHFl1/9GRDPkTxTqHg1dMkzJH9CbbTk xbWlJfKEdB+Np0pBswi+nH/Nvay92VtfJp4nvEztUJkUHXsdksUOkveXK/X5FNuLD838ICx4dv4N I1e8+ZqbxwCNP2jyqXoV/fmhy+WW/2SqFsb1pX68SfEpZ/TCrI3aHzcP//jitodvYmvL+6Xcr5mV vb1ScCzRnPRPfz+LsRSWNasuwRrZlh1sx0E8AriddyzEDfE6EkglFhJDJO5u9fJbFJ0etEMB78D5 4Djm/7kjT0wqhSNURyS+u/2MGJKRu+0ExNkrt1pJti9p2x6b3TBJgmUXuzgnDmI8UWMbkVxeinCw Mo311/l/v3rF7+01D+OkZYE0PrbsYAu+sSyxU0jLLtIiYzmBrFiwnCT9FcsdOOK8ZHbFleSn0znP nDCnxbnAnGT9JeYtrP+FOcV8nTlNnsoc3bBAD85adtCNRcsSffjBsoseca/lBE7Q09LiJOm/ttyB 0+IqcwfncJt5q4krO5k7jV7uY+5m7mPebuLKUea7iHvk48w72OYF5rvZT8C8k/WvMN/Dc19j3s02 bzPvZZv3me9j/ox5P9t/xdzPzPVJcc7yGnPL/1+GO1lPVTXM+VNWOTRRg0YRHgrUK5yj1kvaEA1E xAWiCtl4qJL2ADKkG6Q3XxYjzEcR0E9hCj5KtBd1xCxp6jV5mKP7LJBr1nTRK2h1TvU2w0akCmGl 5lWbBzJqMJsdyaijQaCm/FK5HqspHetoTtMsn4LO0T2mlqcwmlTVOT/28wGhCVKiNANKLiJRlxqB F603axQznIzRhDSq6EWZ4UUs+xud0VHsh1U1kMlmNwu9kTuFaRqpURU0VS3PVmZ0iE7gct0MG/8+ 2fmUvKlfRLYmisd1w8pk1LSu1XUlryM1MNTH9epTftWv+16gIh1oL9abJZyjrfF5a4qccp3oFAcz Wxxx4DpvlaKKxuytRDzeth5rW4W8qBFesvEX8RFRmLBHoB+TpCmRVCCb1gFCruzHqhhW6+qUF6tC pL26nlWN2K+W1LhRjxlVGKmRTFYVo7CiJug09E+GJb+QocMCPMWBK1wvEOfRFF2U0klK8CppqqvG pylRc2Zn+XDQWZIL8iO5KC9S+1RekOex1uOyZGR/w/Hf1lhzqVfFsxE39B/ws7Rm3N3nDrhPuMfc w3R/aE28KsfY2J+RPNp+j+KaOoCey4h+Dd48b9O5G0v2K7j0AM6s+5WQ/E0wVoK+pA6/3bup7bJf CMGjwvxTsr74/f/F95m3TH9x8o0/TU//N+7/D/ScVcA= """ ttf = cStringIO.StringIO(zlib.decompress(base64.decodestring(font))) pdfmetrics.registerFont(TTFont('invisible', ttf))
def generate_pdf(filename, uid, start, count, cate=None, with_head=True, capacity=50*1024): #########Set FONT################ from xhtml2pdf.default import DEFAULT_FONT from xhtml2pdf.document import pisaDocument from reportlab.pdfbase import pdfmetrics from reportlab.pdfbase.ttfonts import TTFont pdfmetrics.registerFont(TTFont('zhfont', os.path.join(app.root_path, 'static/font/yahei-consolas.ttf'))) DEFAULT_FONT["helvetica"] = "zhfont" css = open(os.path.join(app.root_path, "static/css/pdf.css")).read() #result = StringIO.StringIO() full_file_name = get_pdf_full_filename(filename) if not full_file_name: return None result = open(full_file_name, 'wb', 1024*1000) user = User.get(uid) if not user: return None # get status ids = Status.get_ids(user_id=uid, start=start, limit=count, cate=cate) status_list = Status.gets(ids) _html = render(user, status_list, with_head) _pdf = pisaDocument(_html, result, default_css=css, link_callback=link_callback, capacity=capacity) result.close() if not _pdf.err: return full_file_name else: return None
def get_paragraph_styles(): from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle from reportlab.lib.enums import TA_JUSTIFY, TA_RIGHT, TA_CENTER from reportlab.pdfbase import pdfmetrics from reportlab.pdfbase.ttfonts import TTFont pdfmetrics.registerFont(TTFont('Persian', 'Bahij-Nazanin-Regular.ttf')) pdfmetrics.registerFont(TTFont('Persian-Bold', 'Bahij-Nazanin-Bold.ttf')) styles = getSampleStyleSheet() styles.add(ParagraphStyle(name='Justify', alignment=TA_JUSTIFY, fontName='Persian', fontSize=10, wordWrap='CJK')) styles.add(ParagraphStyle(name='Justify-Bold', alignment=TA_JUSTIFY, fontName='Persian-Bold', fontSize=10, wordWrap='CJK')) styles.add(ParagraphStyle(name='Right-indented', alignment=TA_RIGHT, fontName='Persian', fontSize=10, rightIndent=10, wordWrap='CJK')) styles.add(ParagraphStyle(name='Right', alignment=TA_RIGHT, fontName='Persian', fontSize=10, rightIndent=10, wordWrap='CJK')) styles.add(ParagraphStyle(name='Right-with-space', alignment=TA_RIGHT, fontName='Persian', fontSize=10, rightIndent=10, wordWrap='CJK', spaceBefore=12, spaceAfter=12, bulletAnchor='end', bulletIndent=5)) styles.add(ParagraphStyle(name='Right-Bold', alignment=TA_RIGHT, fontName='Persian-Bold', fontSize=10, wordWrap='CJK')) styles.add(ParagraphStyle(name='Right-Bold-Titr', alignment=TA_RIGHT, fontName='Persian-Bold', fontSize=12, textColor=colors.cornflowerblue, wordWrap='CJK')) styles.add(ParagraphStyle(name='Right-small', alignment=TA_RIGHT, fontName='Persian', fontSize=8, rightIndent=20, wordWrap='CJK')) styles.add(ParagraphStyle(name='Centre', alignment=TA_CENTER, fontName='Persian', fontSize=10, wordWrap='CJK')) styles.add(ParagraphStyle(name='Centre-Bold', alignment=TA_CENTER, fontName='Persian-Bold', fontSize=10, wordWrap='CJK')) return styles
def docinit(self, els): from reportlab.lib.fonts import addMapping from reportlab.pdfbase import pdfmetrics from reportlab.pdfbase.ttfonts import TTFont for node in els: for font in node.findall('registerFont'): name = font.get('fontName').encode('ascii') fname = font.get('fontFile').encode('ascii') if name not in pdfmetrics._fonts: pdfmetrics.registerFont(TTFont(name, fname)) #by default, we map the fontName to each style (bold, italic, bold and italic), so that #if there isn't any font defined for one of these style (via a font family), the system #will fallback on the normal font. addMapping(name, 0, 0, name) #normal addMapping(name, 0, 1, name) #italic addMapping(name, 1, 0, name) #bold addMapping(name, 1, 1, name) #italic and bold #if registerFontFamily is defined, we register the mapping of the fontName to use for each style. for font_family in node.findall('registerFontFamily'): family_name = font_family.get('normal').encode('ascii') if font_family.get('italic'): addMapping(family_name, 0, 1, font_family.get('italic').encode('ascii')) if font_family.get('bold'): addMapping(family_name, 1, 0, font_family.get('bold').encode('ascii')) if font_family.get('boldItalic'): addMapping(family_name, 1, 1, font_family.get('boldItalic').encode('ascii'))
def test(): # only works if you have cirrect encodings on your box! c = Canvas('test_japanese.pdf') c.setFont('Helvetica', 30) c.drawString(100,700, 'Japanese Font Support') pdfmetrics.registerFont(CIDFont('HeiseiMin-W3','90ms-RKSJ-H')) pdfmetrics.registerFont(CIDFont('HeiseiKakuGo-W5','90ms-RKSJ-H')) # the two typefaces c.setFont('HeiseiMin-W3-90ms-RKSJ-H', 16) # this says "This is HeiseiMincho" in shift-JIS. Not all our readers # have a Japanese PC, so I escaped it. On a Japanese-capable # system, print the string to see Kanji message1 = '\202\261\202\352\202\315\225\275\220\254\226\276\222\251\202\305\202\267\201B' c.drawString(100, 675, message1) c.save() print 'saved test_japanese.pdf' ## print 'CMAP_DIR = ', CMAP_DIR ## tf1 = CIDTypeFace('HeiseiMin-W3') ## print 'ascent = ',tf1.ascent ## print 'descent = ',tf1.descent ## for cid in [1,2,3,4,5,18,19,28,231,1742]: ## print 'width of cid %d = %d' % (cid, tf1.getCharWidth(cid)) encName = '90ms-RKSJ-H' enc = CIDEncoding(encName) print message1, '->', enc.translate(message1) f = CIDFont('HeiseiMin-W3','90ms-RKSJ-H') print 'width = %0.2f' % f.stringWidth(message1, 10)
def __init__(self, regFont='Anonymous Pro', pdfDir=gettempdir()): self.pdfDir = pdfDir for root, dirs, files in os.walk(os.getcwd()): #to find Fonts directory regardless of how we're invoked if 'BPmono.ttf' in files: fontDir = root self.regFont = regFont self.boldFont = regFont + ' Bold' self.fontSize = self.fontDict[regFont][2] fileNameReg = fontDir + os.sep + self.fontDict[regFont][0] fileNameBold = fontDir + os.sep + self.fontDict[regFont][1] pdfmetrics.registerFont(TTFont(self.regFont, fileNameReg)) pdfmetrics.registerFont(TTFont(self.boldFont, fileNameBold)) tmpCanv = canvas.Canvas('tmp.pdf') # cW - because 'charWidth' is too damn long self.cW = tmpCanv.stringWidth('W', fontName=regFont, fontSize=self.fontSize) del tmpCanv #---Table styles and widths self.styles = {} for tmpStyle in ['codes', 'clmHeader', 'clmLine', 'clmFooter1', 'clmFooter2', 'rptFooter']: self.styles[tmpStyle] = TableStyle([('VALIGN', (0,0), (-1,-1), 'TOP'), ('ALIGN', (0,0), (-1,-1), 'LEFT'), ('FONT', (0,0), (-1,-1), regFont, self.fontSize), ("BOTTOMPADDING",(0,0),(-1,-1),self.pad), ("TOPPADDING", (0,0),(-1,-1),self.pad), ("RIGHTPADDING", (0,0),(-1,-1),self.pad), ("LEFTPADDING", (0,0),(-1,-1),self.pad)])
def testStringWidth(incFontSize): '''example from the reportlab test set''' from _rl_accel import stringWidthU from reportlab.pdfbase.pdfmetrics import _py_stringWidth, getFont, registerFont, _fonts from reportlab.pdfbase.ttfonts import TTFont ttfn = 'Luxi-Serif' t1fn = 'Times-Roman' registerFont(TTFont(ttfn, "luxiserif.ttf")) ttf = getFont(ttfn) t1f = getFont(t1fn) testCp1252 = 'copyright %s trademark %s registered %s ReportLab! Ol%s!' % (chr(169), chr(153),chr(174), chr(0xe9)) enc='cp1252' senc = 'utf8' intern(senc) ts = 'ABCDEF\xce\x91\xce\xb2G' utext = 'ABCDEF\xce\x91\xce\xb2G'.decode('utf8') fontSize = 12 defns="ttfn t1fn ttf t1f testCp1252 enc senc ts utext fontSize ttf.face ttf.face.charWidths ttf.face.defaultWidth t1f.widths t1f.encName t1f.substitutionFonts _fonts" rcv = getrc(defns) #compute initial ref def tfunc(ts,fn,fontSize,enc): w1 = stringWidthU(ts,fn,fontSize,enc) w2 = _py_stringWidth(ts,fn,fontSize,enc) assert abs(w1-w2)<1e-10,"stringWidthU(%r,%r,%s,%r)-->%r != _py_stringWidth(...)-->%r" % (ts,fn,fontSize,enc,w1,w2) tfunc(testCp1252,t1fn,fontSize,enc) tfunc(ts,t1fn,fontSize,senc) tfunc(utext,t1fn,fontSize,senc) tfunc(ts,ttfn,fontSize,senc) tfunc(testCp1252,ttfn,fontSize,enc) tfunc(utext,ttfn,fontSize,senc) if incFontSize: z = fontSize #simulate adding a reference to fontSize print checkrc(defns,rcv)
def pdftest(text=None): logging.info('pdftest') output = StringIO.StringIO() # pdfmetrics.registerTypeFace(pdfmetrics.EmbeddedType1Face( # os.path.join(folderFonts, 'DarkGardenMK.afm'), # os.path.join(folderFonts, 'DarkGardenMK.pfb'))) # pdfmetrics.registerFont(pdfmetrics.Font( # 'DarkGardenMK', 'DarkGardenMK', 'WinAnsiEncoding')) # pdfmetrics.registerFont(TTFont('Vera', os.path.join(folderFonts,'Vera.ttf'))) pdfmetrics.registerFont(TTFont('DejaVuSansMono', os.path.join(folderFonts,'DejaVuSansMono.ttf'))) c = canvas.Canvas(output) #c.setFont('DarkGardenMK', 16) c.setFont('DejaVuSansMono', 16) if text: c.drawString(100,100,text) else: c.drawString(100,100,'pdftest') c.showPage() c.save() logging.info('ok') return output.getvalue()
def get_font(d, font_paths, font_key="fontName", size_key="fontSize"): if font_key in d: font_name = d[font_key] resolved = False try: getTypeFace(font_name) resolved = True except: if font_paths is not None: for path in font_paths: try: registerFont(TTFont(font_name, os.path.join(path, "{0}.ttf".format(font_name)))) resolved = True break except: pass if not resolved: raise Exception("Could not locate font {0}".format(font_name)) else: font_name = shapes.STATE_DEFAULTS["fontName"] font_size = d.get(size_key, shapes.STATE_DEFAULTS["fontSize"]) return (font_name, font_size)
def print_rep(uid): registerFont(TTFont('DroidSans', 'DroidSans.ttf')) pdf = StringIO() doc = SimpleDocTemplate(pdf, pagesize=A4) elements = [] style = getSampleStyleSheet() style.add(ParagraphStyle(name='Header', alignment=TA_LEFT, fontName='DroidSans', fontSize=14, leading=16)) style.add(ParagraphStyle(name='Left', alignment=TA_LEFT, fontName='DroidSans', fontSize=12)) style.add(ParagraphStyle(name='Right', alignment=TA_RIGHT, fontName='DroidSans', fontSize=12)) if uid == 0: elements.append(Paragraph(u'<u>Users List</u>', style['Header'])) u = User.query.all() for i, o in enumerate(u): elements.append(Paragraph(u'%s. %s %s %s' % (i+1, o.name, o.email, o.progress), style['Left'])) else: u = User.query.get(uid) elements.append(Paragraph(u'%s %s %s' % (u.name, u.email, u.progress), style['Header'])) doc.build(elements) pdf_file = pdf.getvalue() pdf.close() response = make_response(pdf_file) response.headers['Content-Disposition'] = "attachment; filename='pdf_user.pdf" response.mimetype = 'application/pdf' return response
def test_instanceStringWidth(self): from reportlab.pdfbase.pdfmetrics import registerFont, getFont, _fonts, unicode2T1 from reportlab.pdfbase.ttfonts import TTFont ttfn = 'Vera' t1fn = 'Times-Roman' registerFont(TTFont(ttfn, "Vera.ttf")) ttf = getFont(ttfn) t1f = getFont(t1fn) testCp1252 = b'copyright \xa9 trademark \x99 registered \xae ReportLab! Ol\xe9!' enc='cp1252' senc = 'utf8' ts = b'ABCDEF\xce\x91\xce\xb2G' utext = b'ABCDEF\xce\x91\xce\xb2G'.decode(senc) fontSize = 12 defns="ttfn t1fn ttf t1f testCp1252 enc senc ts utext fontSize ttf.face ttf.face.charWidths ttf.face.defaultWidth t1f.widths t1f.encName t1f.substitutionFonts _fonts" import sys F = [] def tfunc(f,ts,fontSize,enc,funcs,i): w1 = funcs[i][0](f,ts,fontSize,enc) w2 = funcs[1][0](f,ts,fontSize,enc) #python version if abs(w1-w2)>=1e-10: F.append("stringWidth%s(%r,%r,%s,%r)-->%r != f._py_stringWidth(...)-->%r" % (fontType,f,ts,fontSize,enc,w1,w2)) for font,fontType in ((t1f,'T1'),(ttf,'TTF')): funcs = getFuncs('instanceStringWidth'+fontType) for i,kind in enumerate(('c','py')): for j in (3,2,1,0): #we run several times to allow the refcounts to stabilize if j: rcv = getrc(defns) tfunc(font,testCp1252,fontSize,enc,funcs,i) tfunc(font,ts,fontSize,senc,funcs,i) tfunc(font,utext,fontSize,senc,funcs,i) if not j: rcc = checkrc(defns,rcv) if rcc: F.append("%s %s refcount diffs (%s)" % (fontType,kind,rcc)) assert not F,"instanceStringWidth failures\n\t%s" % '\n\t'.join(F)
def _setup(): from reportlab.pdfbase import pdfmetrics, ttfonts pdfmetrics.registerFont(ttfonts.TTFont("Vera", "Vera.ttf")) pdfmetrics.registerFont(ttfonts.TTFont("VeraBd", "VeraBd.ttf")) pdfmetrics.registerFont(ttfonts.TTFont("VeraIt", "VeraIt.ttf")) pdfmetrics.registerFont(ttfonts.TTFont("VeraBI", "VeraBI.ttf")) F = ['Times-Roman','Courier','Helvetica','Vera', 'VeraBd', 'VeraIt', 'VeraBI'] if sys.platform=='win32': for name, ttf in [ ('Adventurer Light SF','Advlit.ttf'),('ArialMS','ARIAL.TTF'), ('Arial Unicode MS', 'ARIALUNI.TTF'), ('Book Antiqua','BKANT.TTF'), ('Century Gothic','GOTHIC.TTF'), ('Comic Sans MS', 'COMIC.TTF'), ('Elementary Heavy SF Bold','Vwagh.ttf'), ('Firenze SF','flot.ttf'), ('Garamond','GARA.TTF'), ('Jagger','Rols.ttf'), ('Monotype Corsiva','MTCORSVA.TTF'), ('Seabird SF','seag.ttf'), ('Tahoma','TAHOMA.TTF'), ('VerdanaMS','VERDANA.TTF'), ]: for D in ('c:\WINNT','c:\Windows'): fn = os.path.join(D,'Fonts',ttf) if os.path.isfile(fn): try: f = ttfonts.TTFont(name, fn) pdfmetrics.registerFont(f) F.append(name) except: pass return F
def define(self, name, engine, enginefontname): """Define a new font. ``name`` is the name that will be used for this font in the presentation text. ``engine`` is the font engine. MagicPoint supports several, but mgp2pdf supports only "xfont". ``enginefontname`` is the name of the font according to the font engine. For ``xfont`` it can be "family", "family-weight" or "family-weight-slant". Or it can be a fontconfig pattern. """ if engine != "xfont": raise NotImplementedError("unsupported font engine %s" % engine) if '-' in enginefontname and ':' not in enginefontname: if enginefontname.count('-') == 1: # family-weight family, weight = enginefontname.split('-') weight = self.weights.get(weight, weight) enginefontname = '%s:weight=%s' % (family, weight) elif enginefontname.count('-') == 2: # family-weight-slant family, weight, slant = enginefontname.split('-') weight = self.weights.get(weight, weight) slant = {'i': 'italic', 'r': 'roman'}[slant] enginefontname = '%s:weight=%s:slant=%s' % (family, weight, slant) filename = subprocess.Popen( ['fc-match', enginefontname, '-f', '%{file}'], stdout=subprocess.PIPE).communicate()[0].strip() if not filename: sys.exit('Could not find the font file for %s' % enginefontname) log.debug("Font %s: %s -> %s" % (name, enginefontname, filename)) pdfmetrics.registerFont(TTFont(name, filename)) pdfmetrics.getFont(name) # just see if raises
def add_font(fontname, path=None): fontname = fontname.upper() if fontname not in fontnames: if path is None: def addit(args, d, names): for fn in names: FN = fn.upper() if FN[:-4] == fontname and FN[-4:] == '.TTF': pdfmetrics.registerFont(TTFont(FN[:-4], os.path.join(d, fn))) fontnames.append(fontname) if not os.path.exists(os.path.join('./fonts/', fn)): source = open(os.path.join(d, fn), 'rb') dest = open(os.path.join('./fonts/', fn), 'wb') dest.write(source.read()) dest.close() break for fontdir in fontpath: os.path.walk(fontdir, addit, ()) if fontname in fontnames: break else: path = '%s/%s.ttf' % (path, fontname) pdfmetrics.registerFont(TTFont(fontname, path)) fontnames.append(fontname) return fontname in fontnames
def make_cd_pdf(item_list): # Create CD label list cd_label_list = [] for item in item_list: if 'cd' in item.format and not item.compilation_counter > 1: cd_label_list.extend([item] * item.copies) if not cd_label_list: logging.warning('No CD labels to print.') return logging.info('cd_label_list: ({0}): {1}'.format(len(cd_label_list), [item.name for item in cd_label_list])) # Draw CD labels c = canvas.Canvas(os.path.join(PDF_FOLDER, 'cd-labels.pdf'), pagesize=(130 * mm, 225 * mm)) width, height = (130 * mm, 225 * mm) pdfmetrics.registerFont(TTFont('Garamond', FONT_LOCATION)) for item in cd_label_list: # Clipping path = c.beginPath() path.circle(65 * mm, 105 * mm, 60 * mm) path.circle(65 * mm, 105 * mm, 10 * mm) c.clipPath(path, stroke = 1, fill = 0) # Draw CD image c.drawImage(item.image_path, 5 * mm, 45 * mm, width=120 * mm, height=120 * mm) # Draw image counter on label (1, 2, etc.) if item.image_counter: c.setFont('Garamond', 24) c.drawString(62.5 * mm, 50 * mm, str(item.image_counter)) c.showPage() c.save()
def make_cd_pdf(item_list): """Create CD label pdf""" # Filter non-CD items, copied items, split item bases, compilation items after the first for each CD cd_label_list = [each_item for each_item in item_list if \ each_item.compilation_cd_item_counter <= 1 and 'cd' in each_item.format and \ not (each_item.copies > 1 and not each_item.copy_counter) and \ not (each_item.long and not each_item.side)] if not cd_label_list: logging.warning('No CD labels to print.') return logging.info('cd_label_list: ({0}): {1}'.format(len(cd_label_list), [item.name for item in cd_label_list])) # Draw CD labels c = canvas.Canvas(os.path.join(pdf_folder, 'cd-labels.pdf'), pagesize=(150 * mm, 320 * mm)) width, height = (150 * mm, 320 * mm) pdfmetrics.registerFont(TTFont('Garamond', font_path)) for item in cd_label_list: # Clipping path = c.beginPath() path.circle(81 * mm, 113 * mm, 60 * mm) path.circle(81 * mm, 113 * mm, 11 * mm) c.clipPath(path, stroke = 1, fill = 0) # Draw CD image if not item.counter_image_path: item.counter_image_path = make_cover_image(item) c.drawImage(item.counter_image_path, 20 * mm, 52 * mm, width=120 * mm, height=120 * mm) c.showPage() c.save()
def post(self): file = self.request.files['filedata'][0] filedata = file['body'] filename = file['filename'] # print file['content_type'] if os.path.getsize(save(filename, filedata)) >= 5120: msg = "The File is bigger than 5 KB!" self.render("error.html",msg=msg) else: reload(sys) sys.setdefaultencoding('utf-8') try: html = misaka.html(filedata) from io import BytesIO import misaka import xhtml2pdf.pisa as pisa #解决中文字体 from reportlab.pdfbase import pdfmetrics from reportlab.pdfbase.ttfonts import TTFont pdfmetrics.registerFont(TTFont('msyh', './msyh.ttf')) from xhtml2pdf import default default.DEFAULT_FONT["helvetica"]="msyh" buffer = BytesIO() pdf = pisa.CreatePDF(html,buffer) pdf = buffer.getvalue() buffer.close() saved_file_name = 'attachment; filename=' + file['filename'] + '.pdf' self.set_header("Content-Type", "application/pdf") self.set_header('Content-Disposition', saved_file_name) self.write(pdf) except Exception, e: msg = "The File is not written using markdown!" self.render("error.html",msg=msg)
def make_cd_pdf(images): if not images: msg = 'No images found in folder: ' + folder raise SystemError(msg) images_iter = iter(images) c = canvas.Canvas('cd-labels.pdf', pagesize=(130 * mm, 225 * mm)) width, height = (130 * mm, 225 * mm) pdfmetrics.registerFont(TTFont('Garamond', 'c:/sextus share/garamond8.ttf')) print 'CD pages:', len(images) for image in images: # Clipping path = c.beginPath() path.circle(65 * mm, 105 * mm, 60 * mm) path.circle(65 * mm, 105 * mm, 10 * mm) c.clipPath(path, stroke = 1, fill = 0) img = images_iter.next() img_path = os.path.join(images_folder,img).rsplit('_')[0] + '.jpg' # Draw CD image c.drawImage(img_path, 5 * mm, 45 * mm, width=120 * mm, height=120 * mm) # Draw image counter on label (1, 2, etc.) if img[-2] == '_': c.setFont('Garamond', 24) c.drawString(62.5 * mm, 50 * mm, img[-1]) c.showPage() c.save()
def txt2PDF(path): pdfmetrics.registerFont(TTFont('song', 'SURSONG.TTF')) pdfmetrics.registerFont(TTFont('hei', 'SIMHEI.TTF')) fonts.addMapping('song', 0, 0, 'song') fonts.addMapping('song', 0, 1, 'song') fonts.addMapping('song', 1, 0, 'hei') fonts.addMapping('song', 1, 1, 'hei') f=file(path) content = f.read() contentList = content.split('\n') #print contentList stylesheet=getSampleStyleSheet() normalStyle = copy.deepcopy(stylesheet['Normal']) ###设置PDF中文字字体 normalStyle.fontName ='hei' #字体为黑体 normalStyle.fontSize = 14.5 #字体大小 normalStyle.leading = 30 #行间距 normalStyle.firstLineIndent = 32 #首行缩进 story = [] for text in contentList: #story.append(Paragraph(unicode(text, "utf-8" ), normalStyle)) #story.append(Paragraph(text.decode('utf-8'), normalStyle)) story.append(Paragraph(text.decode('gbk'), normalStyle)) pdfPath = path.split('.')[0] + '.pdf' txtName = path.split('.')[0].split('/')[-1] doc = SimpleDocTemplate(pdfPath, rightMargin=20,leftMargin=20, topMargin=20, bottomMargin=20) doc.build(story)
def __init__(self, path, margin_x=48, margin_y=60, file_name='Untitled.pdf', file_name_S3='Untitled.pdf', is_landscape=False, author=None, title=None): self.path = path self.margin_x = self.origin_x = margin_x self.margin_y = self.origin_y = margin_y self.file_name = file_name self.is_landscape = is_landscape self.author = author self.title = title # embeds "Hand of Sean" font: afmFile = os.path.join(settings.FONT_ROOT, 'HandOfSean.afm') pfbFile = os.path.join(settings.FONT_ROOT, 'HandOfSean.pfb') ttfFile = os.path.join(settings.FONT_ROOT, 'handsean.ttf') justFace = pdfmetrics.EmbeddedType1Face(afmFile, pfbFile) #embeds font faceName = 'HandOfSean' # pulled from AFM file pdfmetrics.registerTypeFace(justFace) justFont = pdfmetrics.Font('HandSean', faceName, 'WinAnsiEncoding') pdfmetrics.registerFont(justFont) pdfmetrics.registerFont(TTFont('HandSean', ttfFile)) response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename=' + self.file_name self.set_orientation(self.is_landscape) self.canvas = canvas.Canvas(self.path + '/' + self.file_name, pagesize=(self.page_width, self.page_height)) if self.author is not None: self.canvas.setAuthor(self.author) if self.title is not None: self.canvas.setTitle(self.title)
def getAFont(): '''register a font that supports most Unicode characters''' I = [] font_name = 'DejaVuSans' I.append([(font_name, 0, 0, font_name), (font_name, 1, 0, font_name + '-Bold'), (font_name, 0, 1, font_name + '-Oblique'), (font_name, 1, 1, font_name + '-BoldOblique'), ]) font_name = 'FreeSerif' I.append([(font_name, 0, 0, font_name), (font_name, 1, 0, font_name + 'Bold'), (font_name, 0, 1, font_name + 'Italic'), (font_name, 1, 1, font_name + 'BoldItalic'), ]) for info in I: n = 0 for font in info: fontName = font[3] try: pdfmetrics.registerFont(ttfonts.TTFont(fontName,fontName + '.ttf')) addMapping(*font) n += 1 except: pass if n==4: return font[0] raise ValueError('could not find suitable font')
def process(self): args = dict(self.getAttributeValues(attrMapping=self.attrMapping)) if 'encoding' in args: font = cidfonts.CIDFont(**args) else: font = cidfonts.UnicodeCIDFont(**args) pdfmetrics.registerFont(font)
def ___test2_all(self): """Dumps out ALl GLYPHS in a CID font. Reach for your microscope :-)""" try: from reportlab.pdfbase.cidfonts import CIDFont, findCMapFile findCMapFile('90ms-RKSJ-H') findCMapFile('Identity-H') except: #don't have the font pack. return silently return pdfmetrics.registerFont(CIDFont('HeiseiMin-W3','Identity-H')) c = Canvas('test_japanese_2.pdf') c.setFont('Helvetica', 30) c.drawString(100,800, 'All Glyphs in Adobe-Japan-1-2 collection!') # the two typefaces c.setFont('HeiseiMin-W3-Identity-H', 2) x0 = 50 y0 = 700 dx = 2 dy = 2 for row in range(256): for cell in range(256): s = chr(row) + chr(cell) x = x0 + cell*dx y = y0 - row*dy c.drawString(x,y,s) c.save() if VERBOSE: print('saved '+outputfile('test_multibyte_jpn.pdf'))
def set_cyrillic_font(self): pdfmetrics.registerFont(TTFont('DejaVuSans', _self_path + u'/' 'DejaVuSans.ttf')) self.pdf.setFont('DejaVuSans', 10) # default font if self.debug: self.pdf.setFillColor(red) else: self.pdf.setFillColor(black)
def test_instanceStringWidth(self): from reportlab.pdfbase.pdfmetrics import registerFont, getFont, _fonts, unicode2T1 from reportlab.pdfbase.ttfonts import TTFont ttfn = 'Vera' t1fn = 'Times-Roman' registerFont(TTFont(ttfn, "Vera.ttf")) ttf = getFont(ttfn) t1f = getFont(t1fn) testCp1252 = 'copyright %s trademark %s registered %s ReportLab! Ol%s!' % (chr(169), chr(153),chr(174), chr(0xe9)) enc='cp1252' senc = 'utf8' ts = 'ABCDEF\xce\x91\xce\xb2G' utext = 'ABCDEF\xce\x91\xce\xb2G'.decode(senc) fontSize = 12 defns="ttfn t1fn ttf t1f testCp1252 enc senc ts utext fontSize ttf.face ttf.face.charWidths ttf.face.defaultWidth t1f.widths t1f.encName t1f.substitutionFonts _fonts" rcv = getrc(defns) def tfunc(f,ts,fontSize,enc): w1 = f.stringWidth(ts,fontSize,enc) w2 = f._py_stringWidth(ts,fontSize,enc) assert abs(w1-w2)<1e-10,"f(%r).stringWidthU(%r,%s,%r)-->%r != f._py_stringWidth(...)-->%r" % (f,ts,fontSize,enc,w1,w2) tfunc(t1f,testCp1252,fontSize,enc) tfunc(t1f,ts,fontSize,senc) tfunc(t1f,utext,fontSize,senc) tfunc(ttf,ts,fontSize,senc) tfunc(ttf,testCp1252,fontSize,enc) tfunc(ttf,utext,fontSize,senc) rcc = checkrc(defns,rcv) assert not rcc, "rc diffs (%s)" % rcc
def docinit(self, els): from reportlab.lib.fonts import addMapping from reportlab.pdfbase import pdfmetrics from reportlab.pdfbase.cidfonts import UnicodeCIDFont from reportlab.pdfbase.ttfonts import TTFont for node in els: # register CID fonts for subnode in node.getElementsByTagName('registerCidFont'): params = dict( faceName=subnode.getAttribute('faceName').encode('utf-8')) font = self.font_resolver('UnicodeCIDFont', params) if font: pdfmetrics.registerFont(font) # register TrueType fonts for subnode in node.getElementsByTagName('registerTTFont'): faceName = subnode.getAttribute('faceName').encode('utf-8') fileName = subnode.getAttribute('fileName').encode('utf-8') subfontIndex = subnode.getAttribute('subfontIndex') if subfontIndex: subfontIndex = int(subfontIndex) else: subfontIndex = 0 params = dict(faceName=faceName, fileName=fileName, subfontIndex=subfontIndex) # Resolvers are recommended to implement cache. font = self.font_resolver('TTFont', params) if font: pdfmetrics.registerFont(font)
def docinit(self, els): from reportlab.lib.fonts import addMapping from reportlab.pdfbase import pdfmetrics from reportlab.pdfbase.ttfonts import TTFont for node in els: for font in node.getElementsByTagName('registerFont'): name = font.getAttribute('fontName').encode('ascii') fname = font.getAttribute('fontFile').encode('ascii') pdfmetrics.registerFont(TTFont(name, fname)) addMapping(name, 0, 0, name) #normal addMapping(name, 0, 1, name) #italic addMapping(name, 1, 0, name) #bold addMapping(name, 1, 1, name) #italic and bold for font in node.getElementsByTagName('registerTTFont'): name = font.getAttribute('faceName').encode('ascii') fname = font.getAttribute('fileName').encode('ascii') pdfmetrics.registerFont(TTFont(name, fname)) # , subfontIndex=subfontIndex for font in node.getElementsByTagName('registerFontFamily'): pdfmetrics.registerFontFamily( font.getAttribute('normal').encode('ascii'), normal = font.getAttribute('normal').encode('ascii'), bold = font.getAttribute('bold').encode('ascii'), italic = font.getAttribute('italic').encode('ascii'), boldItalic = font.getAttribute('boldItalic').encode('ascii') )
def Text(self, o): print(C.CTFontCreateWithName) attrString = Q.CFAttributedStringCreate(Q.kCFAllocatorDefault, o.text, {}) line = Q.CTLineCreateWithAttributedString(attrString) Q.CGContextSetTextPosition(self.context, self.X(o.x), self.Y(o.y)) Q.CTLineDraw(line, self.context) return [''] from reportlab.pdfbase import pdfmetrics from reportlab.pdfbase.ttfonts import TTFont if not os.path.basename(o.font) in self.registeredFonts: pdfmetrics.registerFont(TTFont(os.path.basename(o.font), o.font)) self.registeredFonts.append(os.path.basename(o.font)) if o.fillcolor: self.setFillColor(o.fillcolor) if o.strokecolor: self.setStrokeColor(o.strokecolor) self.reportlabcanvas.setFont(os.path.basename(o.font), o.fontsize) if o.align == 'left': self.reportlabcanvas.drawString(self.X(o.x), self.Y(o.y) - o.fontsize + .17*o.fontsize, o.text) elif o.align == 'center': self.reportlabcanvas.drawCentredString(self.X(o.x), self.Y(o.y) - o.fontsize + .17*o.fontsize, o.text) elif o.align == 'right': self.reportlabcanvas.drawRightString(self.X(o.x), self.Y(o.y) - o.fontsize + .17*o.fontsize, o.text) return ['']
def register_font(font_name, family=""): try: return _registered_font_names[font_name] except KeyError: pass found = ff.getFontsWithAttributes(name=font_name) if not found: # print '%(font_name)s not found, loading default for rl_config %(res)s' % locals() res = rl_config.defaultGraphicsFontName else: descr = found[0] if descr.typeCode == "ttf": font = TTFont(descr.name, descr.fileName) else: face = pdfmetrics.EmbeddedType1Face(descr.metricsFileName, descr.fileName) pdfmetrics.registerTypeFace(face) font = pdfmetrics.Font(font_name, font_name, rl_config.defaultEncoding) pdfmetrics.registerFont(font) res = font_name if 10: from reportlab.lib.fonts import addMapping bold = int("Bold" in font_name) italic = int("Italic" in font_name) addMapping(family or font_name, bold, italic, font_name) _registered_font_names[font_name] = res return res
p = Paragraph( '''<para> {date} - <a href="{url}">{url}</a> - wger Workout Manager {version} </para>'''.format(date=date, url=url, version=get_version()), styleSheet["Normal"]) return p # register new truetype fonts for reportlab pdfmetrics.registerFont( TTFont( 'OpenSans', path_join(settings.SITE_ROOT, 'core/static/fonts/OpenSans-Light.ttf'))) pdfmetrics.registerFont( TTFont( 'OpenSans-Bold', path_join(settings.SITE_ROOT, 'core/static/fonts/OpenSans-Bold.ttf'))) pdfmetrics.registerFont( TTFont( 'OpenSans-Regular', path_join(settings.SITE_ROOT, 'core/static/fonts/OpenSans-Regular.ttf'))) pdfmetrics.registerFont( TTFont( 'OpenSans-Italic', path_join(settings.SITE_ROOT, 'core/static/fonts/OpenSans-LightItalic.ttf')))
def reporteador(self): company = self.env['res.company'].search([], limit=1)[0] reload(sys) sys.setdefaultencoding('iso-8859-1') width, height = A4 # 595 , 842 wReal = width - 30 hReal = height - 40 direccion = self.env['main.parameter.hr'].search([])[0].dir_create_file c = canvas.Canvas(direccion+"a.pdf", pagesize=A4) inicio = 0 pos_inicial = hReal-100 endl = 12 font_size = 10 pagina = 1 textPos = 0 ruta_modulo= os.path.join(os.path.dirname(os.path.abspath(__file__))) pdfmetrics.registerFont(TTFont('Arimo-Bold',ruta_modulo+ '/../../fonts/Arimo-Bold.ttf')) pdfmetrics.registerFont(TTFont('Arimo-BoldItalic',ruta_modulo+ '/../../fonts/Arimo-BoldItalic.ttf')) pdfmetrics.registerFont(TTFont('Arimo-Italic', ruta_modulo+ '/../../fonts/Arimo-Italic.ttf')) pdfmetrics.registerFont(TTFont('Arimo-Regular', ruta_modulo+'/../../fonts/Arimo-Regular.ttf')) employees = self.env['planilla.liquidacion.vacaciones.line'].search([('employee_id','in',self.employee_ids.ids),('planilla_liquidacion_id','=',self.env.context['active_id'])]) for row in employees: employee = row.employee_id contract = row.contract_id for cont in range(2): self.cabecera(c, wReal, hReal,company) c.setFont("Arimo-Bold", 14) c.drawCentredString((wReal/2)+20, pos_inicial, u"CERTIFICADO DE TRABAJO") c.line(205, pos_inicial-2, 400, pos_inicial-2) pagina, pos_inicial = self.verify_linea( c, wReal, hReal, pos_inicial, endl*6, pagina) if cont == 1: pagina, pos_inicial = self.verify_linea( c, wReal, hReal, pos_inicial, endl*-9, pagina) c.setFont("Arimo-Regular", 14) c.setFillColor(white) c.setStrokeColor(black) c.rect(400, pos_inicial-4, 80, endl*2, stroke=1, fill=1) c.setFillColor(black) c.drawString(410, pos_inicial+3, u"CARGO") pagina, pos_inicial = self.verify_linea( c, wReal, hReal, pos_inicial, endl*9, pagina) c.setFont("Arimo-Regular", font_size) c.drawString(30, pos_inicial, u"A QUIEN CORRESPONDA:") pagina, pos_inicial = self.verify_linea( c, wReal, hReal, pos_inicial, endl*8, pagina) style = getSampleStyleSheet()["Normal"] style.leading = 12 style.alignment = 4 sust = " " if employee.gender == 'male': sust = " el Sr. " else: sust = " la Sra. " data = [ [Paragraph("<font size="+str(font_size)+">" + u"Dejamos constancia que" + sust + "<b>" + employee.name_related.upper() + u"</b>, identificado con <b>DNI Nº " + (employee.identification_id if employee.identification_id else '') + u"</b> prestó servicios en nuestra empresa desde el " + (self.date_to_text(contract.date_start)[0] if len(self.date_to_text(contract.date_start)) > 0 else '') + ", hasta el " + (self.date_to_text( contract.date_end)[0] if len(self.date_to_text(contract.date_end)) > 0 else '') + u", desempeñandose como <b>" + (employee.job_id.name if employee.job_id.name else '') + u"</b>, demostrando durante su permanencia responsabilidad, honestidad y dedicación en las labores que le fueron encomendadas. <br/><br/> Extendemos el presente a solicitud del interesado(a) para los fines que estime pertinentes." + "</font>", style)] ] t = Table(data, colWidths=(560-30), rowHeights=(40)) t.setStyle(TableStyle([ ('TEXTFONT', (0, 0), (-1, -1), 'Arimo-Regular'), ('FONTSIZE', (0, 0), (-1, -1), font_size) ])) t.wrapOn(c, 25, pos_inicial) t.drawOn(c, 25, pos_inicial) pagina, pos_inicial = self.verify_linea( c, wReal, hReal, pos_inicial, endl*3, pagina) c.drawString(30, pos_inicial, u"Arequipa, " + self.date_to_text( self.date)[0] if len(self.date_to_text(self.date)) else "_"*13) pagina, pos_inicial = self.verify_linea( c, wReal, hReal, pos_inicial, endl*10, pagina) c.setFont("Arimo-Bold", font_size) # c.drawString(30, pos_inicial, u"p. CALQUIPA") # pagina, pos_inicial = self.verify_linea( # c, wReal, hReal, pos_inicial, endl, pagina) rc =company c.drawString(30, pos_inicial, rc.name) c.setFont("Arimo-Regular", font_size) pagina, pos_inicial = self.verify_linea( c, wReal, hReal, pos_inicial, endl*25, pagina) c.setFont("Arimo-Bold", font_size) c.drawCentredString(width/2.00, pos_inicial, rc.name.upper() if rc.name else '') pagina, pos_inicial = self.verify_linea( c, wReal, hReal, pos_inicial, endl, pagina) c.drawCentredString(width/2.00, pos_inicial, rc.street.capitalize() if rc.street else '') pagina, pos_inicial = self.verify_linea( c, wReal, hReal, pos_inicial, endl, pagina) c.drawCentredString(width/2.00, pos_inicial, ("Tel " + rc.phone) if rc.phone else '') pagina, pos_inicial = self.verify_linea( c, wReal, hReal, pos_inicial, endl, pagina) c.setFillColor(HexColor("#175CBB")) c.drawCentredString( width/2.00, pos_inicial, rc.website if rc.website else '') c.showPage() inicio = 0 pos_inicial = hReal-100 pagina = 1 textPos = 0 c.save()
def generateFloor(self): pdfmetrics.registerFont(TTFont('THSarabunNew', 'THSarabunNew.ttf')) y = 792.52 Building = self.ui.comboBox.currentText() Date = self.date Floor = self.ui.floor.text() self.PicPathFloor = { 'Pic1': self.ui.Pic1.topath(), 'Pic2': self.ui.Pic2.topath(), 'Pic3': self.ui.Pic3.topath(), 'Pic4': self.ui.Pic4.topath(), 'Pic5': self.ui.Pic5.topath(), 'Pic6': self.ui.Pic6.topath(), 'Pic7': self.ui.Pic7.topath(), 'Pic8': self.ui.Pic8.topath(), 'Pic9': self.ui.Pic9.topath(), 'Pic10': self.ui.Pic10.topath(), } A1 = self.ui.A1.text() A2 = self.ui.A2.text() N1 = self.ui.N1.text() N2 = self.ui.N2.text() Location = A1 + A2 + N1 + N2 can = canvas.Canvas('File_merge.pdf', pagesize=(A4)) can.setFillColorRGB(0, 0, 0) can.setFont("Helvetica", 20) if self.ui.CC1.isChecked(): can.drawString(195, y - 630, u'\u2713') else: can.drawString(195, y - 649, u'\u2713') if self.ui.DL1.isChecked(): can.drawString(167, y - 676, u'\u2713') elif self.ui.DL2.isChecked(): can.drawString(275, y - 676, u'\u2713') elif self.ui.DL3.isChecked(): can.drawString(420, y - 676, u'\u2713') can.setFont("THSarabunNew", 14) can.drawString(128, y - 149, Building) can.drawString(433, y - 93, Date) can.drawString(323, y - 120, Floor) can.drawString(425, y - 120, Location) can.drawString(130, y - 214, N1) can.drawString(130, y - 430, N2) can.drawString(166, y - 191, A1) can.drawString(440, y - 191, A2) if self.PicPathFloor['Pic1'] != '': can.drawImage(self.PicPathFloor['Pic1'], 72, y - 597, width=240, height=140, preserveAspectRatio=True) if self.PicPathFloor['Pic2'] != '': can.drawImage(self.PicPathFloor['Pic2'], 315, y - 597, width=240, height=140, preserveAspectRatio=True) can.drawString(135, y - 710, self.ui.textEdit.toPlainText()) can.showPage() can.setFillColorRGB(0, 0, 0) can.setFont("THSarabunNew", 14) can.drawString(128, y - 149, Building) can.drawString(433, y - 93, Date) can.drawString(323, y - 120, Floor) can.drawString(425, y - 120, Location) if self.PicPathFloor['Pic3'] != '': can.drawImage(self.PicPathFloor['Pic3'], 72, y - 315, width=240, height=140, preserveAspectRatio=True) if self.PicPathFloor['Pic4'] != '': can.drawImage(self.PicPathFloor['Pic4'], 315, y - 315, width=240, height=140, preserveAspectRatio=True) if self.PicPathFloor['Pic5'] != '': can.drawImage(self.PicPathFloor['Pic5'], 72, y - 460, width=240, height=140, preserveAspectRatio=True) if self.PicPathFloor['Pic6'] != '': can.drawImage(self.PicPathFloor['Pic6'], 315, y - 460, width=240, height=140, preserveAspectRatio=True) if self.PicPathFloor['Pic7'] != '': can.drawImage(self.PicPathFloor['Pic7'], 72, y - 605, width=240, height=140, preserveAspectRatio=True) if self.PicPathFloor['Pic8'] != '': can.drawImage(self.PicPathFloor['Pic8'], 315, y - 605, width=240, height=140, preserveAspectRatio=True) if self.PicPathFloor['Pic9'] != '': can.drawImage(self.PicPathFloor['Pic9'], 72, y - 750, width=240, height=140, preserveAspectRatio=True) if self.PicPathFloor['Pic10'] != '': can.drawImage(self.PicPathFloor['Pic10'], 315, y - 750, width=240, height=140, preserveAspectRatio=True) can.save() Outpath = os.path.join(BASE_DIR, Building + Location + Floor + '.pdf') base_pdf = pdfrw.PdfReader('Floor.pdf') pdfrw.PdfWriter().write('Temp.pdf', base_pdf) base = pdfrw.PdfReader('Temp.pdf') watermark_pdf = pdfrw.PdfReader('File_merge.pdf') for page in range(len(base.pages)): mark = watermark_pdf.pages[page] merger = pdfrw.PageMerge(base.pages[page]) merger.add(mark).render() writer = pdfrw.PdfWriter() writer.write('Temp.pdf', base) inpfn = 'Temp.pdf' out = pdfrw.PdfWriter() write = pdfrw.PdfReader(inpfn) if self.PicPathFloor['Pic3'] == '': out.addpage(write.pages[0]) out.write(Outpath) else: out.addpages(write.pages) out.write(Outpath) os.remove("Temp.pdf")
def generateBeam(self): pdfmetrics.registerFont(TTFont('THSarabunNew', 'THSarabunNew.ttf')) y = 792.52 Building = self.ui.comboBox3.currentText() Date = self.date Floor = self.ui.floor3.text() self.PicPathBeam = { 'Pic1': self.ui.Pic1_3.topath(), 'Pic2': self.ui.Pic2_3.topath(), 'Pic3': self.ui.Pic3_3.topath(), 'Pic4': self.ui.Pic4_3.topath(), 'Pic5': self.ui.Pic5_3.topath(), 'Pic6': self.ui.Pic6_3.topath(), 'Pic7': self.ui.Pic7_3.topath(), 'Pic8': self.ui.Pic8_3.topath(), 'Pic9': self.ui.Pic9_3.topath(), 'Pic10': self.ui.Pic10_3.topath(), } A1 = self.ui.A1_3.text() N1 = self.ui.N1_3.text() Location = A1 + N1 can = canvas.Canvas('File_merge.pdf', pagesize=(A4)) can.setFillColorRGB(0, 0, 0) can.setFont("Helvetica", 20) if self.ui.CC1_3.isChecked(): can.drawString(195, y - 615, u'\u2713') elif self.ui.CC2_3.isChecked(): can.drawString(386, y - 615, u'\u2713') elif self.ui.CC3_3.isChecked(): can.drawString(195, y - 632, u'\u2713') if self.ui.DL1_3.isChecked(): can.drawString(167, y - 668, u'\u2713') elif self.ui.DL2_3.isChecked(): can.drawString(275, y - 668, u'\u2713') elif self.ui.DL3_3.isChecked(): can.drawString(420, y - 668, u'\u2713') can.setFont("THSarabunNew", 14) can.drawString(128, y - 149, Building) can.drawString(433, y - 93, Date) can.drawString(323, y - 120, Floor) can.drawString(425, y - 120, Location) if self.PicPathBeam['Pic1'] != '': can.drawImage(self.PicPathBeam['Pic1'], 72, y - 580, width=240, height=140, preserveAspectRatio=True) if self.PicPathBeam['Pic2'] != '': can.drawImage(self.PicPathBeam['Pic2'], 315, y - 580, width=240, height=140, preserveAspectRatio=True) can.showPage() can.setFillColorRGB(0, 0, 0) can.setFont("THSarabunNew", 14) can.drawString(128, y - 149, Building) can.drawString(433, y - 93, Date) can.drawString(323, y - 120, Floor) can.drawString(425, y - 120, Location) if self.PicPathBeam['Pic3'] != '': can.drawImage(self.PicPathBeam['Pic3'], 72, y - 315, width=240, height=140, preserveAspectRatio=True) if self.PicPathBeam['Pic4'] != '': can.drawImage(self.PicPathBeam['Pic4'], 315, y - 315, width=240, height=140, preserveAspectRatio=True) if self.PicPathBeam['Pic5'] != '': can.drawImage(self.PicPathBeam['Pic5'], 72, y - 460, width=240, height=140, preserveAspectRatio=True) if self.PicPathBeam['Pic6'] != '': can.drawImage(self.PicPathBeam['Pic6'], 315, y - 460, width=240, height=140, preserveAspectRatio=True) if self.PicPathBeam['Pic7'] != '': can.drawImage(self.PicPathBeam['Pic7'], 72, y - 605, width=240, height=140, preserveAspectRatio=True) if self.PicPathBeam['Pic8'] != '': can.drawImage(self.PicPathBeam['Pic8'], 315, y - 605, width=240, height=140, preserveAspectRatio=True) if self.PicPathBeam['Pic9'] != '': can.drawImage(self.PicPathBeam['Pic9'], 72, y - 750, width=240, height=140, preserveAspectRatio=True) if self.PicPathBeam['Pic10'] != '': can.drawImage(self.PicPathBeam['Pic10'], 315, y - 750, width=240, height=140, preserveAspectRatio=True) can.save() Outpath = os.path.join(BASE_DIR, Building + Location + Floor + '.pdf') base_pdf = pdfrw.PdfReader('Beam.pdf') pdfrw.PdfWriter().write('Temp.pdf', base_pdf) base = pdfrw.PdfReader('Temp.pdf') watermark_pdf = pdfrw.PdfReader('File_merge.pdf') for page in range(len(base.pages)): mark = watermark_pdf.pages[page] merger = pdfrw.PageMerge(base.pages[page]) merger.add(mark).render() writer = pdfrw.PdfWriter() writer.write('Temp.pdf', base) inpfn = 'Temp.pdf' out = pdfrw.PdfWriter() write = pdfrw.PdfReader(inpfn) if self.PicPathBeam['Pic3'] == '': out.addpage(write.pages[0]) out.write(Outpath) else: out.addpages(write.pages) out.write(Outpath) os.remove("Temp.pdf")
def _register_fonts(self): pdfmetrics.registerFont( TTFont('Open Sans', finders.find('fonts/OpenSans-Regular.ttf'))) pdfmetrics.registerFont( TTFont('Open Sans I', finders.find('fonts/OpenSans-Italic.ttf'))) pdfmetrics.registerFont( TTFont('Open Sans B', finders.find('fonts/OpenSans-Bold.ttf'))) pdfmetrics.registerFont( TTFont('Open Sans B I', finders.find('fonts/OpenSans-BoldItalic.ttf'))) for family, styles in get_fonts().items(): pdfmetrics.registerFont( TTFont(family, finders.find(styles['regular']['truetype']))) if 'italic' in styles: pdfmetrics.registerFont( TTFont(family + ' I', finders.find(styles['italic']['truetype']))) if 'bold' in styles: pdfmetrics.registerFont( TTFont(family + ' B', finders.find(styles['bold']['truetype']))) if 'bolditalic' in styles: pdfmetrics.registerFont( TTFont(family + ' B I', finders.find(styles['bolditalic']['truetype'])))
if k2 == '当前阶段': times, degrees = parse_time_degrees(v2) p_times.append(times) p_degrees.append(degrees) if k2 == '项目概要': p_outlines.append(parse_project_outlines(v2)) if k2 == '项目组成员': p_members.append(pares_project_members(v2)) return p_names, p_times, p_degrees, p_outlines, p_risks, p_stages, p_charges, p_members, p_processes TYPEFACE = 'SimSun' TYPEFACEFILE = 'SimSun.ttf' # 注册字体 pdfmetrics.registerFont(TTFont(TYPEFACE, TYPEFACEFILE)) def drawTitle(content, text=''): ''' 绘画标题 param content 画布 type list param text 标题文本 ''' style = getSampleStyleSheet() ct = style['Normal'] ct.fontName = TYPEFACE ct.fontSize = 18 # 设置行距 ct.leading = 50 # 颜色
def configure_fonts(self): self.fonts = {} for font_alias, font_filename in BaseReport.FONTS.items(): font_path = os.path.join(self.fonts_path, font_filename) pdfmetrics.registerFont(TTFont(font_alias, font_path))
def print_string(pdf_canvas): pdfmetrics.registerFont(UnicodeCIDFont("HeiseiMin-W3")) # フォントの大きさを設定 small_font_size = 8 middle_font_size = 14 big_font_size = 22 # yamlからデータ取得 person_data = data.get_data() photo = Image.open(person_data['photo']) pdf_canvas.drawInlineImage(photo.resize((get_size_photo(photo))), 450, 247) pdf_canvas.setFont('HeiseiMin-W3', small_font_size) pdf_canvas.drawString(105, 309, person_data['name_kana']) pdf_canvas.drawString(100, 212, person_data['address_kana']) pdf_canvas.drawString(100, 137, person_data['address_kana2']) pdf_canvas.drawString(110, 155, person_data['email']) pdf_canvas.drawString(458, 155, person_data['twitter'] or '') pdf_canvas.setFont('HeiseiMin-W3', middle_font_size) today = datetime.date.today() pdf_canvas.drawString(289, 334, str(today.year)) pdf_canvas.drawString(342, 334, str(today.month)) pdf_canvas.drawString(370, 334, str(today.day)) birthday = datetime.date(person_data['birthday']['year'], person_data['birthday']['month'], person_data['birthday']['day']) pdf_canvas.drawString(119, 242, str(birthday.year)) pdf_canvas.drawString(172, 242, str(birthday.month)) pdf_canvas.drawString(210, 242, str(birthday.day)) pdf_canvas.drawString(271, 242, str(get_age(birthday))) if person_data['gender'] == '男': pdf_canvas.drawString(356, 237, "〇") else: pdf_canvas.drawString(381, 237, "〇") pdf_canvas.drawString(100, 189, person_data['address'][0] or '') pdf_canvas.drawString(100, 173, person_data['address'][1] or '') pdf_canvas.drawString(100, 115, person_data['address2'][0] or '') pdf_canvas.drawString(100, 99, person_data['address2'][1] or '') pdf_canvas.drawString(438, 189, person_data['tel']) pdf_canvas.drawString(438, 114, person_data['tel2']) pdf_canvas.drawString(660, 488, person_data['motivation'][0] or '') pdf_canvas.drawString(660, 470, person_data['motivation'][1] or '') pdf_canvas.drawString(660, 452, person_data['motivation'][2] or '') pdf_canvas.drawString(660, 434, person_data['motivation'][3] or '') pdf_canvas.drawString(660, 388, person_data['self_pr'][0] or '') pdf_canvas.drawString(660, 370, person_data['self_pr'][1] or '') pdf_canvas.drawString(660, 352, person_data['self_pr'][2] or '') pdf_canvas.drawString(660, 334, person_data['self_pr'][3] or '') pdf_canvas.drawString(694, 290, str(person_data['dependents'])) if person_data['spouse'] == '有': pdf_canvas.drawString(772, 288, "〇") else: pdf_canvas.drawString(804, 288, "〇") if person_data['supporting_spouse'] == '有': pdf_canvas.drawString(870, 288, "〇") else: pdf_canvas.drawString(902, 288, "〇") pdf_canvas.drawString(955, 293, person_data['commuting_time']) pdf_canvas.drawString(660, 232, person_data['request'][0] or '') pdf_canvas.drawString(660, 214, person_data['request'][1] or '') pdf_canvas.drawString(660, 196, person_data['request'][2] or '') pdf_canvas.drawString(660, 178, person_data['request'][3] or '') pdf_canvas.drawString(660, 160, person_data['request'][4] or '') pdf_canvas.drawString(660, 142, person_data['request'][5] or '') pdf_canvas.drawString(660, 124, person_data['request'][6] or '') pdf_canvas.drawString(660, 106, person_data['request'][7] or '') pdf_canvas.setFont('HeiseiMin-W3', big_font_size) pdf_canvas.drawString(100, 277, person_data['name']) if person_data['is_cellphone']: pdf_canvas.drawString(517, 167, "〇") else: pdf_canvas.drawString(498, 167, "〇") writing_height = 720 delta_height = 30 for ed in person_data['education']: pdf_canvas.drawString(660, writing_height, str(ed['year'])) pdf_canvas.drawString(732, writing_height, str(ed['month'])) pdf_canvas.drawString(765, writing_height, ed['value']) writing_height -= delta_height for ex in person_data['experience']: pdf_canvas.drawString(660, writing_height, str(ex['year'])) pdf_canvas.drawString(732, writing_height, str(ex['month'])) pdf_canvas.drawString(765, writing_height, ex['value']) writing_height -= delta_height pdf_canvas.drawString(850, writing_height, person_data['finish_value']) pdf_canvas.showPage()
def declaration_ulb_darmstadt(deposit_record, user): """ Takes a deposit and creates authors declaration for ULB Darmstadt and returns that. This function follows the corporate design of TUDA. As this is my (Stefans) first approach with reportlab, the way thingys are placed is not really good """ pdf_buffer = io.BytesIO() page_width, page_height = A4 font_path = os.path.join(BASE_DIR, 'deposit', 'declarations', 'fonts') pdfmetrics.registerFont( TTFont("Charter Regular", os.path.join(font_path, 'Charter-Regular.ttf'))) pdfmetrics.registerFont( TTFont("Front Page Regular", os.path.join(font_path, 'FrontPage-Pro-Regular.ttf'))) logo_path = os.path.join(BASE_DIR, 'deposit', 'declarations', 'logos') tu_logo = os.path.join(logo_path, 'tud_logo.png') ulb_logo = os.path.join(logo_path, 'tud_ulb_logo.png') # Create paragraph styles style_text = ParagraphStyle( name='ulb-text', fontName='Charter Regular', fontSize=10, leading=12, ) style_text_center = copy(style_text) style_text_center.alignment = 2 style_subject = ParagraphStyle( name='ulb-subject', fontName='Front Page Regular', fontSize=18, leading=21.6, ) # Create the canvas c = canvas.Canvas(pdf_buffer, pagesize=A4) c.setTitle( 'Erklärung zur Publikation elektronischer Dokumente - {}'.format( deposit_record.paper.title)) c.setAuthor( 'Universitäts- und Landesbibliothek Darmstadt, Team Digitales Publizieren' ) # Green bar c.setFillColor(tuple([i / 255 for i in [0, 157, 129]])) c.rect(15 * mm, page_height - 20 * mm, page_width - 30 * mm, 4 * mm, fill=True, stroke=False) # Black line c.setFillColor((0, 0, 0)) c.rect(15 * mm, page_height - 21.4 * mm, page_width - 30 * mm, 1.2, fill=True, stroke=False) # The logos c.drawInlineImage(tu_logo, 147.3 * mm, page_height - 47.4 * mm, height=22 * mm, width=55 * mm) c.drawInlineImage(ulb_logo, 173.3 * mm, page_height - 69.4 * mm, height=22 * mm, width=21.8 * mm) # Address # The address is aligned with ULB-logo. # Since its anchor is bottom left, we have to move its height down address_text = """Universitäts- und Landesbibliothek Darmstadt<br/> Team Digitales Publizieren<br/> Magdalendenstraße 8<br/> 64289 Darmstadt """ available_width = 100 * mm available_height = 22 * mm address_p = Paragraph(address_text, style_text) used_width, used_height = address_p.wrap(available_width, available_height) address_p.drawOn(c, 15 * mm, page_height - 48.4 * mm - used_height) # Subject subject_text = """ Erklärung zur Publikation elektronischer Dokumente <br/> (Autoren- und Herausgebervertrag) """ available_width = page_width - 30 * mm available_height = 30 subject_p = Paragraph(subject_text, style_subject) used_width, used_height = subject_p.wrap(available_width, available_height) subject_p.drawOn(c, 15 * mm, page_height - 74.4 * mm - used_height) # Main text of the declaration. It's top is going the an arbitrary set point and the remaining height for dynamic generated content is referenced to this point available_width = page_width - 30 * mm available_height = page_height - 20 * mm - 95 * mm main_text = """ Hiermit gestatte ich (im folgenden: Autorin/Autor bzw. Herausgeberin/Herausgeber) der Universitäts- und Landesbibliothek (ULB) Darmstadt, das unten aufgeführte Werk bzw. dessen Teile in elektronischer Form zu den nachfolgend genannten Bedingungen zu publizieren und zur freien Nutzung im Internet anzubieten. Das Einverständnis der Autorinnen und Autoren dazu liegt vor. <br/> <br/> Die Autorin/der Autor bzw. die Herausgeberin/der Herausgeber versichert, dass sie/er berechtigt ist, über die urheberrechtlichen Nutzungsrechte an diesem Werk zu verfügen und dass bisher keine entgegenstehenden Verfügungen getroffen wurde. Sie/er erklärt, dass mit der Veröffentlichung des Werks keine Rechte Dritter verletzt werden und stellt die ULB Darmstadt von etwaigen Ansprüchen Dritter frei. <br/> <br/> Insbesondere gewährt die Autorin/der Autor bzw. die Herausgeberin/der Herausgeber der ULB Darmstadt das Recht, <br/> <br/> """ main_p = Paragraph(main_text, style_text) used_width, used_height = main_p.wrap(available_width, available_height) available_height -= used_height start_height = page_height - 95 * mm - used_height main_p.drawOn(c, 15 * mm, start_height) # Some conditions as numbered list numbered_list = [ 'das Werk auf ihren eigenen Servern zu vervielfältigen und zu speichern sowie über die internationalen Datennetze zugänglich zu machen,', 'das Werk an die Deutsche Nationalbibliothek sowie an bibliothekarische Partnereinrichtungen weiterzugeben, die ebenfalls zur dauerhaften Speicherung berechtigt sind,', 'das Werk in andere Formate zu migrieren, sofern dies zur Nutzung oder Archivierung notwendig ist,', 'die Metadaten frei an Datenbanken oder Verzeichnisse weiterzugeben.' ] # shall take 10mm available_width_number = 10 * mm for idx, item_text in enumerate(numbered_list): # First the number number_p = Paragraph('(' + str(idx + 1) + ')', style_text) used_width, used_height = number_p.wrap(available_width_number, available_height) number_p.drawOn(c, 15 * mm, start_height - used_height) # Then the text. We reduce the width accordingly item_p = Paragraph(item_text, style_text) used_width, used_height = item_p.wrap( available_width - available_width_number, available_height) available_height -= used_height start_height -= used_height item_p.drawOn(c, 25 * mm, start_height) # The choosen license license_text = """ <br/> Das Werk soll zusätzlich unter folgender Lizenz stehen: <br/> <br/> {} """.format(deposit_record.license.name) license_p = Paragraph(license_text, style_text) used_width, used_height = license_p.wrap(available_width, available_height) available_height -= used_height start_height -= used_height license_p.drawOn(c, 15 * mm, start_height) # Next we do title, authors list # Finally the section for signing # If all this does not fit on this page, do it on the next # In theory, this could be not enough space, but I assume this must be > 200 authors or so title = deposit_record.paper.title # max 1024 Chars authors_list = ", ".join( [str(author) for author in deposit_record.paper.authors]) tuprints_id = deposit_record.identifier signer = user.first_name + ' ' + user.last_name work_text = """ <br/> Titel des Werks: {} <br/><br/> Autor/innen: {} <br/><br/> TUPrints-ID (nach Veröffentlichung): {} """.format(title, authors_list, tuprints_id) work_text_p = Paragraph(work_text, style_text) used_width, used_height = work_text_p.wrap(available_width, available_height) available_height -= used_height start_height -= used_height work_text_p.drawOn(c, 15 * mm, start_height) # Location, Date and a line for signing # We set location to Darmstadt and take the current date signer_text = """ Name der Autorin/des Autors bzw. der Herausgeberin/des Herausgebers: {} <br/><br/> """.format(signer) location_date_text = 'Darmstadt, {}'.format( date.today().strftime('%d.%m.%Y')) # We compute the heights beginning from bottom elements start_height = 20 * mm sign_text = Paragraph('(Unterschrift)', style_text_center) used_width, used_height = sign_text.wrap(100 * mm, available_height) sign_text.drawOn(c, page_width - 15 * mm - used_width, start_height) c.rect(page_width - 15 * mm - used_width, start_height, 100 * mm, 0.5, fill=True, stroke=False) location_date_p = Paragraph(location_date_text, style_text) used_width, used_height = location_date_p.wrap(available_width, available_height) available_height -= used_height location_date_p.drawOn(c, 15 * mm, start_height) signer_p = Paragraph(signer_text, style_text) start_height += used_height used_width, used_height = signer_p.wrap(available_width, available_height) available_height -= used_height signer_p.drawOn(c, 15 * mm, start_height) # We like to monitor the available height, to figure out if a second page is necessary # If the remaining height is < 0, we send error to sentry if available_height < 0: logger.error( "While creating letter for ULB Darmstadt, height left was smaller than 0, leading to overlapping text. Deposit Record: {}" .format(deposit_record.pk)) # Finally make page, save and return the BytesIO c.showPage() c.save() return pdf_buffer
def convert2FontPDF(bookDir, pdfFileName, b, pdf, fontlist): # this code is copied from /decapod.genpdf/src global dpi # ignore warning of missing glyphs reportlab.rl_config.warnOnMissingFontGlyphs = 1 # register all fonts if fontlist == "": for i in range(len(b.fonts)): print b.fonts[i] pdfmetrics.registerFont(TTFont("%d" % (i), b.fonts[i])) else: # if 'fontlist' file is available then use the original fonts f = open(fontlist, "r") line = f.readline( ) # Hasan: FIXME: This code might fail if the json file is quite large. This argument needs validation. dict = json.loads(line) # dict = dict.JSONDecoder() for k in dict.keys(): try: pdfmetrics.registerFont(TTFont("%d" % (int(k)), dict[k])) except: print "Error: unknown error" #pdfmetrics.registerFont(TTFont("%d" %(int(k)),"/home/hasan/Desktop/oFonts/Ubuntu-L.ttf")) # Hasan: FIXME: replace/remove this line !!! # aspect/ratio of the pdf page to be generated ar = float(b.pageSize[0]) / float(b.pageSize[1]) for i in range(len(b.pages)): if (verbose > 1): print("Processing page %d" % (b.pages[i].number)) # put image img = Image.open(b.pages[i].image) # width and height of the document image in pixel W = float(img.size[0]) H = float(img.size[1]) # fit document image to PDF page maximizing the displayed area factor = 0.0 # the next few lines check if the height or the width of the page # is the boundary for the size of the rescaled image if (W / H > ar): width = float(b.pageSize[0]) # width of the PDF page in cms height = width / (W / H) factor = b.pageSize[0] / W if (W / H <= ar): height = float(b.pageSize[1]) width = height / (H / W) factor = b.pageSize[1] / H resizeW = (1.0 / 2.54) * width * dpi # width of the image after resizing resizeH = (1.0 / 2.54) * height * dpi # height of the image after resizing factorScalePx = W / (width * dpi / 2.54 ) # this factor is needed to set the # resulting PDF size into relation with the original image size # this is needed to estimate the correct font size # for each page, for each line, put text for j in range(len(b.pages[i].lines)): # iterate through all pages # check if text-line is fontable and if not ignore it # if(b.pages[i].lines[j].checkTokenable() == False or # b.pages[i].lines[j].checkTextable() == False or if (b.pages[i].lines[j].checkFontable() == False): continue # compute the position of the baseline baseLine = b.pages[i].linesPos[j][1] + b.pages[i].lines[j].baseLineY # for each word in text-line for k in range(len(b.pages[i].lines[j].words)): # compute position of character ccPos = b.pages[i].linesPos[j] + b.pages[i].lines[j].wordPos[k] # set font according to information in fontID file textSizePt = b.pages[i].lines[ j].fontHeight / dpi * 72 / factorScalePx if math.isnan( textSizePt ) or textSizePt < 1.0: # Hasan added this 'if': When the size of the text can not be determined, use 6pt (arbitrarily) textSizePt = int(6) wordFont = b.pages[i].lines[j].wordFont[k] if math.isnan(wordFont): wordFont = 0 pdf.setFont("%d" % wordFont, textSizePt) #print "[info] ocro2pdf::convert2FontPDF: computed font size = %d %f" %(b.pages[i].lines[j].fontHeight/dpi*72*factor,factor) #pdf.setFont("Helvetica", b.pages[i].lines[j].fontHeight/dpi*72/factorScalePx) #Hasan: uncommented this line # draw character in correct position if verbose > 1: WORD = b.pages[i].lines[j].words[k] print "font#=%d, size=%dpt:" % ( wordFont, textSizePt), WORD, ccPos[ 0] * factor * cm, baseLine * factor * cm, b.pages[ i].lines[j].words[k] if not math.isnan(ccPos[0] * factor * cm) and not math.isnan( baseLine * factor * cm): pdf.drawString(ccPos[0] * factor * cm, baseLine * factor * cm, b.pages[i].lines[j].words[k]) if verbose > 1: print "" pdf.showPage() # finish PDF page pdf.save() # save PDF to file
#!/usr/bin/env python from reportlab.pdfgen import canvas from reportlab import rl_config import sys from reportlab.lib.pagesizes import A4 from reportlab.pdfbase import pdfmetrics from reportlab.pdfbase.ttfonts import TTFont rl_config.useA85 = 0 rl_config.ttfAsciiReadable = 0 font = 'Times-Roman' if len(sys.argv) == 4: pdfmetrics.registerFont(TTFont('font', sys.argv[3])) font = 'font' top_margin = A4[1] - 72 - 0.5 * 72 bottom_margin = 72 + 0.5 * 72 canv = canvas.Canvas(sys.argv[2], invariant=0) canv.setPageCompression(1) y = 0 tx = None data = open(sys.argv[1], 'r').readlines() for line in data: if y < bottom_margin: if tx: canv.drawText(tx)
:contact: $Author: Hospes, Gerd-Joachim (uidv8815) $ (last change) :date: $Date: 2016/12/01 11:22:29CET $ """ # Import Python Modules -------------------------------------------------------- from reportlab.pdfbase import pdfmetrics from reportlab.pdfbase.ttfonts import TTFont import reportlab.platypus as plat from reportlab.lib import colors from reportlab.lib.units import cm # Import STK Modules ----------------------------------------------------------- from ..base.flowables import TableBase, html_str, url_str, build_table_row, build_table_header, NORMAL_STYLE from ..algo_base.flowables import color_result from ....val.asmt import ValAssessmentStates pdfmetrics.registerFont(TTFont('Calibri', 'Calibri.ttf')) # Defines ---------------------------------------------------------------------- # Table column width definitions SUMMARY_ID_WIDTH = 190 SUMMARY_NAME_WIDTH = 190 SUMMARY_RESULT_WIDTH = 64 # Functions -------------------------------------------------------------------- # Classes ---------------------------------------------------------------------- # these table classes normally provide only a _create method, # some also an Append to add a row class Overview(TableBase): """
__author__ = 'R.Azh' from reportlab.pdfgen import canvas c = canvas.Canvas('hello.pdf') #can be an absolute path or a relative path c.drawString(100, 750, "Welcome to Reportlab") c.save() print('################## change font ######################') from reportlab.pdfbase import pdfmetrics from reportlab.pdfbase.ttfonts import TTFont # add a font that supports farsi # copy Bahij-Nazanin-Regular.ttf into /usr/local/lib/python3.4/dist-packages/reportlab/fonts folder pdfmetrics.registerFont(TTFont('Persian', 'Bahij-Nazanin-Regular.ttf')) c = canvas.Canvas('font.pdf') c.setFont('Persian', 14) c.drawString(100, 750, u"خوش آمدید".encode('utf-8')) c.save() print('################## print farsi ######################') from bidi.algorithm import get_display from rtl import reshaper c = canvas.Canvas('farsi.pdf') c.setFont('Persian', 14) reshaped_text = reshaper.reshape( u"خوش آمدید") # for reshaping and concating words bidi_text = get_display(reshaped_text) # for right to left # c.drawString(100, 750, bidi_text) from hazm import *
#NACHO MAS import sys, os, pyproj import datetime from pylab import * import catalogues, solarsystem, util, sesame import ephem from reportlab.pdfgen import canvas from reportlab.lib.pagesizes import A6, A5, A4, A3, A2, A1, A0, landscape, portrait from reportlab.lib.colors import Color from reportlab.pdfbase import pdfmetrics from reportlab.pdfbase.ttfonts import TTFont pdfmetrics.registerFont(TTFont('arial', 'arial.ttf')) fontscale = 1.8 class styles: def Cross(self, c, x, y): c.saveState() c.setStrokeColor(Color(0., 0., 0., alpha=0.6)) c.setFillColor(Color(0.2, 0.2, 0.8, alpha=0.6)) c.setLineWidth(0.1) c.setFont("Helvetica", 2.5 * fontscale) c.translate(x, y) c.scale(2, 2) c.circle(0, 0, r=0.2, stroke=1, fill=1) p = c.beginPath()
def process(self): args = self.getAttributeValues(valuesOnly=True) font = pdfmetrics.Font(*args) pdfmetrics.registerFont(font)
def register_fonts(): font_path = path.join(path.dirname(__file__), MAIN_FONT_FILE) reportlab.rl_config.warnOnMissingFontGlyphs = 0 pdfmetrics.registerFont(TTFont(MAIN_FONT_NAME, font_path))
from PyPDF2 import PdfFileWriter, PdfFileReader import io from reportlab.pdfgen import canvas from reportlab.pdfbase import pdfmetrics from reportlab.pdfbase.ttfonts import TTFont pdfmetrics.registerFont(TTFont('Roboto', 'RobotoMono-Medium.ttf')) pdfmetrics.registerFont(TTFont('Robotomono', 'RobotoMono-Medium.ttf')) packet = io.BytesIO() # create a new PDF with Reportlab def creatpdf(name, event): can = canvas.Canvas(packet) # can.setFont('Roboto', 5) # can.setFont('Roboto', 70) # To find the font size. for x in range(20, 50, 2): can.setFont('Roboto', x) can.drawString((x - 30) * 40, 295, str(x)) # can.save() can.setFillColorRGB(255, 0, 0) can.setFont('Roboto', 38) # You'll have to determine the following values with the help of the helper file, get_pdf_coordinates.py start = 5 end = 600
def setTTFonts(): global alreadyRegistered if not alreadyRegistered: distribution = pkg_resources.get_distribution('indico-fonts') font_dir = os.path.join(distribution.location, 'indico_fonts') pdfmetrics.registerFont( TTFont('Times-Roman', os.path.join(font_dir, 'LiberationSerif-Regular.ttf'))) pdfmetrics.registerFont( TTFont('Times-Bold', os.path.join(font_dir, 'LiberationSerif-Bold.ttf'))) pdfmetrics.registerFont( TTFont('Times-Italic', os.path.join(font_dir, 'LiberationSerif-Italic.ttf'))) pdfmetrics.registerFont( TTFont('Times-Bold-Italic', os.path.join(font_dir, 'LiberationSerif-BoldItalic.ttf'))) addMapping('Times-Roman', 0, 0, 'Times-Roman') addMapping('Times-Roman', 1, 0, 'Times-Bold') addMapping('Times-Roman', 0, 1, 'Times-Italic') addMapping('Times-Roman', 1, 1, 'Times-Bold-Italic') pdfmetrics.registerFont( TTFont('Sans', os.path.join(font_dir, 'LiberationSans-Regular.ttf'))) pdfmetrics.registerFont( TTFont('Sans-Bold', os.path.join(font_dir, 'LiberationSans-Bold.ttf'))) pdfmetrics.registerFont( TTFont('Sans-Italic', os.path.join(font_dir, 'LiberationSans-Italic.ttf'))) pdfmetrics.registerFont( TTFont('Sans-Bold-Italic', os.path.join(font_dir, 'LiberationSans-BoldItalic.ttf'))) addMapping('Sans', 0, 0, 'Sans') addMapping('Sans', 1, 0, 'Sans-Bold') addMapping('Sans', 0, 1, 'Sans-Italic') addMapping('Sans', 1, 1, 'Sans-Bold-Italic') pdfmetrics.registerFont( TTFont('Courier', os.path.join(font_dir, 'LiberationMono-Regular.ttf'))) pdfmetrics.registerFont( TTFont('Courier-Bold', os.path.join(font_dir, 'LiberationMono-Bold.ttf'))) pdfmetrics.registerFont( TTFont('Courier-Italic', os.path.join(font_dir, 'LiberationMono-Italic.ttf'))) pdfmetrics.registerFont( TTFont('Courier-Bold-Italic', os.path.join(font_dir, 'LiberationMono-BoldItalic.ttf'))) addMapping('Courier', 0, 0, 'Courier') addMapping('Courier', 1, 0, 'Courier-Bold') addMapping('Courier', 0, 1, 'Courier-Italic') addMapping('Courier', 1, 1, 'Courier-Bold-Italic') pdfmetrics.registerFont( TTFont('LinuxLibertine', os.path.join(font_dir, 'LinLibertine_Rah.ttf'))) pdfmetrics.registerFont( TTFont('LinuxLibertine-Bold', os.path.join(font_dir, 'LinLibertine_RBah.ttf'))) pdfmetrics.registerFont( TTFont('LinuxLibertine-Italic', os.path.join(font_dir, 'LinLibertine_RIah.ttf'))) pdfmetrics.registerFont( TTFont('LinuxLibertine-Bold-Italic', os.path.join(font_dir, 'LinLibertine_RBIah.ttf'))) addMapping('LinuxLibertine', 0, 0, 'LinuxLibertine') addMapping('LinuxLibertine', 1, 0, 'LinuxLibertine-Bold') addMapping('LinuxLibertine', 0, 1, 'LinuxLibertine-Italic') addMapping('LinuxLibertine', 1, 1, 'LinuxLibertine-Bold-Italic') pdfmetrics.registerFont( TTFont('Kochi-Mincho', os.path.join(font_dir, 'kochi-mincho-subst.ttf'))) pdfmetrics.registerFont( TTFont('Kochi-Gothic', os.path.join(font_dir, 'kochi-gothic-subst.ttf'))) alreadyRegistered = True
def _set_font(self, size): print(self.font_name, self.font_file) rl_config.autoGenerateMissingTTFName = True pdfmetrics.registerFont(TTFont(self.font_name, self.font_file)) self.canv.setFont(self.font_name, size)
def process(self): args = self.getAttributeValues(valuesOnly=True) font = cidfonts.UnicodeCIDFont(*args) pdfmetrics.registerFont(font)
from lxml import etree, objectify import csv import os from reportlab.lib import colors from reportlab.lib.pagesizes import letter # from reportlab.lib.styles import getSampleStyleSheet from reportlab.lib.units import inch, mm from reportlab.pdfgen import canvas from reportlab.platypus import Paragraph, Table, TableStyle, Image from reportlab.pdfbase.ttfonts import TTFont from reportlab.pdfbase import pdfmetrics from reportlab.lib.styles import ParagraphStyle from reportlab.lib.enums import TA_LEFT, TA_CENTER pdfmetrics.registerFont(TTFont('Georgia', 'Georgia.ttf')) ######################################################################## class PDFOrder(object): """""" #---------------------------------------------------------------------- def __init__(self, csvFile): """Constructor""" self.csvFile = csvFile # self.csvObj = self.getCSV() # print(self.csvObj) #----------------------------------------------------------------------
import os from reportlab.lib import utils from reportlab.lib.pagesizes import A4 from reportlab.pdfgen import canvas from os.path import join, dirname from dotenv import load_dotenv from reportlab.pdfbase import pdfmetrics from reportlab.pdfbase.ttfonts import TTFont from reportlab.pdfbase.pdfmetrics import stringWidth from ftplib import FTP from datetime import datetime #from multiprocessing import Pool #import itertools #from shutil import copyfile #os.chdir('/opt/dbs/convert/') pdfmetrics.registerFont(TTFont('Univers_57_Condensed', 'font/Univers_57_Condensed.ttf')) pdfmetrics.registerFont(TTFont('Univers_67_Condensed_Bold', 'font/Univers_67_Condensed_Bold.ttf')) pdfmetrics.registerFont(TTFont('Univers_LT_67_Condensed_Bold_Oblique', 'font/Univers_LT_67_Condensed_Bold_Oblique.ttf')) def convert_to_pdf(path, file, period): directory = os.getenv('CONVERT_FOLDER_DEST') + '/Invoice_PDF_' + period + '/' #+ path + '/' if not os.path.exists(directory): os.makedirs(directory) c = canvas.Canvas((directory + '%s.pdf' % file.replace('.TXT', '')), pagesize=A4) x = 5 initY = y = 795 space = 11 thisLine = 0 firstPage = True if os.getenv('CONVERT_LOGO') == 'TRUE':
from reportlab.platypus import * from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle from reportlab.lib.pagesizes import A4 from reportlab.pdfbase import pdfmetrics from reportlab.pdfbase.ttfonts import TTFont from contacts.models import Supplier from supplies.models import Supply from projects.models import Project from po.models import PurchaseOrder, Item django.setup() logger = logging.getLogger(__name__) pdfmetrics.registerFont(TTFont('Tahoma', settings.FONT_ROOT + 'Tahoma.ttf')) pdfmetrics.registerFont(TTFont('Garuda', settings.FONT_ROOT + 'Garuda.ttf')) class ProjectPDF(): queryset = Project.objects.filter( purchaseorder__isnull=False).order_by('codename') item_heading_style = [ ('INNERGRID', (0, 0), (-1, -1), 1, colors.CMYKColor(black=60)), ('LINERIGHT', (0, 0), (-1, -1), 1, colors.CMYKColor(black=60)), ('VALIGN', (0, 0), (-1, -1), 'TOP'), ('FONT', (0, 0), (-1, -1), 'Tahoma'), ('TEXTCOLOR', (0, 0), (-1, -1), colors.CMYKColor(black=60)), ('ALIGNMENT', (0, 0), (-1, -1), 'CENTER'), ('PADDING', (0, 1), (-1, -1), 0), ('FONTSIZE', (0, 0), (-1, -1), 10)
############################################################################### # main ############################################################################### if __name__ == '__main__': if len(sys.argv) < 3: raise Exception("syntax: %s <inFile> <inFile> ... <inFile> <outFile>") inFiles = sys.argv[1:-1] outFile = sys.argv[-1] # # setup, measurements # pdfmetrics.registerFont(TTFont('Alpha2', './resources/ChessAlpha2.ttf')) pdfmetrics.registerFont(TTFont('FreeSans', './resources/FreeSans.ttf')) c = canvas.Canvas(outFile, pagesize=letter) unitsPerInch = inch inchesPerUnit = 1.0 / unitsPerInch pageWidth = 8.5 * unitsPerInch # 612 in testing pageHeight = 11.0 * unitsPerInch # 792 in testing margin = MARGIN_INCHES * unitsPerInch printAreaWidth = pageWidth - 2 * margin printAreaHeight = pageHeight - 2 * margin #c.rect(margin + 0, margin + 0, printAreaWidth, printAreaHeight)
import pandas as pd from reportlab.graphics.charts.barcharts import VerticalBarChart from reportlab.graphics.charts.legends import Legend from reportlab.lib.pagesizes import letter # 画图相关 from reportlab.graphics.shapes import Drawing, colors, Auto from reportlab.graphics import renderPDF from reportlab.graphics.charts.lineplots import LinePlot from reportlab.graphics.widgets.markers import makeMarker from reportlab.pdfbase.pdfmetrics import stringWidth from reportlab.pdfbase.ttfonts import TTFont from reportlab.pdfbase import pdfmetrics pdfmetrics.registerFont(TTFont('song', 'SURSONG.TTF')) pdfmetrics.registerFont(TTFont('hei', 'SIMHEI.TTF')) from reportlab.lib import fonts fonts.addMapping('song', 0, 0, 'song') fonts.addMapping('song', 0, 1, 'song') fonts.addMapping('song', 1, 0, 'hei') fonts.addMapping('song', 1, 1, 'hei') def addFront(canvas_param, theme, subtitle, pagesize=letter): """ 函数功能:为pdf文档添加功能,分“主题”、“副标题”两部分 :param canvas: :param pagesize: 页面大小,默认A4 :param theme: 主题字符串
import io from django.conf import settings from plantilla_reporte.funciones.funciones import insert_data_pdf, texto_pdf from reportlab.lib.pagesizes import A4 from reportlab.pdfgen import canvas from django.http import HttpResponse from reportlab.pdfbase.pdfmetrics import registerFont from reportlab.pdfbase.ttfonts import TTFont from datetime import datetime registerFont(TTFont('Arial', 'Arial.ttf')) def reporte(request, datos, nombre, inicio, fin, categoria): ##Esta data nosotros la generaremos con django serán las consultas # esta siendo generado aleatoriamente todo lo saqué de un ejemplo de inter y lo fui modificando response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename={}.pdf'.format( nombre) buffer = io.BytesIO() c = canvas.Canvas(buffer, pagesize=A4) w, h = A4 max_rows_per_page = 25 #Aquí ponemos cuantos registros queremos por páginas # Margin. x_offset = 50 y_offset = 150 # Space between rows. padding = 15 #Imagen c.drawImage(settings.MEDIA_ROOT + '/logo/logo.png', x_offset,
# Copyright ReportLab Europe Ltd.2000 - 2016 # see license.txt for license details __doc__ = '' __version__ = '3.3.0' # REPORTLAB_TEST_SCRIPT import sys from reportlab.platypus import * from reportlab.lib.styles import getSampleStyleSheet from reportlab.rl_config import defaultPageSize from reportlab.lib.fonts import addMapping from reportlab.pdfbase import pdfmetrics from reportlab.pdfbase.ttfonts import TTFont FONT = 'Play' pdfmetrics.registerFont(TTFont(FONT, 'Play-Regular.ttf')) addMapping(FONT, 0, 0, FONT) PAGE_HEIGHT = defaultPageSize[1] PAGE_WIDTH = defaultPageSize[0] styles = getSampleStyleSheet() Title = "Project Report 2" from reportlab.lib.units import inch pageinfo = "%s" % (Title) def pageStyle(canvas, doc):
from datetime import datetime, timedelta from decimal import getcontext, Decimal from os.path import join import pdfrw from reportlab.pdfgen import canvas from reportlab.pdfbase import pdfmetrics from reportlab.pdfbase.ttfonts import TTFont from reportlab.lib.pagesizes import A4, landscape from textwrap import wrap pdfmetrics.registerFont(TTFont('THSarabunNew', 'THSarabunNew.ttf')) y = 792.52 Building = 'Cedar' Date = '18/09/2020' Floor = '4A' Location = '15AB' Damage = 3 #1Severe 2Moderate 3Least can = canvas.Canvas('File_merge.pdf', pagesize=(A4)) can.setFillColorRGB(0, 0, 0) can.setFont("Helvetica", 20) can.drawString(195, y - 630, u'\u2713') if Damage == 1: can.drawString(167, y - 676, u'\u2713') elif Damage == 2: can.drawString(275, y - 676, u'\u2713') elif Damage == 3: can.drawString(420, y - 676, u'\u2713') can.setFont("THSarabunNew", 14)
from reportlab.pdfbase import pdfmetrics from reportlab.pdfbase.ttfonts import TTFont from reportlab.pdfgen import canvas from reportlab.lib.pagesizes import A4 import os import sqlite3 import locale """ # Accion que carga y registra las fuentes que va a usar los informes una vez generados """ pdfmetrics.registerFont(TTFont('MontserratTH', 'Montserrat-Thin.ttf')) pdfmetrics.registerFont(TTFont('Montserrat', 'Montserrat-Regular.ttf')) pdfmetrics.registerFont(TTFont('MontserratBL', 'Montserrat-Bold.ttf')) pdfmetrics.registerFont( TTFont('MontserratAlt', 'MontserratAlternates-Regular.ttf')) """ # Accion que conecta con la BBDD nada mas abrir el programa """ try: bbdd = 'dataBaseRestaurante' conexion = sqlite3.connect(bbdd) cur = conexion.cursor() print('BASE DE DATOS CONECTADA') except sqlite3.OperationalError as e: print(e) def cerrarConexion(): """
def test1(self): "This makes one long multi-page paragraph." # Build story. story = [] styleSheet = getSampleStyleSheet() h3 = styleSheet['Heading3'] bt = styleSheet['BodyText'] text = '''If you imagine that the box of X's tothe left is an image, what I want to be able to do is flow a series of paragraphs around the image so that once the bottom of the image is reached, then text will flow back to the left margin. I know that it would be possible to something like this using tables, but I can't see how to have a generic solution. There are two examples of this in the demonstration section of the reportlab site. If you look at the "minimal" euro python conference brochure, at the end of the timetable section (page 8), there are adverts for "AdSu" and "O'Reilly". I can see how the AdSu one might be done generically, but the O'Reilly, unsure... I guess I'm hoping that I've missed something, and that it's actually easy to do using platypus.We can do greek letters <greek>mDngG</greek>. This should be a u with a dieresis on top <unichar code=0xfc/>="<unichar code="0xfc"/>" and this &#xfc;="ü" and this \\xc3\\xbc="\xc3\xbc". On the other hand this should be a pound sign &pound;="£" and this an alpha &alpha;="α". You can have links in the page <link href="http://www.reportlab.com" color="blue">ReportLab</link> & <a href="http://www.reportlab.org" color="green">ReportLab.org</a>. Use scheme "pdf:" to indicate an external PDF link, "http:", "https:" to indicate an external link eg something to open in your browser. If an internal link begins with something that looks like a scheme, precede with "document:". <strike>This text should have a strike through it.</strike> ''' from reportlab.platypus.flowables import ImageAndFlowables, Image from reportlab.lib.testutils import testsFolder gif = os.path.join(testsFolder, 'pythonpowered.gif') heading = Paragraph('This is a heading', h3) story.append( ImageAndFlowables(Image(gif), [heading, Paragraph(text, bt)])) phrase = 'This should be a paragraph spanning at least three pages. ' description = ''.join([('%d: ' % i) + phrase for i in range(250)]) story.append( ImageAndFlowables(Image(gif), [heading, Paragraph(description, bt)], imageSide='left')) story.append(NextPageTemplate('special')) story.append(PageBreak()) VERA = ('Vera', 'VeraBd', 'VeraIt', 'VeraBI') for v in VERA: registerFont(TTFont(v, v + '.ttf')) registerFontFamily(*(VERA[:1] + VERA)) story.append( ImageAndFlowables( Image(gif, width=280, height=120), Paragraph( '''<font name="Vera">The <b>concept</b> of an <i>integrated</i> one <b><i>box</i></b> solution for <i><b>advanced</b></i> voice and data applications began with the introduction of the IMACS. The IMACS 200 carries on that tradition with an integrated solution optimized for smaller port size applications that the IMACS could not economically address. An array of the most popular interfaces and features from the IMACS has been bundled into a small 2U chassis providing the ultimate in ease of installation.</font>''', style=ParagraphStyle( name="base", fontName="Helvetica", leading=12, leftIndent=0, firstLineIndent=0, spaceBefore=9.5, fontSize=9.5, )), imageSide='left', )) story.append( ImageAndFlowables( Image(gif, width=240, height=120), Paragraph( '''The concept of an integrated one box solution for advanced voice and data applications began with the introduction of the IMACS. The IMACS 200 carries on that tradition with an integrated solution optimized for smaller port size applications that the IMACS could not economically address. An array of the most popular interfaces and features from the IMACS has been bundled into a small 2U chassis providing the ultimate in ease of installation.''', style=ParagraphStyle( name="base", fontName="Helvetica", leading=12, leftIndent=0, firstLineIndent=0, spaceBefore=9.5, fontSize=9.5, )), imageSide='left', )) story.append(PageBreak()) story.append(Paragraph('Image larger than the frame', h3)) story.append( ImageAndFlowables( Image(gif, width=6 * 110, height=6 * 44), Paragraph( '''The concept of an integrated one box solution for advanced voice and data applications began with the introduction of the IMACS. The IMACS 200 carries on that tradition with an integrated solution optimized for smaller port size applications that the IMACS could not economically address. An array of the most popular interfaces and features from the IMACS has been bundled into a small 2U chassis providing the ultimate in ease of installation.''', style=ParagraphStyle( name="base", fontName="Helvetica", leading=12, leftIndent=0, firstLineIndent=0, spaceBefore=9.5, fontSize=9.5, )), imageSide='left', )) doc = MyDocTemplate(outputfile('test_platypus_imageandflowables.pdf'), showBoundary=1) doc.multiBuild(story)