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
def prepare_additional_fonts(self): """This method loads additional fonts and register them using ReportLab PDF metrics package. Just supports TTF fonts, for a while.""" if not self.report.additional_fonts: return for font_family_name, fonts_or_file in self.report.additional_fonts.iteritems(): # Supports font family with many styles (i.e: normal, italic, bold, bold-italic, etc.) if isinstance(fonts_or_file, (list, tuple, dict)): for font_item in fonts_or_file: # List of tuples with format like ('font-name', 'font-file', True/False bold, True/False italic) if isinstance(font_item, (list, tuple)): font_name, font_file, is_bold, is_italic = font_item pdfmetrics.registerFont(TTFont(font_name, font_file)) addMapping(font_family_name, is_bold, is_italic, font_name) # List of dicts with format like {'file': '', 'name': '', 'bold': False, 'italic': False} elif isinstance(font_item, dict): pdfmetrics.registerFont(TTFont(font_item["name"], font_item["file"])) addMapping( font_family_name, font_item.get("bold", False), font_item.get("italic", False), font_item["name"], ) # Old style: font name and file path else: pdfmetrics.registerFont(TTFont(font_family_name, fonts_or_file))
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 getStyle(self): ''' Returns the style (color and font details) specified by the user through a dictionary ''' fontDB = QFontDatabase() matchFont=self.sysFonts.matchingFontName(str(self.elFont.rawName())) qFontStyle=str(fontDB.styleString(self.elFont)) matchFontStyle='' if qFontStyle.find("Normal")!=-1: matchFontStyle=matchFont else: matchFontStyle=matchFont + " " + qFontStyle #Register the fonts to be used in the report fontStyle=self._buildFontFamily() for k,v in fontStyle.iteritems(): #self.InfoMessage(k + ", " + v) pdfmetrics.registerFont(TTFont(k,v)) #Add font mappings psMappings=self._postScriptMappings(fontStyle) for ps in psMappings: addMapping(matchFont,ps["Bold"],ps["Italic"],ps["Style"]) dStyle={} dStyle["fontName"]=matchFontStyle dStyle["fontSize"]=self.elFont.pointSize() dStyle["alignment"]=self.hAlign dStyle["textColor"]=HexColor(str(self.elFontColor.name())) return dStyle
def Create_PDF_into_buffer(html, font_file_path): # # 注册字体 pdfmetrics.registerFont(TTFont('yahei', font_file_path)) # fonts.addMapping('song', 0, 0, 'song') fonts.addMapping('song', 0, 1, 'song') DEFAULT_FONT['helvetica'] = 'yahei' xhtml2pdf.reportlab_paragraph.Paragraph.wrap = wrap return pisaDocument(html)
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 loadFonts(): from reportlab import rl_config rl_config.warnOnMissingFontGlyphs = 0 logger = netsvc.Logger() for dirname in rl_config.TTFSearchPath: for filename in [x for x in os.listdir(dirname) if x.lower().endswith('.ttf') and rl_isreg(x, dirname) ]: try: face = ttfonts.TTFontFace(filename) face.extractInfo(0) # Only header is needed except ttfonts.TTFError, reason: logger.notifyChannel( 'init', netsvc.LOG_WARNING, 'module report_truetype: registration of font file %s failed: %s' % ( filename, reason.message )) else: logger.notifyChannel( 'init', netsvc.LOG_INFO, 'module report_truetype: registering font %s (%s)' % ( face.name, filename )) font = ttfonts.TTFont(face.name, filename) pdfmetrics.registerFont(font) if not font._multiByte: # Already done in registerFont with multi-byte fonts ttname = font.fontName.lower() fonts.addMapping(ttname, 0, 0, font.fontName) fonts.addMapping(ttname, 1, 0, font.fontName) fonts.addMapping(ttname, 0, 1, font.fontName) fonts.addMapping(ttname, 1, 1, font.fontName)
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 run(args): from reportlab.pdfbase import pdfmetrics from reportlab.pdfbase.ttfonts import TTFont from reportlab.lib.fonts import addMapping # Process args parser = argparse.ArgumentParser( formatter_class=argparse.RawDescriptionHelpFormatter, description='Generate calendar pages in PDF format.', epilog='''PyCalendarGen 0.9.5, Copyright (C) 2005-2012 Johan Wärlander PyCalendarGen comes with ABSOLUTELY NO WARRANTY. This is free software, and you are welcome to redistribute it under certain conditions. See the file COPYING for details.''') parser.add_argument('year', type=str, metavar='YYYY', help='The 4-digit starting year for the calendar ' 'page, like 2012.') parser.add_argument('month', type=str, metavar='MM[-NN]', help='The number of the month you want to generate ' 'a page for, like 05 for May. If of the format ' 'MM-NN, it describes a range of up to 12 months. ' 'In this case, if NN < MM, it means the calendar ' 'wraps into month NN of the next year.') parser.add_argument('filename', type=str, nargs='?', help='The name of the PDF file to be written. By ' 'default, it will be named like YYYY-MM.pdf.') parser.add_argument('--cover-image', type=str, metavar='FILENAME', nargs='?', help='Generate a cover page using the specified image.') parser.add_argument('--monthly-image-dir', type=str, metavar='DIRECTORY', nargs='?', help='Generate an opposing page for each month, with ' 'an image taken by cycling through the files of ' 'the specified directory in alphabetical order.') parser.add_argument('-v', '--verbose', action='store_true', help='Verbose output.') args = parser.parse_args() # Load fonts for spec in fonttable: pdfmetrics.registerFont(TTFont(spec[0], spec[1])) for font in fontmap: try: addMapping(font[0], font[1], font[2], font[3]) if args.verbose: print font print "added." except Exception, e: print "Error adding Font:" print e
def run(args): from reportlab.pdfbase import pdfmetrics from reportlab.pdfbase.ttfonts import TTFont from reportlab.lib.fonts import addMapping # Load fonts for spec in fonttable: pdfmetrics.registerFont(TTFont(spec[0], spec[1])) for font in fontmap: addMapping(font[0], font[1], font[2], font[3]) # Font test page if 0: c = Canvas("fonts.pdf", pagesize=portrait(A4)) ypos = 100 for font in fonttable: c.setFont(font[0], 24) c.drawString(100, ypos, font[0]) ypos += 24 c.save() # Process args if len(args) == 4: fname = args[3] else: fname = args[1] + '-' + args[2] + '.pdf' # Draw the calendar c = Canvas(fname, pagesize=landscape(A4)) year = int(args[1]) month = args[2] if len(month.split('-')) > 1: start = int(month.split('-')[0]) end = int(month.split('-')[1]) if end < start: for m in range(12-start+1): drawCalendarPage(c, year, start+m) for m in range(end): drawCalendarPage(c, year+1, 1+m) else: for m in range(end-start+1): drawCalendarPage(c, year, start+m) else: month = int(month) drawCalendarPage(c, year, month) c.save()
def registerReportlabFonts(self, font_list): font_variants = ['', 'bold', 'italic', 'bolditalic'] for font in font_list: if not font.get('name'): continue if font.get('type') == 'cid': pdfmetrics.registerFont(UnicodeCIDFont(font['name'])) else: for (i, font_variant) in enumerate(font_variants): if i == len(font.get('file_names')) or not self.fontInstalled(font): break full_font_name = font['name'] + font_variant pdfmetrics.registerFont(TTFont(full_font_name, self.getAbsFontPath(font.get('file_names')[i]) )) italic = font_variant in ['italic', 'bolditalic'] bold = font_variant in ['bold', 'bolditalic'] addMapping(font['name'], bold, italic, full_font_name)
def writePDF(issue,duzhe): reportlab.rl_config.warnOnMissingFontGlyphs = 0 pdfmetrics.registerFont(TTFont('song',"simsun.ttc")) pdfmetrics.registerFont(TTFont('hei',"msyh.ttc")) fonts.addMapping('song', 0, 0, 'song') fonts.addMapping('song', 0, 1, 'song') fonts.addMapping('song', 1, 0, 'hei') fonts.addMapping('song', 1, 1, 'hei') stylesheet=getSampleStyleSheet() normalStyle = copy.deepcopy(stylesheet['Normal']) normalStyle.fontName ='song' normalStyle.fontSize = 11 normalStyle.leading = 11 normalStyle.firstLineIndent = 20 titleStyle = copy.deepcopy(stylesheet['Normal']) titleStyle.fontName ='song' titleStyle.fontSize = 15 titleStyle.leading = 20 firstTitleStyle = copy.deepcopy(stylesheet['Normal']) firstTitleStyle.fontName ='song' firstTitleStyle.fontSize = 20 firstTitleStyle.leading = 20 firstTitleStyle.firstLineIndent = 50 smallStyle = copy.deepcopy(stylesheet['Normal']) smallStyle.fontName ='song' smallStyle.fontSize = 8 smallStyle.leading = 8 story = [] story.append(Paragraph("<b>读者{0}期</b>".format(issue), firstTitleStyle)) for eachColumn in duzhe: story.append(Paragraph('__'*28, titleStyle)) story.append(Paragraph('<b>{0}</b>'.format(eachColumn), titleStyle)) for eachArticle in duzhe[eachColumn]: story.append(Paragraph(eachArticle["title"],normalStyle)) story.append(flowables.PageBreak()) for eachColumn in duzhe: for eachArticle in duzhe[eachColumn]: story.append(Paragraph("<b>{0}</b>".format(eachArticle["title"]),titleStyle)) story.append(Paragraph(" {0} {1}".format(eachArticle["writer"],eachArticle["from"]),smallStyle)) para=eachArticle["context"].split(" ") for eachPara in para: story.append(Paragraph(eachPara,normalStyle)) story.append(flowables.PageBreak()) #story.append(Paragraph("context",normalStyle)) doc = SimpleDocTemplate("duzhe"+issue+".pdf") print "Writing PDF..." doc.build(story)
def create_styles(self): self.styles = getSampleStyleSheet() if self.config.get('font', '') != '': self.fontName = 'custom_font' fontfilename = self.config.get('font', '') (fontfilenamebase, fontfilenameextension) = os.path.splitext(fontfilename) pdfmetrics.registerFont(TTFont(self.fontName, fontfilename)) addMapping(self.fontName, 0, 0, self.fontName) # build font family if available to support <b> and <i> if os.path.isfile(fontfilenamebase + 'bd' + fontfilenameextension): pdfmetrics.registerFont(TTFont(self.fontName + '-bold', fontfilenamebase + 'bd' + fontfilenameextension)) addMapping(self.fontName, 1, 0, self.fontName + '-bold') if os.path.isfile(fontfilenamebase + 'bi' + fontfilenameextension): pdfmetrics.registerFont(TTFont(self.fontName + '-bolditalic', fontfilenamebase + 'bi' + fontfilenameextension)) addMapping(self.fontName, 1, 1, self.fontName + '-bolditalic') if os.path.isfile(fontfilenamebase + 'i' + fontfilenameextension): pdfmetrics.registerFont(TTFont(self.fontName + '-italic', fontfilenamebase + 'i' + fontfilenameextension)) addMapping(self.fontName, 0, 1, self.fontName + '-italic') else: self.fontName = "Helvetica" if self.config.get('font_size', '') != '': self.base_font_size = int(self.config.get('font_size')) else: self.base_font_size = 18 title_font_size = self.base_font_size heading1_font_size = self.base_font_size - 8 heading2_font_size = self.base_font_size - 3 heading3_font_size = self.base_font_size - 11 normal_font_size = self.base_font_size - 13 if heading1_font_size < 4: heading1_font_size = 4 if heading2_font_size < 4: heading2_font_size = 4 if heading3_font_size < 4: heading3_font_size = 4 if normal_font_size < 4: normal_font_size = 4 # adjust font for (name, style) in self.styles.byName.items(): style.fontName = self.fontName #adjust font sizes self.styles['Title'].fontSize = title_font_size self.styles['Title'].leading = title_font_size + 2 self.styles['Normal'].fontSize = normal_font_size self.styles['Normal'].leading = normal_font_size + 2 self.styles['Heading1'].fontSize = heading1_font_size self.styles['Heading1'].leading = heading1_font_size + 2 self.styles['Heading2'].fontSize = heading2_font_size self.styles['Heading2'].leading = heading2_font_size + 2 self.styles['Heading3'].fontSize = heading3_font_size self.styles['Heading3'].leading = heading3_font_size + 2
def draw(self, invoice, stream): """ Draws the invoice """ # embed unicode font pdfmetrics.registerFont( TTFont('FreeSans', join(STATIC_DIR, 'FreeSans.ttf')) ) addMapping('FreeSans', 0, 0, 'FreeSans') self.baseline = -2*cm canvas = Canvas(stream, pagesize=A4) canvas.setCreator("django-invoice") canvas.setAuthor(smart_text(invoice.contractor)) canvas.setTitle(smart_text(invoice)) canvas.translate(0, 29.7*cm) canvas.setFont(self.FONT_NAME, 10) canvas.saveState() self.draw_header(invoice, canvas) canvas.restoreState() canvas.saveState() self.draw_subscriber(invoice, canvas) canvas.restoreState() canvas.saveState() self.draw_contractor(invoice, canvas) canvas.restoreState() canvas.saveState() self.draw_info(invoice, canvas) canvas.restoreState() canvas.saveState() self.draw_items(invoice, canvas) canvas.restoreState() canvas.saveState() self.draw_footer(invoice, canvas) canvas.restoreState() canvas.showPage() canvas.save() canvas = None self.baseline = 0
def registerFontFamily(family,normal=None,bold=None,italic=None,boldItalic=None): from reportlab.lib import fonts if not normal: normal = family family = family.lower() if not boldItalic: boldItalic = italic or bold or normal if not bold: bold = normal if not italic: italic = normal fonts.addMapping(family, 0, 0, normal) fonts.addMapping(family, 1, 0, bold) fonts.addMapping(family, 0, 1, italic) fonts.addMapping(family, 1, 1, boldItalic)
def registerTypeFace(face): assert isinstance(face, TypeFace), 'Not a TypeFace: %s' % face _typefaces[face.name] = face # HACK - bold/italic do not apply for type 1, so egister # all combinations of mappings. from reportlab.lib import fonts ttname = string.lower(face.name) if not face.name in standardFonts: fonts.addMapping(ttname, 0, 0, face.name) fonts.addMapping(ttname, 1, 0, face.name) fonts.addMapping(ttname, 0, 1, face.name) fonts.addMapping(ttname, 1, 1, face.name)
def register_fonts_from_paths(regular, italic=None, bold=None, bolditalic=None, font_name='Reporting'): """ Pass paths to TTF files which should be used for the PDFDocument """ pdfmetrics.registerFont(TTFont('%s' % font_name, regular)) pdfmetrics.registerFont(TTFont('%s-Italic' % font_name, italic or regular)) pdfmetrics.registerFont(TTFont('%s-Bold' % font_name, bold or regular)) pdfmetrics.registerFont(TTFont('%s-BoldItalic' % font_name, bolditalic or bold or regular)) addMapping('%s' % font_name, 0, 0, '%s' % font_name) # regular addMapping('%s' % font_name, 0, 1, '%s-Italic' % font_name) # italic addMapping('%s' % font_name, 1, 0, '%s-Bold' % font_name) # bold addMapping('%s' % font_name, 1, 1, '%s-BoldItalic' % font_name) # bold & italic
def __init__(self, pdf_file, xml_file,country_name): pdfmetrics.registerFont(TTFont('Arial', 'fonts/Arial.ttf')) pdfmetrics.registerFont(TTFont('Arial-Bold', 'fonts/Arial-Bold.ttf')) pdfmetrics.registerFont(TTFont('Arial-Italic', 'fonts/Arial-Italic.ttf')) addMapping('Arial',0,0,'Arial') addMapping('Arial',0,1,'Arial-Italic') addMapping('Arial',1,0,'Arial-Bold') self.country = country_name self.styles = getSampleStyleSheet() self.e = ElementTree.parse(xml_file).getroot() self.width, self.height = int(self.e.getchildren()[0].get("width")), int(self.e.getchildren()[0].get("height")) self.c = canvas.Canvas(pdf_file, pagesize=(self.width,self.height)) self.fonts = {} for page in self.e.findall("page"): for fontspec in page.findall("fontspec"): font = {} font["size"] = int(fontspec.get("size")) font["color"] = fontspec.get("color") font["background"] = fontspec.get("background") if fontspec.get("indent") is not None: font["indent"] = fontspec.get("indent") else: font["indent"] = "0" if fontspec.get("padding") is not None: font["padding"] = fontspec.get("padding") else: font["padding"] = "0" self.fonts[fontspec.get("id")] = 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.findall('registerFont'): name = font.get('fontName').encode('ascii') fname = font.get('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
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
def registerFonts(homedir): font_mappings = [] for fname in os.listdir(os.path.join(homedir, "resources")): psname, ext = os.path.splitext(fname) if ext == ".ttf": name = psname name_lower = name.lower() pdfmetrics.registerFont(TTFont(psname, os.path.join(homedir, "resources", fname))) try: idx = name_lower.index("oblique") italic = True name = name[:idx] + name[idx+len("oblique"):] name_lower = name.lower() except ValueError: italic = False if not italic: try: idx = name_lower.index("italic") italic = True name = name[:idx] + name[idx+len("italic"):] name_lower = name.lower() except ValueError: italic = False try: idx = name_lower.index("bold") bold = True name = name[:idx] + name[idx+len("bold"):] except ValueError: bold = False name = name.replace("-", "").lower() font_mappings.append((name, bold, italic, psname)) for font_mapping in sorted(font_mappings): addMapping(*font_mapping) print font_mapping
def registerFont(font): "Registers a font, including setting up info for accelerated stringWidth" #assert isinstance(font, Font), 'Not a Font: %s' % font fontName = font.fontName _fonts[fontName] = font if font._multiByte: # CID fonts don't need to have typeface registered. #need to set mappings so it can go in a paragraph even if within # bold tags from reportlab.lib import fonts ttname = string.lower(font.fontName) fonts.addMapping(ttname, 0, 0, font.fontName) fonts.addMapping(ttname, 1, 0, font.fontName) fonts.addMapping(ttname, 0, 1, font.fontName) fonts.addMapping(ttname, 1, 1, font.fontName)
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'): face = font.getAttribute('faceName') file = font.getAttribute('fileName') pdfmetrics.registerFont(TTFont(face, file))
def docinit(self, els): from reportlab.lib.fonts import addMapping from reportlab.pdfbase import pdfmetrics from reportlab.pdfbase.ttfonts import TTFont from os import listdir from constants import fonts_location for font in listdir(fonts_location): if font.endswith(".ttf"): pdfmetrics.registerFont(TTFont(font[:-4], fonts_location + font)) 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
def loadFonts(fontpath): """ Loads all fonts for use in ReportLab. """ log.debug('Attempting to load fonts from %s...' % fontpath) # Globally register Gentium family of fonts registerFont(TTFont("Gentium", os.path.join(fontpath, "GenBkBasR.ttf"))) registerFont(TTFont("Gentium-B", os.path.join(fontpath, "GenBkBasB.ttf"))) registerFont(TTFont("Gentium-I", os.path.join(fontpath, "GenBkBasI.ttf"))) registerFont(TTFont("Gentium-BI", os.path.join(fontpath, "GenBkBasBI.ttf"))) fonts.addMapping('Gentium', 0, 0, 'Gentium') fonts.addMapping('Gentium', 0, 1, 'Gentium-I') fonts.addMapping('Gentium', 1, 0, 'Gentium-B') fonts.addMapping('Gentium', 1, 1, 'Gentium-BI') fonts._ps2tt_map.update({'Gentium': ('Gentium', 0, 0)}) registerFont(TTFont("Optimus-Princeps-SemiBold", os.path.join(fontpath, "OptimusPrincepsSemiBold.ttf"))) log.debug('Loaded fonts from %s' % fontpath)
def build_pdf(self,path): fonts.addMapping('hei', 0, 0, 'hei') fonts.addMapping('hei', 0, 1, 'hei') stylesheet=getSampleStyleSheet() elements = [] doc = BaseDocTemplate(path,title=self.title) frame = Frame(doc.leftMargin, doc.bottomMargin, doc.width, doc.height, id='normal') template = PageTemplate(id='test', frames=frame, onPage=self.header_footer) doc.addPageTemplates([template]) covername={"GRE":"G R E","TOEFL":"托 福","SAT":"S A T","IELTS":"雅 思","GMAT":"G M A T","kaoyan":"考 研"} covertitle="智 课 网 "+covername[self.type]+" 备 考 资 料" elements.append(Spacer(40,250)) stylesheet["Title"].fontSize=35 fonts.addMapping('yhb', 0, 0, 'yhb') fonts.addMapping('yhb', 0, 1, 'yhb') bigTitle=Paragraph('<font name="yhb">'+covertitle+"</font>",stylesheet["Title"]) elements.append(bigTitle) elements.append(PageBreak()) stylesheet['Normal'].fontSize=14 stylesheet['Normal'].leading=14*1.5 stylesheet['Normal'].firstLineIndent=28 stylesheet['Heading1'].leading=20*1.5 stylesheet["Heading1"].alignment=1 title_pra=Paragraph('<font name="hei">'+self.title+"</font>",stylesheet["Heading1"]) elements.append(title_pra) for item in self.content.split("\n"): try: content = Paragraph('<font name="hei">'+item+'</font>', stylesheet['Normal']) elements.append(content) except Exception: print "some error" logging.warning("some error with" +item) elements.append(PageBreak()) data = open("pdf_image/thelastpage.png").read() img1 = StringIO(data) elements.append(Image(img1,width=110*mm,height=226*mm)) doc.build(elements)
def registerFont(font): "Registers a font, including setting up info for accelerated stringWidth" #assert isinstance(font, Font), 'Not a Font: %s' % font fontName = font.fontName _fonts[fontName] = font if font._multiByte: # CID fonts don't need to have typeface registered. #need to set mappings so it can go in a paragraph even if within # bold tags from reportlab.lib import fonts ttname = string.lower(font.fontName) fonts.addMapping(ttname, 0, 0, font.fontName) fonts.addMapping(ttname, 1, 0, font.fontName) fonts.addMapping(ttname, 0, 1, font.fontName) fonts.addMapping(ttname, 1, 1, font.fontName) #cannot accelerate these yet... else: if _stringWidth: _rl_accel.setFontInfo(string.lower(fontName), _dummyEncoding, font.face.ascent, font.face.descent, font.widths)
def __init__(self, flist, font_path=None, style_path=None, def_dpi=300): log.info('Using stylesheets: %s' % ','.join(flist)) # find base path if hasattr(sys, 'frozen'): self.PATH = abspath(dirname(sys.executable)) else: self.PATH = abspath(dirname(__file__)) # flist is a list of stylesheet filenames. # They will be loaded and merged in order. # but the two default stylesheets will always # be loaded first flist = [ join(self.PATH, 'styles', 'styles.style'), join(self.PATH, 'styles', 'default.style') ] + flist self.def_dpi = def_dpi if font_path is None: font_path = [] font_path += ['.', os.path.join(self.PATH, 'fonts')] self.FontSearchPath = map(os.path.expanduser, font_path) if style_path is None: style_path = [] style_path += [ '.', os.path.join(self.PATH, 'styles'), '~/.rst2pdf/styles' ] self.StyleSearchPath = map(os.path.expanduser, style_path) self.FontSearchPath = list(set(self.FontSearchPath)) self.StyleSearchPath = list(set(self.StyleSearchPath)) log.info('FontPath:%s' % self.FontSearchPath) log.info('StylePath:%s' % self.StyleSearchPath) findfonts.flist = self.FontSearchPath # Page width, height self.pw = 0 self.ph = 0 # Page size [w,h] self.ps = None # Margins (top,bottom,left,right,gutter) self.tm = 0 self.bm = 0 self.lm = 0 self.rm = 0 self.gm = 0 #text width self.tw = 0 # Default emsize, later it will be the fontSize of the base style self.emsize = 10 self.languages = [] ssdata = self.readSheets(flist) # Get pageSetup data from all stylessheets in order: self.ps = pagesizes.A4 self.page = {} for data, ssname in ssdata: page = data.get('pageSetup', {}) if page: self.page.update(page) pgs = page.get('size', None) if pgs: # A standard size pgs = pgs.upper() if pgs in pagesizes.__dict__: self.ps = list(pagesizes.__dict__[pgs]) self.psname = pgs if 'width' in self.page: del (self.page['width']) if 'height' in self.page: del (self.page['height']) elif pgs.endswith('-LANDSCAPE'): self.psname = pgs.split('-')[0] self.ps = list( pagesizes.landscape( pagesizes.__dict__[self.psname])) if 'width' in self.page: del (self.page['width']) if 'height' in self.page: del (self.page['height']) else: log.critical('Unknown page size %s in stylesheet %s'%\ (page['size'], ssname)) continue else: #A custom size if 'size' in self.page: del (self.page['size']) # The sizes are expressed in some unit. # For example, 2cm is 2 centimeters, and we need # to do 2*cm (cm comes from reportlab.lib.units) if 'width' in page: self.ps[0] = self.adjustUnits(page['width']) if 'height' in page: self.ps[1] = self.adjustUnits(page['height']) self.pw, self.ph = self.ps if 'margin-left' in page: self.lm = self.adjustUnits(page['margin-left']) if 'margin-right' in page: self.rm = self.adjustUnits(page['margin-right']) if 'margin-top' in page: self.tm = self.adjustUnits(page['margin-top']) if 'margin-bottom' in page: self.bm = self.adjustUnits(page['margin-bottom']) if 'margin-gutter' in page: self.gm = self.adjustUnits(page['margin-gutter']) if 'spacing-header' in page: self.ts = self.adjustUnits(page['spacing-header']) if 'spacing-footer' in page: self.bs = self.adjustUnits(page['spacing-footer']) if 'firstTemplate' in page: self.firstTemplate = page['firstTemplate'] # tw is the text width. # We need it to calculate header-footer height # and compress literal blocks. self.tw = self.pw - self.lm - self.rm - self.gm # Get page templates from all stylesheets self.pageTemplates = {} for data, ssname in ssdata: templates = data.get('pageTemplates', {}) # templates is a dictionary of pageTemplates for key in templates: template = templates[key] # template is a dict. # template[´frames'] is a list of frames if key in self.pageTemplates: self.pageTemplates[key].update(template) else: self.pageTemplates[key] = template # Get font aliases from all stylesheets in order self.fontsAlias = {} for data, ssname in ssdata: self.fontsAlias.update(data.get('fontsAlias', {})) embedded_fontnames = [] self.embedded = [] # Embed all fonts indicated in all stylesheets for data, ssname in ssdata: embedded = data.get('embeddedFonts', []) for font in embedded: try: # Just a font name, try to embed it if isinstance(font, unicode): # See if we can find the font fname, pos = findfonts.guessFont(font) if font in embedded_fontnames: pass else: fontList = findfonts.autoEmbed(font) if fontList: embedded_fontnames.append(font) if not fontList: if (fname, pos) in embedded_fontnames: fontList = None else: fontList = findfonts.autoEmbed(fname) if fontList is not None: self.embedded += fontList # Maybe the font we got is not called # the same as the one we gave # so check that out suff = ["", "-Oblique", "-Bold", "-BoldOblique"] if not fontList[0].startswith(font): # We need to create font aliases, and use them for fname, aliasname in zip( fontList, [font + suffix for suffix in suff]): self.fontsAlias[aliasname] = fname continue # Each "font" is a list of four files, which will be # used for regular / bold / italic / bold+italic # versions of the font. # If your font doesn't have one of them, just repeat # the regular font. # Example, using the Tuffy font from # http://tulrich.com/fonts/ # "embeddedFonts" : [ # ["Tuffy.ttf", # "Tuffy_Bold.ttf", # "Tuffy_Italic.ttf", # "Tuffy_Bold_Italic.ttf"] # ], # The fonts will be registered with the file name, # minus the extension. if font[0].lower().endswith('.ttf'): # A True Type font for variant in font: location = self.findFont(variant) pdfmetrics.registerFont( TTFont(str(variant.split('.')[0]), location)) log.info('Registering font: %s from %s'%\ (str(variant.split('.')[0]),location)) self.embedded.append(str(variant.split('.')[0])) # And map them all together regular, bold, italic, bolditalic = [ variant.split('.')[0] for variant in font ] addMapping(regular, 0, 0, regular) addMapping(regular, 0, 1, italic) addMapping(regular, 1, 0, bold) addMapping(regular, 1, 1, bolditalic) else: # A Type 1 font # For type 1 fonts we require # [FontName,regular,italic,bold,bolditalic] # where each variant is a (pfbfile,afmfile) pair. # For example, for the URW palladio from TeX: # ["Palatino",("uplr8a.pfb","uplr8a.afm"), # ("uplri8a.pfb","uplri8a.afm"), # ("uplb8a.pfb","uplb8a.afm"), # ("uplbi8a.pfb","uplbi8a.afm")] faceName = font[0] regular = pdfmetrics.EmbeddedType1Face(*font[1]) italic = pdfmetrics.EmbeddedType1Face(*font[2]) bold = pdfmetrics.EmbeddedType1Face(*font[3]) bolditalic = pdfmetrics.EmbeddedType1Face(*font[4]) except Exception, e: try: if isinstance(font, list): fname = font[0] else: fname = font log.error("Error processing font %s: %s", os.path.splitext(fname)[0], str(e)) log.error("Registering %s as Helvetica alias", fname) self.fontsAlias[fname] = 'Helvetica' except Exception, e: log.critical("Error processing font %s: %s", fname, str(e)) continue
def listpath(e, dirpath, dirpath1): tStart = time.time() global story cont = 0 cont1 = 0 Story = [] fig = False ost = "" pdfpath1 = "" ddrddd = dirpath1[0:dirpath1.rfind('\\') + 1] if ".dbf" not in dirpath1 and ".DBF" not in dirpath1: wx.MessageBox(u"不存在DBF檔 請重新選取", u"提示訊息") else: print 'Wait for PDF......' db = dbf.Dbf(dirpath1) for record in db: # print record['Plt_no'], record['Vil_dt'], record['Vil_time'],record['Bookno'],record['Vil_addr'],record['Rule_1'],record['Truth_1'],record['Rule_2'],record['Truth_2'],record['color'],record['A_owner1'] filename2 = record['Plt_no'].decode('big5') + "." + record[ 'Vil_dt'] + "." + record['Vil_time'] #檔名 piece2.append(filename2) #檔名 piece2.append(record['Plt_no']) #車牌 piece2.append(record['Vil_dt']) #日期 piece2.append(record['Vil_time']) #時間 piece2.append(record['Bookno']) #冊頁號 piece2.append(record['Vil_addr']) #違規地點 piece2.append(record['Rule_1']) #法條1 piece2.append(record['Truth_1']) #法條1事實 piece2.append(record['Rule_2']) #法條2 piece2.append(record['Truth_2']) #法條2事實 piece2.append(record['color']) #車顏色 piece2.append(record['A_owner1']) #車廠牌 record.store() print 'Wait for PDF......' for root, dirs, files in os.walk(dirpath): for f in files: if ".jpg" in os.path.join(root, f): strsu = os.path.join(f).replace('-1.jpg', '').replace( '_1.jpg', '') if strsu in piece2: cc = os.path.join(root, f) cont = cont + 1 photo_path.append(cc) # print photo_path if u'-1.jpg' in photo_path[0]: ost = '-1' if u'_1.jpg' in photo_path[0]: ost = '_1' for record in db: filename = record['Plt_no'] + "." + record[ 'Vil_dt'] + "." + record['Vil_time'] + ost #檔名 piece1.append(filename) #檔名 piece1.append(record['Plt_no']) #車牌 piece1.append(record['Vil_dt']) #日期 piece1.append(record['Vil_time']) #時間 piece1.append(record['Bookno']) #冊頁號 piece1.append(record['Vil_addr']) #違規地點 piece1.append(record['Rule_1']) #法條1 piece1.append(record['Truth_1']) #法條1事實 piece1.append(record['Rule_2']) #法條2 piece1.append(record['Truth_2']) #法條2事實 piece1.append(record['color']) #車顏色 piece1.append(record['A_owner1']) #車廠牌 record.store() x = 0 wxc = 0 wxc2 = 0 v22 = '' v1 = '' c = False e = len(photo_path) wxwx = len(piece1) // 12 for x in range(wxwx): for t in range(e): phtotpath = photo_path[t] phtotpath = phtotpath[phtotpath.rfind(u'\\') + 1:len(phtotpath)].replace( '.jpg', '') e1 = piece1[x * 12 + 1] if e1[0:len(e1) - 5] == phtotpath[0:len(e1) - 5] and piece1[ x * 12 + 11] != '' and piece1[x * 12 + 12] != '': fig = True break # if e1[0:len(e1)-5] == phtotpath[0:len(e1)-5] and piece1[x*12+11] == '' and piece1[x*12+12] == '': # pho = photo_path[t] # print '123' # print pho.encode('utf-8') # break if fig == False and piece1[x * 12 + 11] != '' and piece1[ x * 12 + 12] != '': wxc2 = 1 print e1 print piece1[x * 12 + 5 + 1] if piece1[x * 12 + 11] == '' and piece1[x * 12 + 12] == '': pdfmetrics.registerFont(TTFont('song', 'simsun.ttf')) fonts.addMapping('song', 0, 0, 'song') fonts.addMapping('song', 0, 1, 'song') stylesheet = getSampleStyleSheet() normalStyle = copy.deepcopy(stylesheet['Normal']) normalStyle.fontName = 'song' normalStyle.size = '13' # im2 = Image(pho,400,300) # story.append(im2) story2.append( Paragraph( u'<font size=15 color=red>車牌: ' + piece2[x * 12 + 1 + 1].decode('big5') + '</font><font size=13 color=white>-</font>' + u'<font size=13>冊頁號: </font><font size=13 color=blue>' + piece2[x * 12 + 1 + 4] + '</font><font size=13 color=white>-----</font>' + u'<font size=13 color=blue>-1</font>', normalStyle)) story2.append( Paragraph( '----------------------------------------------------------------------------------------------------------------', normalStyle)) story2.append( Paragraph( u'<font size=13>日期: </font><font size=13 color=blue>' + piece2[x * 12 + 1 + 2] + '</font><font size=13 color=white>--</font>' + u' <font size=13>時間: </font><font size=13 color=blue>' + piece2[x * 12 + 1 + 3] + '</font><font size=13 color=white>--</font>' + u' <font size=13>違規地點: </font><font size=13 color=blue>' + piece2[x * 12 + 1 + 5].decode('big5') + '</font>', normalStyle)) story2.append( Paragraph( u'<font size=13 color=blue>錯誤訊息: 交換不到車種、顏色,皆為空</font>', normalStyle)) story2.append( Paragraph( '----------------------------------------------------------------------------------------------------------------', normalStyle)) wxc += 1 fig = False if story2 != []: bbt = piece2[x * 12 + 1 + 4] doc2 = SimpleDocTemplate(dirpath1[0:dirpath1.rfind('.')] + '_exception.pdf', rightMargin=1, leftMargin=1, topMargin=1, bottomMargin=1) print 'Wait for PDF_exception......' doc2.build(story2) print 'Mission accomplished' if wxc2 == 1: print '請修正錯誤後重來' if wxc2 == 0: for x in range(wxwx): for t in range(e): # print piece1[x*12+1] # print photo_path[t].encode('utf-8') phtotpath = photo_path[t] phtotpath = phtotpath[phtotpath.rfind(u'\\') + 1:len(phtotpath)].replace( '.jpg', '') e1 = piece1[x * 12 + 1] if e1[0:len(e1) - 5] == phtotpath[0:len(e1) - 5] and piece1[ x * 12 + 11] != '' and piece1[x * 12 + 12] != '': # if x%2 == 0: # v22 = v1 fig = True cont1 = cont1 + 1 pathr = photo_path[t] pathrr = photo_path[t].replace('1.jpg', '2.jpg') isexists = os.path.exists(pathr) isexistss2 = os.path.exists(pathrr) pdfpath1 = pathr[0:pathr.rfind(u'\\')] pdfpath1 = pdfpath1[0:pdfpath1.rfind(u'\\') + 1] if not isexists: print pathr if isexists: Pnum = piece2[x * 12 + 1 + 4] tryr = Pnum[0:9] photo = pathr photo3 = pathrr pdfmetrics.registerFont( TTFont('song', 'simsun.ttf')) fonts.addMapping('song', 0, 0, 'song') fonts.addMapping('song', 0, 1, 'song') #----------------------------------------------------- db1 = dbf.Dbf('DBF\\COLOR_CODE.DBF') for record in db1: co = piece2[x * 12 + 1 + 10] if len(co) > 0: if record['Color_id'] == co[0]: color = record['Color'] else: color = "" for record in db1: co = piece2[x * 12 + 1 + 10] if len(co) == 2: if record['Color_id'] == co[1]: color = color + record['Color'] #----------------------------------------------------- stylesheet = getSampleStyleSheet() normalStyle = copy.deepcopy( stylesheet['Normal']) normalStyle.fontName = 'song' normalStyle.size = '13' isexistsss = os.path.exists(photo3) im = Image(photo, 400, 300) story.append(im) story.append( Paragraph( u'<font size=15 color=red>車牌: ' + piece2[x * 12 + 1 + 1] + '</font><font size=13 color=white>-</font>' + u'<font size=13>廠牌: </font><font size=13 color=blue>' + piece2[x * 12 + 1 + 11].decode('big5') + '</font><font size=13 color=white>-</font>' + u' <font size=13>顏色: </font><font size=13 color=blue>' + color.decode('big5') + '</font><font size=13 color=white>-</font>' + u'<font size=13>冊頁號: </font><font size=13 color=blue>' + piece2[x * 12 + 1 + 4] + '</font><font size=13 color=white>-----</font>' + u'<font size=13 color=blue>-1</font>', normalStyle)) story.append( Paragraph( '----------------------------------------------------------------------------------------------------------------', normalStyle)) story.append( Paragraph( u'<font size=13>日期: </font><font size=13 color=blue>' + piece2[x * 12 + 1 + 2] + '</font><font size=13 color=white>--</font>' + u' <font size=13>時間: </font><font size=13 color=blue>' + piece2[x * 12 + 1 + 3] + '</font><font size=13 color=white>--</font>' + u' <font size=13>違規地點: </font><font size=13 color=blue>' + piece2[x * 12 + 1 + 5].decode('big5') + '</font>', normalStyle)) story.append( Paragraph( u'<font size=13>違規法條1: </font><font size=13 color=blue>' + piece2[x * 12 + 1 + 6] + '</font>', normalStyle)) story.append( Paragraph( u'<font size=13>違規事實1: </font><font size=13 color=blue>' + piece2[x * 12 + 1 + 7].decode('big5').replace( ' ', '') + '</font>', normalStyle)) if len(piece2[x * 12 + 1 + 8]) > 1: story.append( Paragraph( u'<font size=13>違規法條2: </font><font size=13 color=blue>' + piece2[x * 12 + 1 + 8] + u'</font><font size=13 color=white>----</font><font size=13>違規事實2: </font><font size=13 color=blue>' + piece2[x * 12 + 1 + 9].decode('big5') + '</font>', normalStyle)) story.append( Paragraph( '----------------------------------------------------------------------------------------------------------------', normalStyle)) if isexistsss: im2 = Image(photo3, 400, 300) story.append(im2) story.append( Paragraph( u'<font size=15 color=red>車牌: ' + piece2[x * 12 + 1 + 1] + '</font><font size=13 color=white>-</font>' + u'<font size=13>廠牌: </font><font size=13 color=blue>' + piece2[x * 12 + 1 + 11].decode('big5') + '</font><font size=13 color=white>-</font>' + u' <font size=13>顏色: </font><font size=13 color=blue>' + color.decode('big5') + '</font><font size=13 color=white>-</font>' + u'<font size=13>冊頁號: </font><font size=13 color=blue>' + piece2[x * 12 + 1 + 4] + '</font><font size=13 color=white>-----</font>' + u'<font size=13 color=blue>-2</font>', normalStyle)) story.append( Paragraph( '----------------------------------------------------------------------------------------------------------------', normalStyle)) story.append( Paragraph( u'<font size=13>日期: </font><font size=13 color=blue>' + piece2[x * 12 + 1 + 2] + '</font><font size=13 color=white>--</font>' + u' <font size=13>時間: </font><font size=13 color=blue>' + piece2[x * 12 + 1 + 3] + '</font><font size=13 color=white>--</font>' + u' <font size=13>違規地點: </font><font size=13 color=blue>' + piece2[x * 12 + 1 + 5].decode('big5') + '</font>', normalStyle)) story.append( Paragraph( u'<font size=13>違規法條1: </font><font size=13 color=blue>' + piece2[x * 12 + 1 + 6] + '</font>', normalStyle)) story.append( Paragraph( u'<font size=13>違規事實1: </font><font size=13 color=blue>' + piece2[x * 12 + 1 + 7].decode('big5').replace( ' ', '') + '</font>', normalStyle)) if len(piece2[x * 12 + 1 + 8]) > 1: story.append( Paragraph( u'<font size=13>違規法條2: </font><font size=13 color=blue>' + piece2[x * 12 + 1 + 8] + u'</font><font size=13 color=white>----</font><font size=13>違規事實2: </font><font size=13 color=blue>' + piece2[x * 12 + 1 + 9].decode('big5') + '</font>', normalStyle)) story.append( Paragraph( '----------------------------------------------------------------------------------------------------------------', normalStyle)) print 'Progress ' + str(cont1) + '/' + str( cont - wxc) + '/' + str( wxwx) + '....exception:' + str(wxc) break if x < wxwx - 1: g1 = piece2[x * 12 + 1 + 4] g1 = g1[0:len(g1) - 3] g2 = piece2[x * 12 + 1 + 4 + 12] g2 = g2[0:len(g2) - 3] if g1 != g2 or x == wxwx - 1: bbt = piece2[x * 12 + 1 + 4] doc = SimpleDocTemplate( ddrddd + bbt[0:len(bbt) - 3] + piece2[x * 12 + 1 + 5].decode('big5').replace( '?', '') + '.pdf', rightMargin=1, leftMargin=1, topMargin=1, bottomMargin=1) print 'Wait for PDF......' doc.build(story) story = [] print 'Mission accomplished' tEnd = time.time() print "Spend " + str((tEnd - tStart) // 1) + " second"
def generate(self, participant, event): buffer = io.BytesIO() doc = SimpleDocTemplate(buffer, pagesize=letter, rightMargin=72, leftMargin=72, topMargin=72, bottomMargin=18) payload = dict(participant_id=participant.id, event_id=event.id) qrw = QrCodeWidget(payload) # getBounds returns boundary as array: b[0], b[1], b[2], b[3] = x1, y1, x2, y2 b = qrw.getBounds() width = b[2] - b[0] height = b[3] - b[1] d = Drawing(290, 290, transform=[290. / width, 0, 0, 290. / height, 0, 0]) d.add(qrw) im = Image(d, 2 * inch, 2 * inch) pdfmetrics.registerFont(TTFont('Verdana', 'Vera.ttf')) pdfmetrics.registerFont(TTFont('Verdana-Bold', 'VeraBd.ttf')) pdfmetrics.registerFont(TTFont('Verdana-Italic', 'VeraIt.ttf')) pdfmetrics.registerFont(TTFont('Verdana-BoldItalic', 'VeraBI.ttf')) addMapping('verdana', 0, 0, 'Verdana') addMapping('verdana', 1, 0, 'Verdana-Bold') addMapping('verdana', 0, 1, 'Verdana-Italic') addMapping('verdana', 1, 1, 'Verdana-BoldItalic') story = [] start_date = event.start.strftime("%d/%m/%Y %H:%M") end_date = event.end.strftime("%d/%m/%Y %H:%M") now_dt_string = datetime.now().strftime("%d/%m/%Y %H:%M:%S") styles = getSampleStyleSheet() styles.add( ParagraphStyle(name='Justify', fontSize=10, leading=12, alignment=TA_JUSTIFY, fontName='Verdana')) styles.add( ParagraphStyle(name='Standard', fontSize=10, leading=12, fontName='Verdana')) ptext = '<font size="12">Wygenerowano dnia: %s</font>' % now_dt_string story.append(Paragraph(ptext, styles["Standard"])) story.append(Spacer(1, 12)) ptext = '<font size="12">Użytkownik: %s</font>' % participant.get_full_name( ) story.append(Paragraph(ptext, styles["Standard"])) story.append(Spacer(1, 24)) ptext = u'<font size="12">To jest twoja wejściówka na wydarzenie <b>%s</b>! \ Podczas wydarzenia możesz zostać poproszony o pokazanie wejściówki, dlatego \ pamiętaj aby mieć ją zawsze przy sobie. Wejściówkę możesz wydrukować lub \ okazać na urządzeniu elektronicznym.</font>' % event.name story.append(Paragraph(ptext, styles["Justify"])) story.append(Spacer(1, 12)) ptext = '<font size="12">Start wydarzenia: %s</font>' % start_date story.append(Paragraph(ptext, styles["Justify"])) ptext = '<font size="12">Koniec: %s</font>' % end_date story.append(Paragraph(ptext, styles["Standard"])) story.append(Spacer(1, 60)) story.append(im) doc.build(story) buffer.seek(0) return buffer
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'))
# 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): # canvas.drawImage("snkanim.gif", 36, 36)
def listpath(e,dirpath,dirpath1): doc = SimpleDocTemplate("form_letter1.pdf",rightMargin=1,leftMargin=1,topMargin=1,bottomMargin=1) tStart = time.time() global story cont = 0 cont1 = 0 Story=[] ost = "" pdfpath1 = "" if ".dbf" not in dirpath1 and ".DBF" not in dirpath1: wx.MessageBox(u"不存在DBF檔 請重新選取",u"提示訊息") else : db = dbf.Dbf(dirpath1) for record in db: # print record['Plt_no'], record['Vil_dt'], record['Vil_time'],record['Bookno'],record['Vil_addr'],record['Rule_1'],record['Truth_1'],record['Rule_2'],record['Truth_2'],record['color'],record['A_owner1'] filename2 = record['Plt_no'] + "." + record['Vil_dt'] + "." + record['Vil_time'] #檔名 piece2.append( filename2 ) #檔名 piece2.append( record['Plt_no'] ) #車牌 piece2.append( record['Vil_dt'] ) #日期 piece2.append( record['Vil_time'] ) #時間 piece2.append( record['Bookno'] ) #冊頁號 piece2.append( record['Vil_addr'] ) #違規地點 piece2.append( record['Rule_1'] ) #法條1 piece2.append( record['Truth_1'] ) #法條1事實 piece2.append( record['Rule_2'] ) #法條2 piece2.append( record['Truth_2'] ) #法條2事實 piece2.append( record['color'] ) #車顏色 piece2.append( record['A_owner1'] ) #車廠牌 record.store() print '正在轉換圖檔大小......' for root, dirs, files in os.walk(dirpath): for f in files: if ".jpg" in os.path.join(root , f) : strsu = os.path.join(f).replace('-1.jpg','').replace('_1.jpg','') if strsu in piece2 : cc = os.path.join(root , f) cont = cont +1 photo_path.append(cc) if u'-1.jpg' in photo_path[0] : ost = u'-1' if u'_1.jpg' in photo_path[0] : ost = u'_1' e = len(photo_path) for t1 in range(e): pathr = photo_path[t1] pathrr = photo_path[t1].replace('1.jpg','2.jpg') isexists = os.path.exists(pathr) isexistss2 = os.path.exists(pathrr) img = PIL.Image.open(pathr) imgSize = img.size # print imgSize maxSize = max(imgSize) # print maxSize # minSize = min(imgSize) # print minSize if maxSize > 900 : if isexists: resize_img(pathr,pathr, 900) if isexistss2: resize_img(pathrr,pathrr, 900) for record in db: filename = record['Plt_no'] + "." + record['Vil_dt'] + "." + record['Vil_time']+ost#檔名 piece1.append( filename ) #檔名 piece1.append( record['Plt_no'] ) #車牌 piece1.append( record['Vil_dt'] ) #日期 piece1.append( record['Vil_time'] ) #時間 piece1.append( record['Bookno'] ) #冊頁號 piece1.append( record['Vil_addr'] ) #違規地點 piece1.append( record['Rule_1'] ) #法條1 piece1.append( record['Truth_1'] ) #法條1事實 piece1.append( record['Rule_2'] ) #法條2 piece1.append( record['Truth_2'] ) #法條2事實 piece1.append( record['color'] ) #車顏色 piece1.append( record['A_owner1'] ) #車廠牌 record.store() print 'Wait for PDF......' x = 0 c = False wxwx = (len(piece1))//12 for x in range(wxwx): for t in range(e): # print piece1[x*12+1] # print photo_path[t].encode('utf-8') phtotpath = photo_path[t] phtotpath = phtotpath[phtotpath.rfind(u'\\')+1:len(phtotpath)].replace('.jpg','') e1 = piece1[x*12+1] if e1[0:len(e1)-5] == phtotpath[0:len(e1)-5]: cont1 = cont1+1 pathr2 = photo_path[t] pathrr2 = photo_path[t].replace('1.jpg','2.jpg') pdfpath1 = pathr2[0:pathr2.rfind(u'\\')] pdfpath1 = pdfpath1[0:pdfpath1.rfind(u'\\')+1] # cc2isexists = os.path.exists(pathrr2) # if cc2isexists: # cont1 = cont1+1 Pnum = piece2[x*12+1+4] tryr = Pnum[0:9] photo = pathr2 photo3 = pathrr2 pdfmetrics.registerFont(TTFont('song', 'simsun.ttf')) fonts.addMapping('song', 0, 0, 'song') fonts.addMapping('song', 0, 1, 'song') #----------------------------------------------------- db1 = dbf.Dbf('DBF\\COLOR_CODE.DBF') for record in db1: co = piece2[x*12+1+10] if len(co) > 0: if record['Color_id'] == co[0]: color = record['Color'] else: color = "" for record in db1: co = piece2[x*12+1+10] if len(co) == 2: if record['Color_id'] == co[1]: color = color+record['Color'] #----------------------------------------------------- stylesheet=getSampleStyleSheet() normalStyle = copy.deepcopy(stylesheet['Normal']) normalStyle.fontName ='song' normalStyle.size = '13' isexistsss = os.path.exists(photo3) im = Image(photo,400,300) story.append(im) story.append(Paragraph(u'<font size=15 color=red>車牌: '+piece2[x*12+1+1]+'</font><font size=13 color=white>-</font>'+u'<font size=13>廠牌: </font><font size=13 color=blue>'+piece2[x*12+1+11].decode('big5')+'</font><font size=13 color=white>-</font>'+u' <font size=13>顏色: </font><font size=13 color=blue>'+color.decode('big5')+'</font><font size=13 color=white>-</font>'+u'<font size=13>冊頁號: </font><font size=13 color=blue>'+piece2[x*12+1+4]+'</font><font size=13 color=white>-----</font>'+u'<font size=13 color=blue>-1</font>', normalStyle)) story.append(Paragraph('----------------------------------------------------------------------------------------------------------------',normalStyle)) story.append(Paragraph(u'<font size=13>日期: </font><font size=13 color=blue>'+piece2[x*12+1+2]+'</font><font size=13 color=white>--</font>'+u' <font size=13>時間: </font><font size=13 color=blue>'+piece2[x*12+1+3]+'</font><font size=13 color=white>--</font>'+u' <font size=13>違規地點: </font><font size=13 color=blue>'+piece2[x*12+1+5].decode('big5')+'</font>',normalStyle)) story.append(Paragraph(u'<font size=13>違規法條1: </font><font size=13 color=blue>'+piece2[x*12+1+6]+'</font>',normalStyle)) story.append(Paragraph(u'<font size=13>違規事實1: </font><font size=13 color=blue>'+piece2[x*12+1+7].decode('big5').replace(' ','')+'</font>',normalStyle)) if len(piece2[x*12+1+8])>1: story.append(Paragraph(u'<font size=13>違規法條2: </font><font size=13 color=blue>'+piece2[x*12+1+8]+u'</font><font size=13 color=white>----</font><font size=13>違規事實2: </font><font size=13 color=blue>'+piece2[x*12+1+9].decode('big5')+'</font>',normalStyle)) story.append(Paragraph('----------------------------------------------------------------------------------------------------------------',normalStyle)) if isexistsss: im2 = Image(photo3,400,300) story.append(im2) story.append(Paragraph(u'<font size=15 color=red>車牌: '+piece2[x*12+1+1]+'</font><font size=13 color=white>-</font>'+u'<font size=13>廠牌: </font><font size=13 color=blue>'+piece2[x*12+1+11].decode('big5')+'</font><font size=13 color=white>-</font>'+u' <font size=13>顏色: </font><font size=13 color=blue>'+color.decode('big5')+'</font><font size=13 color=white>-</font>'+u'<font size=13>冊頁號: </font><font size=13 color=blue>'+piece2[x*12+1+4]+'</font><font size=13 color=white>-----</font>'+u'<font size=13 color=blue>-2</font>', normalStyle)) story.append(Paragraph('----------------------------------------------------------------------------------------------------------------',normalStyle)) story.append(Paragraph(u'<font size=13>日期: </font><font size=13 color=blue>'+piece2[x*12+1+2]+'</font><font size=13 color=white>--</font>'+u' <font size=13>時間: </font><font size=13 color=blue>'+piece2[x*12+1+3]+'</font><font size=13 color=white>--</font>'+u' <font size=13>違規地點: </font><font size=13 color=blue>'+piece2[x*12+1+5].decode('big5')+'</font>',normalStyle)) story.append(Paragraph(u'<font size=13>違規法條1: </font><font size=13 color=blue>'+piece2[x*12+1+6]+'</font>',normalStyle)) story.append(Paragraph(u'<font size=13>違規事實1: </font><font size=13 color=blue>'+piece2[x*12+1+7].decode('big5').replace(' ','')+'</font>',normalStyle)) if len(piece2[x*12+1+8])>1: story.append(Paragraph(u'<font size=13>違規法條2: </font><font size=13 color=blue>'+piece2[x*12+1+8]+u'</font><font size=13 color=white>----</font><font size=13>違規事實2: </font><font size=13 color=blue>'+piece2[x*12+1+9].decode('big5')+'</font>',normalStyle)) story.append(Paragraph('----------------------------------------------------------------------------------------------------------------',normalStyle)) print 'Progress '+str(cont1)+'/'+str(cont)+'/'+str(wxwx) break doc = SimpleDocTemplate(pdfpath1+'repor.pdf',rightMargin=1,leftMargin=1,topMargin=1,bottomMargin=1) print 'Wait for PDF......' doc.build(story) story=[] print 'Mission accomplished' tEnd = time.time() print "Spend "+str((tEnd - tStart)//1)+" second"
def createpdf(orders, fname, count): reportlab.rl_config.warnOnMissingFontGlyphs = 0 pdfmetrics.registerFont(TTFont('hei', 'simhei.ttf')) fonts.addMapping('hei', 0, 0, 'hei') fonts.addMapping('hei', 0, 1, 'hei') ts = [('FONT', (0, 0), (-1, -1), 'hei'), ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), ('LEFTPADDING', (0, 0), (-1, -1), 1), ('RIGHTPADDING', (0, 0), (-1, -1), 1), ('BOTTOMPADDING', (0, 0), (-1, -1), 0), ('TOPPADDING', (0, 0), (-1, -1), 3), ('LINEABOVE', (0, 0), (-1, 1), 0.5, colors.black), ('FONTSIZE', (0, 0), (-1, -1), 9)] ts2 = [('FONT', (0, 0), (-1, -1), 'hei'), ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), ('LEFTPADDING', (0, 0), (-1, -1), 1), ('RIGHTPADDING', (0, 0), (-1, -1), 1), ('BOTTOMPADDING', (0, 0), (-1, -1), 0), ('TOPPADDING', (0, 0), (-1, -1), 3), ('FONTSIZE', (0, 0), (-1, -1), 9)] phdsize = setting.PeiHuoDanSize.split(';') #配货单打印尺寸设置 第一个数表示当前应用的是第几个尺寸 arrsize = phdsize[int(phdsize[0])].split(',') width = int(arrsize[0]) #285 height = int(arrsize[1]) #350 doc = SimpleDocTemplate('upload/' + fname, pagesize=(width, height), leftMargin=3, rightMargin=3, topMargin=8, bottomMargin=2) stylesheet = getSampleStyleSheet() stylesheet.add(ParagraphStyle(name='p', alignment=TA_JUSTIFY, fontSize=9)) stylesheet.add(ParagraphStyle(name='hh1', alignment=TA_CENTER, fontSize=18)) stylesheet.add( ParagraphStyle(name='td1', alignment=TA_JUSTIFY, fontSize=9, wordWrap='CJK')) stylesheet['hh1'].fontName = 'hei' stylesheet['p'].fontName = 'hei' stylesheet['td1'].fontName = 'hei' elements = [] for o in orders: elements.append(Paragraph('易 凡 网 配 货 单', stylesheet['hh1'])) elements.append(Spacer(1, 16)) title = [] title.append([ '订单号:' + str(o.ordernum), '日期:' + str(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(o.ordered))) ]) table = Table(title, (133, 133), 18, ts2) elements.append(table) elements.append(Spacer(1, 3)) data = [] data.append(['名称(规格)', '单价', '数量', '小计']) for item in o.items: if item.item_type == 2: gift = u'(积分换购)' elif item.item_type == 9: gift = u'(赠品)' else: gift = '' if item.product_standard_name: td = [ Paragraph( item.product.name + u'(' + item.product_standard_name + u')' + gift, stylesheet['td1']), item.price, item.quantity, item.quantity * item.price ] else: td = [ Paragraph( item.product.name + u'(' + item.product_standard.name + u')' + gift, stylesheet['td1']), item.price, item.quantity, item.quantity * item.price ] # styleTd = Paragraph(td[0], stylesheet['BodyText']) data.append(td) table = Table(data, (176, 30, 30, 30), 18, ts) elements.append(table) elements.append( flowables.Preformatted( '-----------------------------------------------------------', stylesheet['p'])) elements.append(Spacer(1, 3)) total = [] total.append( ['商品费用(元):' + str(o.price), '物流费用(元):' + str(o.shippingprice)]) total.append([ '本次优惠(元):' + str(o.price + o.shippingprice - o.currentprice), '合计(元):' + str(o.currentprice) ]) if o.payment == 0: collect_price = o.currentprice - o.pay_balance else: collect_price = 0 total.append( ['使用余额(元):' + str(o.pay_balance), '代收金额(元):' + str(collect_price)]) table2 = Table(total, (133, 133), 18, ts2) elements.append(table2) elements.append(Spacer(1, 3)) elements.append( flowables.Preformatted( '-----------------------------------------------------------', stylesheet['p'])) elements.append(Spacer(1, 3)) elements.append( flowables.Preformatted( u'客户:' + o.take_name + u' (' + o.take_tel + u')', stylesheet['p'])) elements.append(Spacer(1, 3)) elements.append( flowables.Preformatted(u'地址:' + o.take_address, stylesheet['p'])) elements.append(flowables.PageBreak()) doc.build(elements)
from reportlab.graphics.charts.lineplots import LinePlot from reportlab.graphics.charts.legends import Legend from reportlab.lib.styles import ParagraphStyle from reportlab.rl_config import defaultPageSize from reportlab.lib.units import inch from reportlab.lib import colors, fonts from reportlab.graphics.charts.axes import XValueAxis from reportlab.graphics.charts.textlabels import Label from reportlab.platypus.tables import TableStyle from reportlab.pdfbase import pdfmetrics from reportlab.pdfbase.ttfonts import TTFont try: pdfmetrics.registerFont( TTFont('Arial', '/usr/share/fonts/truetype/msttcorefonts/Arial.ttf')) fonts.addMapping('Arial', 0, 0, 'Arial') fonts.addMapping('Arial', 0, 1, 'Arial') Bullet = True except: Bullet = False (PAGE_WIDTH, PAGE_HEIGHT) = defaultPageSize Styles = { 'Normal': ParagraphStyle(name='Normal', fontName='Helvetica', fontSize=10, leading=12, spaceAfter=5, bulletFontName='Arial' if Bullet else 'Helvetica', bulletFontSize=10),
illust(examples.ttffont1, "Using a the Rina TrueType Font") disc("""In the above example the true type font object is created using""") eg(""" TTFont(name,filename) """) disc( """so that the ReportLab internal name is given by the first argument and the second argument is a string(or file like object) denoting the font's TTF file. In Marius' original patch the filename was supposed to be exactly correct, but we have modified things so that if the filename is relative then a search for the corresponding file is done in the current directory and then in directories specified by $reportlab.rl_config.TTFSearchpath$!""") from reportlab.lib.styles import ParagraphStyle from reportlab.lib.fonts import addMapping addMapping('Rina', 0, 0, 'Rina') addMapping('Rina', 0, 1, 'Rina') addMapping('Rina', 1, 0, 'Rina') addMapping('Rina', 1, 1, 'Rina') disc( """Before using the TT Fonts in Platypus we should add a mapping from the family name to the individual font names that describe the behaviour under the $<b>$ and $<i>$ attributes.""" ) eg(""" from reportlab.lib.fonts import addMapping addMapping('Rina', 0, 0, 'Rina') #normal addMapping('Rina', 0, 1, 'Rina') #italic addMapping('Rina', 1, 0, 'Rina') #bold addMapping('Rina', 1, 1, 'Rina') #italic and bold
# encoding = utf-8 import PIL from reportlab.lib.pagesizes import letter from reportlab.lib.utils import ImageReader from reportlab.pdfgen import canvas from DataSource.Code2Name import code2name from Function.SeaSelect.Sub.reportlab_sub import print_k_to_pdf, add_front, add_tail_page from Function.SeaSelect.gen_pic import stk_code from Global_Value.file_dir import sea_select_pic_dir from SDK.MyTimeOPT import get_current_date_str 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') date = '2019-12-28' if __name__ == '__main__': c = canvas.Canvas(U"魔灯海选" + get_current_date_str() + ".pdf", pagesize=letter) c = add_front(c, '魔灯每日股票海选结果' + get_current_date_str(), '本文档由免费开源的量化投资软件“魔灯”自动生成 末尾公众号内有软件介绍', pagesize=letter) c = print_k_to_pdf(c, stk_code, date) c = add_tail_page(c) c.save()
def setTTFontMapping(self, face, fontname, filename, mode='all'): from reportlab.lib.fonts import addMapping from reportlab.pdfbase import pdfmetrics from reportlab.pdfbase.ttfonts import TTFont if fontname not in pdfmetrics._fonts: pdfmetrics.registerFont(TTFont(fontname, filename)) if mode == 'all': addMapping(face, 0, 0, fontname) #normal addMapping(face, 0, 1, fontname) #italic addMapping(face, 1, 0, fontname) #bold addMapping(face, 1, 1, fontname) #italic and bold elif (mode == 'normal') or (mode == 'regular'): addMapping(face, 0, 0, fontname) #normal elif mode == 'italic': addMapping(face, 0, 1, fontname) #italic elif mode == 'bold': addMapping(face, 1, 0, fontname) #bold elif mode == 'bolditalic': addMapping(face, 1, 1, fontname) #italic and bold
def request_crime_record(request): submitted = False if request.method == 'POST': aa = request.POST #totalcrime=CrimeRecord.objects.get(criminal_nrc=aa.get('nrc')).count() response = HttpResponse(content_type='application/pdf;charset=utf-8') response[ 'Content-Disposition'] = 'inline; filename="desktop/mypdf1.pdf"' font_file = 'Pyidaungsu.ttf' pdfmetrics.registerFont(TTFont('Pyidaungsu', font_file)) addMapping('Pyidaungsu', 0, 0, 'Pyidaungsu') width, height = defaultPageSize #actual content dateTimeObj = datetime.datetime.now() timestampStr = dateTimeObj.strftime("%d-%b-%Y (%H:%M:%S.%f)") try: totalcount = CrimeRecord.objects.filter( criminal_nrc=aa.get('nrc')).count() print("totalcount", totalcount) c = CrimeRecord.objects.get(criminal_nrc=aa.get('nrc')) #print(c) except: totalcount = 0 if (totalcount >= 1): print("Criminal") next_line = '\n' # totalcount_str=str(totalcount) pdf_content = u"မင်္ဂလာဒုံမြို့နယ်--------------------------------" + next_line + "စာအမှတ်၊ 1/သဃအ-ရကအ/၂၀ -------------\nရက်စွဲ၊" + timestampStr + '\n---------------------အကြောင်းအရာ။ ထောက်ခံချက်--------------------------------------------------- \n\n' + c.township + '..မြို့နယ်၊..' + c.ward + '..ကျေးရွာ..' + c.street + 'လမ်း၊' + ' ' + c.number + 'အမှတ် ..' + ' ' + 'တွင်နေထိုင်သော (အဘ)ဦး၏ ...သား/သမီးဖြစ်သူ မောင်/မ' + c.criminal_name + ' ... နိုင်ငံသားစိစစ်ရေးကဒ်ပြားအမှတ်' + c.criminal_nrc + '...ကိုင်သောသူသည် ကျေးရွာအုပ်စုအတွင်း...ကျေးရွာအုပ်စုအတွင်း ၌' + ' ပြစ်မှု၊ဥပဒေပုဒ်မ(' + c.potema + ' ) ဖြင့် အမှန်တကယ်ပြစ်မှုကျူးလွန်ထားသူဖြစ်ကြောင်းကို...အပိုင်ဆယ်အိမ်မှူး/ရာအိမ်မှူး ၏ထောက်ခံချက်အရ ...မှန်ကန်ကြောင်း ထပ်ဆင့်ထောက်ခံအပ်ပါသည်။' pdf_content.replace("\n", "<br />") styles = getSampleStyleSheet() styles["Title"].fontName = 'Pyidaungsu' para = Paragraph(pdf_content, styles["Title"]) canv = canvas.Canvas('crime_record1.pdf') para.wrap(width, height) para.drawOn(canv, 0, height / 2) canv.showPage() canv.save() elif (totalcount == 0): print("No crime_record") next_line = '\n' pdf_content = u"မင်္ဂလာဒုံမြို့နယ်--------------------------------" + next_line + "စာအမှတ်၊ 1/သဃအ-ရကအ/၂၀ -------------\nရက်စွဲ၊" + timestampStr + '\n---------------------အကြောင်းအရာ။ ထောက်ခံချက်--------------------------------------------------- \n\n' + aa.get( 'nrc' ) + 'သည် ပြစ်မှုကင်းစင်ကြောင် ကျေးကျေးရွာအုပ်စုအတွင်း...ကျေးရွာအုပ်စုအတွင်း...အပိုင်ဆယ်အိမ်မှူး/ရာအိမ်မှူး ၏ထောက်ခံချက်အရ ...မှန်ကန်ကြောင်း ထပ်ဆင့်ထောက်ခံအပ်ပါသည်။' pdf_content.replace("\n", "<br />") styles = getSampleStyleSheet() styles["Title"].fontName = 'Pyidaungsu' para = Paragraph(pdf_content, styles["Title"]) canv = canvas.Canvas('crime_record2.pdf') para.wrap(width, height) para.drawOn(canv, 0, height / 2) canv.showPage() canv.save() return response else: form = TestModel() if 'submitted' in request.GET: submitted = True return render(request, 'request_crime_record.html', { 'form': form, 'submitted': submitted })
class FeedPDF(object): FONT_MEIRYO = 'Meiryo' FONT_MEIRYO_BOLD = 'Meiryo-Bold' django_settings.PDF_FONT_DIR pdfmetrics.registerFont(TTFont(FONT_MEIRYO, django_settings.PDF_FONT_DIR + 'meiryo.ttc')) pdfmetrics.registerFont(TTFont(FONT_MEIRYO_BOLD, django_settings.PDF_FONT_DIR + 'meiryob.ttc')) fonts.addMapping(FONT_MEIRYO, 0, 0, FONT_MEIRYO) # normal fonts.addMapping(FONT_MEIRYO, 0, 1, FONT_MEIRYO + '-Italic') # italic fonts.addMapping(FONT_MEIRYO, 1, 0, FONT_MEIRYO + '-Bold') # bold fonts.addMapping(FONT_MEIRYO, 1, 1, FONT_MEIRYO + '-BoldItalic') # italic and bold def __init__(self, feed, stix_package): self.feed = feed self.stix_package = stix_package # Header文字列を取得する def set_header_string(self): if self.stix_package is not None: return 'S-TIP CTI PDF Report: %s' % (self.stix_package.id_) else: return 'S-TIP CTI PDF Report' # Footer文字列を取得する def set_footer_string(self): t_format = '%B %-d, %Y %H:%M%z' d = datetime.datetime.now(pytz.timezone(django_settings.TIME_ZONE)) return 'CTI Converted to PDF by S-TIP - %s' % (d.strftime(t_format)) # 各ページ共通描画 def set_common_per_page(self, canvas, doc): PAGE_WIDTH, PAGE_HEIGHT = pagesizes.A4 PDF_HEADER_FONT_SIZE = 8 canvas.saveState() # header string = self.set_header_string() canvas.setFont(self.FONT_MEIRYO, PDF_HEADER_FONT_SIZE) canvas.drawCentredString((PAGE_WIDTH / 2.0), (PAGE_HEIGHT - 20), string) # footer string = self.set_footer_string() canvas.setFont(self.FONT_MEIRYO, PDF_HEADER_FONT_SIZE) canvas.drawCentredString((PAGE_WIDTH / 2.0), 20, string) # 左上: アイコン image_path = django_settings.PDF_IMAGE_DIR + 'apple-icon-180x180.png' canvas.drawImage(image_path, 10*mm, 285*mm, width=10*mm, height=10*mm, preserveAspectRatio=True, mask=[0, 0, 0, 0, 0, 0]) # 右上: TLP表記 string = 'TLP: %s' % (self.feed.tlp.upper()) # Tableにて実装 data = [[string], ] table = Table(data) if self.feed.tlp.upper() == 'RED': color = '#FF0033' elif self.feed.tlp.upper() == 'AMBER': color = '#FFC000' elif self.feed.tlp.upper() == 'GREEN': color = '#33FF00' else: color = '#FFFFFF' table.setStyle(TableStyle([ # 背景色は黒 ('BACKGROUND', (0, 0), (-1, -1), colors.black), # テキスト色はTLPによって異なる ('TEXTCOLOR', (0, 0), (-1, -1), color), # 表で使うフォントとそのサイズを設定 ('FONT', (0, 0), (-1, -1), self.FONT_MEIRYO, 9), # ('FONT', (0, 0), (-1, -1), 'CJK', 9), # 四角に罫線を引いて、0.5の太さで、色は黒 ('BOX', (0, 0), (-1, -1), 1, colors.black), # 四角の内側に格子状の罫線を引いて、0.25の太さで、色は赤 ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black), # セルの縦文字位置を、TOPにする ('VALIGN', (0, 0), (-1, -1), 'TOP'), ])) # 配置位置 table.wrapOn(canvas, 180*mm, 287*mm) table.drawOn(canvas, 180*mm, 287*mm) canvas.restoreState() def first_page(self, canvas, doc): self.set_common_per_page(canvas, doc) def last_page(self, canvas, doc): self.set_common_per_page(canvas, doc) # PDF作成 def make_pdf_content(self, response, feed): HEADER_BACKGROUND_COLOR = colors.HexColor('#48ACC6') EVEN_BACKGROUND_COLOR = colors.HexColor('#DAEEF3') ODD_BACKGROUND_COLOR = colors.white # style変更 styles = getSampleStyleSheet() for name in ('Normal', 'BodyText', 'Title', 'Heading1', 'Heading2', 'Heading3', 'Heading4', 'Heading5', 'Heading6', 'Bullet', 'Definition', 'Code'): styles[name].wordWrap = 'CJK' styles[name].fontName = 'meiryo' # doc作成 doc = SimpleDocTemplate(response, pagesize=portrait(A4)) story = [] # Title string = '<b>Title:</b> %s' % (feed.title) story.append(Paragraph(string, styles['Normal'])) # Author if feed.administrative_code is None: administrative_code = '-' else: administrative_code = feed.administrative_code if feed.country_code is None: country_code = '-' else: country_code = feed.country_code string = '%s (%s - %s, %s)' % (feed.user.get_screen_name(), feed.user.get_sector_display(), administrative_code, country_code) txt = '<b>Author:</b> %s' % (string) story.append(Paragraph(txt, styles['Normal'])) # Produced Time string = str(self.stix_package.timestamp) txt = '<b>Produced Time:</b> %s' % (string) story.append(Paragraph(txt, styles['Normal'])) # STIX Package ID string = str(self.stix_package.id_) txt = '<b>STIX Package ID:</b> %s' % (string) story.append(Paragraph(txt, styles['Normal'])) # 空行 story.append(Spacer(1, 1.0*cm)) # content txt = '<b>Content:</b>' story.append(Paragraph(txt, styles['Normal'])) # txt = feed.post.value.encode('utf-8') txt = feed.post story.append(Paragraph(txt, styles['Normal'])) # 空行 story.append(Spacer(1, 1.0*cm)) # STIXからObservablesとIndicatorsを抽出 indicators = FeedStix.get_indicators(self.stix_package) if len(indicators) == 0: txt = '<b>Indicators: </b>None' story.append(Paragraph(txt, styles['Normal'])) else: txt = '<b>Indicators:</b>' story.append(Paragraph(txt, styles['Normal'])) # 空行 story.append(Spacer(1, 0.1*cm)) # Table d = [ # header ['Type', 'Indicators'], ] # STIXからObservablesとIndicatorsを抽出 for item in indicators: (type_, value, _) = item item = [] item.append(type_) # file_nameの場合は値がパイプで囲まれている if type_ == 'file_name': # 前後のパイプをトリミング value = value[1:-1] item.append(value) d.append(item) # この幅くらいがちょうどよい table = Table(d, colWidths=(20*mm, 135*mm), rowHeights=6*mm) table.setStyle(TableStyle([ # 背景色 # 先頭行(ヘッダ) # 2ECCFA ('BACKGROUND', (0, 0), (-1, 0), HEADER_BACKGROUND_COLOR), # 表で使うフォントとそのサイズを設定 ('FONT', (0, 0), (-1, -1), self.FONT_MEIRYO, 9), # 先頭行だけbold ('FONT', (0, 0), (-1, 0), self.FONT_MEIRYO_BOLD, 9), # 先頭行は白 ('TEXTCOLOR', (0, 0), (-1, 0), colors.white), # 罫線 ('BOX', (0, 0), (-1, -1), 0.10, HEADER_BACKGROUND_COLOR), ('INNERGRID', (0, 0), (-1, -1), 0.10, HEADER_BACKGROUND_COLOR), # セルの縦文字位置を、TOPにする ('VALIGN', (0, 0), (-1, -1), 'TOP'), ])) # stripe for i in range(len(indicators)): if (i % 2) == 0: table.setStyle(TableStyle([ ('BACKGROUND', (0, i + 1), (-1, i + 1), EVEN_BACKGROUND_COLOR), ('TEXTCOLOR', (0, i + 1), (-1, i + 1), colors.black), ])) else: table.setStyle(TableStyle([ ('BACKGROUND', (0, i + 1), (-1, i + 1), ODD_BACKGROUND_COLOR), ('TEXTCOLOR', (0, i + 1), (-1, i + 1), colors.black), ])) story.append(table) # 改ページ story.append(PageBreak()) # PDF 作成 doc.build(story, onFirstPage=self.first_page, onLaterPages=self.last_page)
def autoEmbed(fname): """Given a font name, does a best-effort of embedding said font and its variants. Returns a list of the font names it registered with ReportLab. """ log.info('Trying to embed %s' % fname) fontList = [] variants = [] f = findFont(fname) if f: # We have this font located if f[0].lower()[-4:] == '.afm': #Type 1 font family = families[f[2]] # Register the whole family of faces faces = [ pdfmetrics.EmbeddedType1Face(*fonts[fn.lower()][:2]) for fn in family ] for face in faces: pdfmetrics.registerTypeFace(face) for face, name in zip(faces, family): fontList.append(name) font = pdfmetrics.Font(face, name, "WinAnsiEncoding") log.info('Registering font: %s from %s'%\ (face,name)) pdfmetrics.registerFont(font) # Map the variants regular, italic, bold, bolditalic = family addMapping(fname, 0, 0, regular) addMapping(fname, 0, 1, italic) addMapping(fname, 1, 0, bold) addMapping(fname, 1, 1, bolditalic) addMapping(regular, 0, 0, regular) addMapping(regular, 0, 1, italic) addMapping(regular, 1, 0, bold) addMapping(regular, 1, 1, bolditalic) log.info('Embedding as %s' % fontList) return fontList else: # A TTF font variants = [fonts[f.lower()][0] for f in families[f[2]]] if not variants: # Try fc-match variants = findTTFont(fname) # It is a TT Font and we found it using fc-match (or found *something*) if variants: for variant in variants: vname = os.path.basename(variant)[:-4] try: if vname not in pdfmetrics._fonts: _font = TTFont(vname, variant, validate=1) log.info('Registering font: %s from %s'%\ (vname,variant)) pdfmetrics.registerFont(_font) except TTFError: log.error('Error registering font: %s from %s' % (vname, variant)) else: fontList.append(vname) regular, bold, italic, bolditalic = [ os.path.basename(variant)[:-4] for variant in variants ] addMapping(regular, 0, 0, regular) addMapping(regular, 0, 1, italic) addMapping(regular, 1, 0, bold) addMapping(regular, 1, 1, bolditalic) log.info('Embedding via findTTFont as %s' % fontList) return fontList
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 __init__(self, flist, font_path=None, style_path=None, def_dpi=300): log.info('Using stylesheets: %s' % ','.join(flist)) # find base path if hasattr(sys, 'frozen'): self.PATH = abspath(dirname(sys.executable)) else: self.PATH = abspath(dirname(__file__)) # flist is a list of stylesheet filenames. # They will be loaded and merged in order. # but the two default stylesheets will always # be loaded first flist = [ join(self.PATH, 'styles', 'styles.style'), join(self.PATH, 'styles', 'default.style') ] + flist self.def_dpi = def_dpi if font_path is None: font_path = [] font_path += ['.', os.path.join(self.PATH, 'fonts')] self.FontSearchPath = map(os.path.expanduser, font_path) if style_path is None: style_path = [] style_path += [ '.', os.path.join(self.PATH, 'styles'), '~/.rst2pdf/styles' ] self.StyleSearchPath = map(os.path.expanduser, style_path) self.FontSearchPath = list(set(self.FontSearchPath)) self.StyleSearchPath = list(set(self.StyleSearchPath)) log.info('FontPath:%s' % self.FontSearchPath) log.info('StylePath:%s' % self.StyleSearchPath) findfonts.flist = self.FontSearchPath # Page width, height self.pw = 0 self.ph = 0 # Page size [w,h] self.ps = None # Margins (top,bottom,left,right,gutter) self.tm = 0 self.bm = 0 self.lm = 0 self.rm = 0 self.gm = 0 #text width self.tw = 0 # Default emsize, later it will be the fontSize of the base style self.emsize = 10 self.languages = [] ssdata = self.readSheets(flist) # Get pageSetup data from all stylessheets in order: self.ps = pagesizes.A4 self.page = {} for data, ssname in ssdata: page = data.get('pageSetup', {}) if page: self.page.update(page) pgs = page.get('size', None) if pgs: # A standard size pgs = pgs.upper() if pgs in pagesizes.__dict__: self.ps = list(pagesizes.__dict__[pgs]) self.psname = pgs if 'width' in self.page: del (self.page['width']) if 'height' in self.page: del (self.page['height']) elif pgs.endswith('-LANDSCAPE'): self.psname = pgs.split('-')[0] self.ps = list( pagesizes.landscape( pagesizes.__dict__[self.psname])) if 'width' in self.page: del (self.page['width']) if 'height' in self.page: del (self.page['height']) else: log.critical('Unknown page size %s in stylesheet %s'%\ (page['size'], ssname)) continue else: #A custom size if 'size' in self.page: del (self.page['size']) # The sizes are expressed in some unit. # For example, 2cm is 2 centimeters, and we need # to do 2*cm (cm comes from reportlab.lib.units) if 'width' in page: self.ps[0] = self.adjustUnits(page['width']) if 'height' in page: self.ps[1] = self.adjustUnits(page['height']) self.pw, self.ph = self.ps if 'margin-left' in page: self.lm = self.adjustUnits(page['margin-left']) if 'margin-right' in page: self.rm = self.adjustUnits(page['margin-right']) if 'margin-top' in page: self.tm = self.adjustUnits(page['margin-top']) if 'margin-bottom' in page: self.bm = self.adjustUnits(page['margin-bottom']) if 'margin-gutter' in page: self.gm = self.adjustUnits(page['margin-gutter']) if 'spacing-header' in page: self.ts = self.adjustUnits(page['spacing-header']) if 'spacing-footer' in page: self.bs = self.adjustUnits(page['spacing-footer']) if 'firstTemplate' in page: self.firstTemplate = page['firstTemplate'] # tw is the text width. # We need it to calculate header-footer height # and compress literal blocks. self.tw = self.pw - self.lm - self.rm - self.gm # Get page templates from all stylesheets self.pageTemplates = {} for data, ssname in ssdata: templates = data.get('pageTemplates', {}) # templates is a dictionary of pageTemplates for key in templates: template = templates[key] # template is a dict. # template[´frames'] is a list of frames if key in self.pageTemplates: self.pageTemplates[key].update(template) else: self.pageTemplates[key] = template # Get font aliases from all stylesheets in order self.fontsAlias = {} for data, ssname in ssdata: self.fontsAlias.update(data.get('fontsAlias', {})) embedded_fontnames = [] self.embedded = [] # Embed all fonts indicated in all stylesheets for data, ssname in ssdata: embedded = data.get('embeddedFonts', []) for font in embedded: try: # Just a font name, try to embed it if isinstance(font, unicode): # See if we can find the font fname, pos = findfonts.guessFont(font) if font in embedded_fontnames: pass else: fontList = findfonts.autoEmbed(font) if fontList: embedded_fontnames.append(font) if not fontList: if (fname, pos) in embedded_fontnames: fontList = None else: fontList = findfonts.autoEmbed(fname) if fontList is not None: self.embedded += fontList # Maybe the font we got is not called # the same as the one we gave # so check that out suff = ["", "-Oblique", "-Bold", "-BoldOblique"] if not fontList[0].startswith(font): # We need to create font aliases, and use them for fname, aliasname in zip( fontList, [font + suffix for suffix in suff]): self.fontsAlias[aliasname] = fname continue # Each "font" is a list of four files, which will be # used for regular / bold / italic / bold+italic # versions of the font. # If your font doesn't have one of them, just repeat # the regular font. # Example, using the Tuffy font from # http://tulrich.com/fonts/ # "embeddedFonts" : [ # ["Tuffy.ttf", # "Tuffy_Bold.ttf", # "Tuffy_Italic.ttf", # "Tuffy_Bold_Italic.ttf"] # ], # The fonts will be registered with the file name, # minus the extension. if font[0].lower().endswith('.ttf'): # A True Type font for variant in font: location = self.findFont(variant) pdfmetrics.registerFont( TTFont(str(variant.split('.')[0]), location)) log.info('Registering font: %s from %s'%\ (str(variant.split('.')[0]),location)) self.embedded.append(str(variant.split('.')[0])) # And map them all together regular, bold, italic, bolditalic = [ variant.split('.')[0] for variant in font ] addMapping(regular, 0, 0, regular) addMapping(regular, 0, 1, italic) addMapping(regular, 1, 0, bold) addMapping(regular, 1, 1, bolditalic) else: # A Type 1 font # For type 1 fonts we require # [FontName,regular,italic,bold,bolditalic] # where each variant is a (pfbfile,afmfile) pair. # For example, for the URW palladio from TeX: # ["Palatino",("uplr8a.pfb","uplr8a.afm"), # ("uplri8a.pfb","uplri8a.afm"), # ("uplb8a.pfb","uplb8a.afm"), # ("uplbi8a.pfb","uplbi8a.afm")] faceName = font[0] regular = pdfmetrics.EmbeddedType1Face(*font[1]) italic = pdfmetrics.EmbeddedType1Face(*font[2]) bold = pdfmetrics.EmbeddedType1Face(*font[3]) bolditalic = pdfmetrics.EmbeddedType1Face(*font[4]) except Exception as e: try: if isinstance(font, list): fname = font[0] else: fname = font log.error("Error processing font %s: %s", os.path.splitext(fname)[0], str(e)) log.error("Registering %s as Helvetica alias", fname) self.fontsAlias[fname] = 'Helvetica' except Exception as e: log.critical("Error processing font %s: %s", fname, str(e)) continue # Go though all styles in all stylesheets and find all fontNames. # Then decide what to do with them for data, ssname in ssdata: for [skey, style] in self.stylepairs(data): for key in style: if key == 'fontName' or key.endswith('FontName'): # It's an alias, replace it if style[key] in self.fontsAlias: style[key] = self.fontsAlias[style[key]] # Embedded already, nothing to do if style[key] in self.embedded: continue # Standard font, nothing to do if style[key] in ("Courier", "Courier-Bold", "Courier-BoldOblique", "Courier-Oblique", "Helvetica", "Helvetica-Bold", "Helvetica-BoldOblique", "Helvetica-Oblique", "Symbol", "Times-Bold", "Times-BoldItalic", "Times-Italic", "Times-Roman", "ZapfDingbats"): continue # Now we need to do something # See if we can find the font fname, pos = findfonts.guessFont(style[key]) if style[key] in embedded_fontnames: pass else: fontList = findfonts.autoEmbed(style[key]) if fontList: embedded_fontnames.append(style[key]) if not fontList: if (fname, pos) in embedded_fontnames: fontList = None else: fontList = findfonts.autoEmbed(fname) if fontList: embedded_fontnames.append((fname, pos)) if fontList: self.embedded += fontList # Maybe the font we got is not called # the same as the one we gave so check that out suff = ["", "-Bold", "-Oblique", "-BoldOblique"] if not fontList[0].startswith(style[key]): # We need to create font aliases, and use them basefname = style[key].split('-')[0] for fname, aliasname in zip( fontList, [basefname + suffix for suffix in suff]): self.fontsAlias[aliasname] = fname style[key] = self.fontsAlias[basefname +\ suff[pos]] else: log.error( "Unknown font: \"%s\"," "replacing with Helvetica", style[key]) style[key] = "Helvetica" #log.info('FontList: %s'%self.embedded) #log.info('FontAlias: %s'%self.fontsAlias) # Get styles from all stylesheets in order self.stylesheet = {} self.styles = [] self.linkColor = 'navy' # FIXME: linkColor should probably not be a global # style, and tocColor should probably not # be a special case, but for now I'm going # with the flow... self.tocColor = None for data, ssname in ssdata: self.linkColor = data.get('linkColor') or self.linkColor self.tocColor = data.get('tocColor') or self.tocColor for [skey, style] in self.stylepairs(data): sdict = {} # FIXME: this is done completely backwards for key in style: # Handle color references by name if key == 'color' or key.endswith('Color') and style[key]: style[key] = formatColor(style[key]) # Yet another workaround for the unicode bug in # reportlab's toColor elif key == 'commands': style[key] = validateCommands(style[key]) #for command in style[key]: #c=command[0].upper() #if c=='ROWBACKGROUNDS': #command[3]=[str(c) for c in command[3]] #elif c in ['BOX','INNERGRID'] or c.startswith('LINE'): #command[4]=str(command[4]) # Handle alignment constants elif key == 'alignment': style[key] = dict( TA_LEFT=0, LEFT=0, TA_CENTER=1, CENTER=1, TA_CENTRE=1, CENTRE=1, TA_RIGHT=2, RIGHT=2, TA_JUSTIFY=4, JUSTIFY=4, DECIMAL=8, )[style[key].upper()] elif key == 'language': if not style[key] in self.languages: self.languages.append(style[key]) # Make keys str instead of unicode (required by reportlab) sdict[str(key)] = style[key] sdict['name'] = skey # If the style already exists, update it if skey in self.stylesheet: self.stylesheet[skey].update(sdict) else: # New style self.stylesheet[skey] = sdict self.styles.append(sdict) # If the stylesheet has a style name docutils won't reach # make a copy with a sanitized name. # This may make name collisions possible but that should be # rare (who would have custom_name and custom-name in the # same stylesheet? ;-) # Issue 339 styles2 = [] for s in self.styles: if not re.match("^[a-z](-?[a-z0-9]+)*$", s['name']): s2 = copy(s) s2['name'] = docutils.nodes.make_id(s['name']) log.warning( '%s is an invalid docutils class name, adding alias %s' % (s['name'], s2['name'])) styles2.append(s2) self.styles.extend(styles2) # And create reportlabs stylesheet self.StyleSheet = StyleSheet1() # Patch to make the code compatible with reportlab from SVN 2.4+ and # 2.4 if not hasattr(self.StyleSheet, 'has_key'): self.StyleSheet.__class__.has_key = lambda s, k: k in s for s in self.styles: if 'parent' in s: if s['parent'] is None: if s['name'] != 'base': s['parent'] = self.StyleSheet['base'] else: del (s['parent']) else: s['parent'] = self.StyleSheet[s['parent']] else: if s['name'] != 'base': s['parent'] = self.StyleSheet['base'] # If the style has no bulletFontName but it has a fontName, set it if ('bulletFontName' not in s) and ('fontName' in s): s['bulletFontName'] = s['fontName'] hasFS = True # Adjust fontsize units if 'fontSize' not in s: s['fontSize'] = s['parent'].fontSize s['trueFontSize'] = None hasFS = False elif 'parent' in s: # This means you can set the fontSize to # "2cm" or to "150%" which will be calculated # relative to the parent style s['fontSize'] = self.adjustUnits(s['fontSize'], s['parent'].fontSize) s['trueFontSize'] = s['fontSize'] else: # If s has no parent, it's base, which has # an explicit point size by default and % # makes no sense, but guess it as % of 10pt s['fontSize'] = self.adjustUnits(s['fontSize'], 10) # If the leading is not set, but the size is, set it if 'leading' not in s and hasFS: s['leading'] = 1.2 * s['fontSize'] # If the bullet font size is not set, set it as fontSize if ('bulletFontSize' not in s) and ('fontSize' in s): s['bulletFontSize'] = s['fontSize'] # If the borderPadding is a list and wordaxe <=0.3.2, # convert it to an integer. Workaround for Issue if 'borderPadding' in s and ((HAS_WORDAXE and \ wordaxe_version <='wordaxe 0.3.2') or reportlab.Version < "2.3" )\ and isinstance(s['borderPadding'], list): log.warning('Using a borderPadding list in '\ 'style %s with wordaxe <= 0.3.2 or Reportlab < 2.3. That is not '\ 'supported, so it will probably look wrong'%s['name']) s['borderPadding'] = s['borderPadding'][0] self.StyleSheet.add(ParagraphStyle(**s)) self.emsize = self['base'].fontSize # Make stdFont the basefont, for Issue 65 reportlab.rl_config.canvas_basefontname = self['base'].fontName # Make stdFont the default font for table cell styles (Issue 65) reportlab.platypus.tables.CellStyle.fontname = self['base'].fontName
def process(self): args = self.getAttributeValues(valuesOnly=True) fonts.addMapping(*args)
from reportlab.pdfgen import canvas from reportlab.lib.units import inch, mm from reportlab.lib.pagesizes import A4, letter from reportlab.lib.styles import getSampleStyleSheet from reportlab.platypus import * from reportlab.lib import colors from reportlab.pdfbase import pdfmetrics from reportlab.pdfbase.ttfonts import TTFont pdfmetrics.registerFont(TTFont('hei', 'hei.ttf')) from reportlab.lib import fonts fonts.addMapping('hei', 0, 0, 'hei') fonts.addMapping('hei', 0, 1, 'hei') import copy def hello(): c = canvas.Canvas("../hellozhizying.pdf") c.drawString(10, 800, "hellozhiying") c.drawString(10, 700, "hellopython") c.drawString(10, 600, "你好") c.drawString(10, 500, "nihao") c.showPage() c.save() # hello() def pdf_generator(pdf_url, pdf_data): pdf_data = {
from reportlab.pdfbase import pdfmetrics from reportlab.pdfbase.ttfonts import TTFont from reportlab.lib.styles import getSampleStyleSheet from reportlab.lib import fonts from reportlab.lib.pagesizes import letter from reportlab.platypus import Paragraph, SimpleDocTemplate # 英文字体 Arial # 建立字体的映射关系 registerFont => addMapping => tt2ps pdfmetrics.registerFont(TTFont('Arial', 'Arial.ttf')) pdfmetrics.registerFont(TTFont('Arial-Italic', 'Arial Italic.ttf')) pdfmetrics.registerFont(TTFont('Arial-Bold', 'Arial Bold.ttf')) pdfmetrics.registerFont(TTFont('Arial-BoldItalic', 'Arial Bold Italic.ttf')) fonts.addMapping('arial', 0, 0, 'Arial') fonts.addMapping('arial', 0, 1, 'Arial-Italic') fonts.addMapping('arial', 1, 0, 'Arial-Bold') fonts.addMapping('arial', 1, 1, 'Arial-BoldItalic') arial_font_name = fonts.tt2ps('arial', 0, 0) arial_font_name_i = fonts.tt2ps(arial_font_name, 0, 1) arial_font_name_b = fonts.tt2ps(arial_font_name, 1, 0) arial_font_name_bi = fonts.tt2ps(arial_font_name, 1, 1) # 中文字体 宋体-简 # 正常、斜体、粗体等都在一个字体文件里,需要使用subfontIndex pdfmetrics.registerFont(TTFont('Songti', 'Songti.ttc', subfontIndex=3)) pdfmetrics.registerFont(TTFont('Songti-Italic', 'Songti.ttc', subfontIndex=2)) pdfmetrics.registerFont(TTFont('Songti-Bold', 'Songti.ttc', subfontIndex=1)) pdfmetrics.registerFont(
def get(self, request, *args, **kwargs): """! Función que construye el certificado con los datos del usuario @author William Páez <*****@*****.**> @param self <b>{object}</b> Objeto que instancia la clase @param request <b>{object}</b> Objeto que contiene la petición @param *args <b>{tupla}</b> Tupla de valores, inicialmente vacia @param **kwargs <b>{dict}</b> Diccionario de datos, inicialmente vacio @return Certificado del usuario en un pdf """ response = HttpResponse(content_type='application/pdf') if Subscriber.objects.filter(event=kwargs['evento'], profile=self.request.user.profile): subscriber = Subscriber.objects.get( event=kwargs['evento'], profile=self.request.user.profile) front_image = subscriber.event.certificate.front_image.path # print(imagen_delantera) if subscriber.event.certificate.back_image: back_image = subscriber.event.certificate.back_image.path # print(imagen_tracera) else: back_image = None width = subscriber.event.certificate.front_image.width certificate_width = width / 2 # print('ancho certificado: ' + str(ancho_certificado)) first_name = subscriber.profile.user.first_name last_name = subscriber.profile.user.last_name name = first_name + last_name if len(name) <= 18: name_width = (len(name) * 22) / 2 else: name_width = (len(name) * 14) / 2 # print('ancho nombre: ' + str(ancho_nombre)) coordinate_x_name = certificate_width - name_width # print(coordenada_x_nombre) coordinate_y_name = subscriber.event.certificate.coordinate_y_name coordinate_name = coordinate_x_name, coordinate_y_name # print(coordenada_nombre) u = subscriber.profile.user.username[0] + '-' +\ subscriber.profile.user.username[1:3] + '.' +\ subscriber.profile.user.username[3:6] + '.' +\ subscriber.profile.user.username[6:] username = '******' % u # print(len(username)) username_width = (len(username) * 14) / 2 # print(ancho_username) coordinate_x_username = certificate_width - username_width # print(coordenada_x_username) coordinate_y_name = subscriber.event.certificate.coordinate_y_name coordinate_username = coordinate_x_username, coordinate_y_name - 40 # print(coordenada_username) group = self.request.user.groups.all() role_width = (len(str(group[0])) * 14) / 2 # print(ancho_rol) coordinate_x_role = certificate_width - role_width coordinate_y_name = subscriber.event.certificate.coordinate_y_name coordinate_role = coordinate_x_role, coordinate_y_name - 70 # print(coordenada_rol) role = str(group[0]) thematic = subscriber.event.certificate.thematic BASE_DIR = os.path.dirname( os.path.dirname(os.path.abspath(__file__))) pdfmetrics.registerFont( TTFont( 'Roboto-Regular', os.path.join(BASE_DIR, 'static/css/font/Roboto/Roboto-Regular.ttf'))) addMapping('Roboto-Regular', 0, 0, 'Roboto-Regular') buffer = BytesIO() pdf = canvas.Canvas(buffer, landscape(letter), bottomup=50) front_img = Image.open(front_image) # ImageDraw.Draw(front_img) # draw = ImageDraw.Draw(front_img) pdf.setTitle( '%s-%s' % (subscriber.profile.user.username, subscriber.event.id)) pdf.setAuthor('Sofi') # pdf.setSubject('') pdf.setCreator('CENDITEL') pdf.drawInlineImage(front_img, 0, 0) pdf.setFillColorRGB(0, 0, 0) pdf.setFont('Roboto-Regular', 30) first_name = subscriber.profile.user.first_name last_name = subscriber.profile.user.last_name pdf.drawString(coordinate_name[0], coordinate_name[1], first_name + ' ' + last_name) pdf.setFont('Roboto-Regular', 25) pdf.drawString(coordinate_username[0], coordinate_username[1], username) pdf.setFont('Roboto-Regular', 20) pdf.drawString(coordinate_role[0], coordinate_role[1], role) pdf.showPage() if back_image: back_img = Image.open(back_image) # ImageDraw.Draw(back_img) # draw = ImageDraw.Draw(back_img) pdf.drawInlineImage(back_img, 0, 0) thematic_pdf = pdf.beginText(50, 562) thematic_pdf.textLines(thematic.splitlines()) pdf.drawText(thematic_pdf) pdf.showPage() pdf.save() pdf = buffer.getvalue() buffer.close() username = subscriber.profile.user.username id = subscriber.event.id response[ 'Content-Disposition'] = 'attachment; filename=%s-%s.pdf' % ( username, id) response.write(pdf) return response
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') # 获取纸面的高度和宽度 w = letter[0] h = letter[1] def add_front(canvas_param, theme, subtitle, pagesize=letter): """ 函数功能:为pdf文档添加功能,分“主题”、“副标题”两部分 :param canvas: :param pagesize: 页面大小,默认A4 :param theme: 主题字符串
#coding=utf-8 import reportlab.rl_config reportlab.rl_config.warnOnMissingFontGlyphs = 0 from reportlab.pdfbase import pdfmetrics from reportlab.pdfbase.ttfonts import TTFont from reportlab.pdfgen import canvas pdfmetrics.registerFont(TTFont('SimKai', 'SimKai.ttf')) from reportlab.lib import fonts fonts.addMapping('SimKai', 0, 0, 'SimKai') import copy from reportlab.platypus import Paragraph, SimpleDocTemplate, PageBreak from reportlab.lib.styles import getSampleStyleSheet stylesheet = getSampleStyleSheet() normalStyle = copy.deepcopy(stylesheet['Normal']) normalStyle.fontName = 'SimKai' normalStyle.fontSize = 20 s = [['阿', '的']] story = [] story.append(Paragraph(s, normalStyle)) doc = SimpleDocTemplate('hello.pdf') doc.build(story)
def get_report_styles(): # Output container for all derived styles report_styles = {} # Register additional font support rl_config.warnOnMissingFontGlyphs = 0 pdfmetrics.registerFont(TTFont('Garamond', 'C:/windows/fonts/gara.ttf')) pdfmetrics.registerFont( TTFont('Garamond-Bold', 'C:/windows/fonts/garabd.ttf')) pdfmetrics.registerFont( TTFont('Garamond-Italic', 'C:/windows/fonts/garait.ttf')) fonts.addMapping('Garamond', 0, 0, 'Garamond') fonts.addMapping('Garamond', 0, 1, 'Garamond-Italic') fonts.addMapping('Garamond', 1, 0, 'Garamond-Bold') fonts.addMapping('Garamond', 1, 1, 'Garamond-Italic') lead_multiplier = 1.20 body_style = styles.ParagraphStyle( name='Normal', fontName='Garamond', fontSize=11.5, leading=11.5 * lead_multiplier, alignment=enums.TA_LEFT, ) report_styles['body_style'] = body_style body_style_right = styles.ParagraphStyle( name='BodyRight', parent=body_style, alignment=enums.TA_RIGHT, ) report_styles['body_style_right'] = body_style_right body_style_center = styles.ParagraphStyle( name='BodyCenter', parent=body_style, alignment=enums.TA_CENTER, ) report_styles['body_style_center'] = body_style_center body_style_10 = styles.ParagraphStyle( name='BodySmall', parent=body_style, fontSize=10, leading=10 * lead_multiplier, ) report_styles['body_style_10'] = body_style_10 body_style_9 = styles.ParagraphStyle( name='Body9', parent=body_style, fontSize=9, leading=9 * lead_multiplier, ) report_styles['body_style_9'] = body_style_9 body_style_10_right = styles.ParagraphStyle( name='BodySmallRight', parent=body_style_10, alignment=enums.TA_RIGHT, ) report_styles['body_style_10_right'] = body_style_10_right body_style_10_center = styles.ParagraphStyle( name='BodySmallCenter', parent=body_style_10, alignment=enums.TA_CENTER, ) report_styles['body_style_10_center'] = body_style_10_center indented = styles.ParagraphStyle( name='Indented', parent=body_style, leftIndent=24, ) report_styles['indented'] = indented contact_style = styles.ParagraphStyle( name='Contact', parent=body_style, fontSize=10, ) report_styles['contact_style'] = contact_style contact_style_right = styles.ParagraphStyle( name='ContactRight', parent=contact_style, alignment=enums.TA_RIGHT, ) report_styles['contact_style_right'] = contact_style_right contact_style_right_bold = styles.ParagraphStyle( name='ContactRightBold', parent=contact_style_right, fontName='Garamond-Bold', ) report_styles['contact_style_right_bold'] = contact_style_right_bold heading_style = styles.ParagraphStyle( name='Heading', parent=body_style, fontName='Garamond-Bold', fontSize=16, leading=16 * lead_multiplier, ) report_styles['heading_style'] = heading_style code_style = styles.ParagraphStyle( name='Code', parent=body_style, fontSize=7, leading=7 * lead_multiplier, ) report_styles['code_style'] = code_style code_style_right = styles.ParagraphStyle( name='CodeRight', parent=code_style, alignment=enums.TA_RIGHT, ) report_styles['code_style_right'] = code_style_right title_style = styles.ParagraphStyle( name='Title', parent=body_style, fontName='Garamond-Bold', fontSize=18, leading=18 * lead_multiplier, leftIndent=1.7 * u.inch, ) report_styles['title_style'] = title_style sub_title_style = styles.ParagraphStyle( name='Subtitle', parent=title_style, fontName='Garamond', fontSize=14, leading=14 * lead_multiplier, ) report_styles['sub_title_style'] = sub_title_style section_style = styles.ParagraphStyle( name='Section', parent=title_style, alignment=enums.TA_CENTER, leftIndent=0.0, ) report_styles['section_style'] = section_style default_table_style = p.TableStyle([ ('GRID', (0, 0), (-1, -1), 1, colors.white), ('ALIGNMENT', (0, 0), (-1, -1), 'LEFT'), ('VALIGN', (0, 0), (-1, -1), 'TOP'), ('TOPPADDING', (0, 0), (-1, -1), 2), ('BOTTOMPADDING', (0, 0), (-1, -1), 2), ]) report_styles['default_table_style'] = default_table_style return report_styles
def loadFont(self, names, src, encoding="WinAnsiEncoding", bold=0, italic=0): # XXX Just works for local filenames! if names and src: file = src src = file.uri log.debug("Load font %r", src) if type(names) is types.ListType: fontAlias = names else: fontAlias = (x.lower().strip() for x in names.split(",") if x) # XXX Problems with unicode here fontAlias = [str(x) for x in fontAlias] fontName = fontAlias[0] parts = src.split(".") baseName, suffix = ".".join(parts[:-1]), parts[-1] suffix = suffix.lower() if suffix in ["ttc", "ttf"]: # determine full font name according to weight and style fullFontName = "%s_%d%d" % (fontName, bold, italic) # check if font has already been registered if fullFontName in self.fontList: log.warn( self.warning( "Repeated font embed for %s, skip new embed ", fullFontName)) else: # Register TTF font and special name filename = file.getNamedFile() pdfmetrics.registerFont(TTFont(fullFontName, filename)) # Add or replace missing styles for bold in (0, 1): for italic in (0, 1): if ("%s_%d%d" % (fontName, bold, italic)) not in self.fontList: addMapping(fontName, bold, italic, fullFontName) # Register "normal" name and the place holder for style self.registerFont(fontName, fontAlias + [fullFontName]) elif suffix in ("afm", "pfb"): if suffix == "afm": afm = file.getNamedFile() tfile = pisaFileObject(baseName + ".pfb") pfb = tfile.getNamedFile() else: pfb = file.getNamedFile() tfile = pisaFileObject(baseName + ".afm") afm = tfile.getNamedFile() # determine full font name according to weight and style fullFontName = "%s_%d%d" % (fontName, bold, italic) # check if font has already been registered if fullFontName in self.fontList: log.warn( self.warning( "Repeated font embed for %s, skip new embed", fontName)) else: # Include font face = pdfmetrics.EmbeddedType1Face(afm, pfb) fontNameOriginal = face.name pdfmetrics.registerTypeFace(face) # print fontName, fontNameOriginal, fullFontName justFont = pdfmetrics.Font(fullFontName, fontNameOriginal, encoding) pdfmetrics.registerFont(justFont) # Add or replace missing styles for bold in (0, 1): for italic in (0, 1): if ("%s_%d%d" % (fontName, bold, italic)) not in self.fontList: addMapping(fontName, bold, italic, fontNameOriginal) # Register "normal" name and the place holder for style self.registerFont( fontName, fontAlias + [fullFontName, fontNameOriginal]) else: log.warning(self.warning("wrong attributes for <pdf:font>"))
# Set these, and then **maybe** think of setting the stylesheets below # if you want finer control stdFont = 'song' stdBold = 'song' stdItalic = 'song' stdBoldItalic = 'song' stdMono = 'song' # You can embed your own fonts and use them later if you want if os.path.isfile('wrabbit/WHITRABT.TTF'): pdfmetrics.registerFont(TTFont('WhiteRabbit', 'wrabbit/WHITRABT.TTF')) addMapping('WhiteRabbit', 0, 0, 'WhiteRabbit') #normal addMapping('WhiteRabbit', 0, 1, 'WhiteRabbit') #italic addMapping('WhiteRabbit', 1, 0, 'WhiteRabbit') #bold addMapping('WhiteRabbit', 1, 1, 'WhiteRabbit') #italic and bold stdMono = 'WhiteRabbit' def getStyleSheet(): """Returns a stylesheet object""" stylesheet = StyleSheet1() stylesheet.add(ParagraphStyle(name='Normal', fontName=stdFont, bulletFontName=stdFont, fontSize=10, bulletFontSize=10, leading=12,
#DATABASES = { # 'default': { # 'ENGINE': 'django.db.backends.sqlite3', # 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), # } #} # Database # https://docs.djangoproject.com/en/1.10/ref/settings/#databases from reportlab.pdfbase import pdfmetrics from reportlab.pdfbase.ttfonts import TTFont from reportlab.lib.fonts import addMapping pdfmetrics.registerFont(TTFont('Verdana',Fonts, 'UTF-8')) addMapping('Verdana', 0, 0, 'Verdana') # Password validation # https://docs.djangoproject.com/en/1.10/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, {
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 setTTFonts(): global alreadyRegistered if not alreadyRegistered: # Import fonts from indico.extra (separate package) import indico.extra.fonts dir = os.path.split(os.path.abspath(indico.extra.fonts.__file__))[0] pdfmetrics.registerFont( TTFont('Times-Roman', os.path.join(dir, 'LiberationSerif-Regular.ttf'))) pdfmetrics.registerFont( TTFont('Times-Bold', os.path.join(dir, 'LiberationSerif-Bold.ttf'))) pdfmetrics.registerFont( TTFont('Times-Italic', os.path.join(dir, 'LiberationSerif-Italic.ttf'))) pdfmetrics.registerFont( TTFont('Times-Bold-Italic', os.path.join(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(dir, 'LiberationSans-Regular.ttf'))) pdfmetrics.registerFont( TTFont('Sans-Bold', os.path.join(dir, 'LiberationSans-Bold.ttf'))) pdfmetrics.registerFont( TTFont('Sans-Italic', os.path.join(dir, 'LiberationSans-Italic.ttf'))) pdfmetrics.registerFont( TTFont('Sans-Bold-Italic', os.path.join(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(dir, 'LiberationMono-Regular.ttf'))) pdfmetrics.registerFont( TTFont('Courier-Bold', os.path.join(dir, 'LiberationMono-Bold.ttf'))) pdfmetrics.registerFont( TTFont('Courier-Italic', os.path.join(dir, 'LiberationMono-Italic.ttf'))) pdfmetrics.registerFont( TTFont('Courier-Bold-Italic', os.path.join(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(dir, 'LinLibertine_Re-4.4.1.ttf'))) pdfmetrics.registerFont( TTFont('LinuxLibertine-Bold', os.path.join(dir, 'LinLibertine_Bd-4.1.0.ttf'))) pdfmetrics.registerFont( TTFont('LinuxLibertine-Italic', os.path.join(dir, 'LinLibertine_It-4.0.6.ttf'))) pdfmetrics.registerFont( TTFont('LinuxLibertine-Bold-Italic', os.path.join(dir, 'LinLibertine_BI-4.0.5.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(dir, 'kochi-mincho-subst.ttf'))) pdfmetrics.registerFont( TTFont('Kochi-Gothic', os.path.join(dir, 'kochi-gothic-subst.ttf'))) #pdfmetrics.registerFont(TTFont('Uming-CN', os.path.join(dir, 'uming.ttc'))) alreadyRegistered = True
def setTTFontMapping(self,face, fontname, filename, mode='all'): from reportlab.lib.fonts import addMapping from reportlab.pdfbase import pdfmetrics from reportlab.pdfbase.ttfonts import TTFont if fontname not in pdfmetrics._fonts: pdfmetrics.registerFont(TTFont(fontname, filename)) if mode == 'all': addMapping(face, 0, 0, fontname) #normal addMapping(face, 0, 1, fontname) #italic addMapping(face, 1, 0, fontname) #bold addMapping(face, 1, 1, fontname) #italic and bold elif (mode== 'normal') or (mode == 'regular'): addMapping(face, 0, 0, fontname) #normal elif mode == 'italic': addMapping(face, 0, 1, fontname) #italic elif mode == 'bold': addMapping(face, 1, 0, fontname) #bold elif mode == 'bolditalic': addMapping(face, 1, 1, fontname) #italic and bold
# minus the extension. if font[0].lower().endswith('.ttf'): # A True Type font for variant in font: location = self.findFont(variant) pdfmetrics.registerFont( TTFont(str(variant.split('.')[0]), location)) log.info('Registering font: %s from %s'%\ (str(variant.split('.')[0]),location)) self.embedded.append(str(variant.split('.')[0])) # And map them all together regular, bold, italic, bolditalic = [ variant.split('.')[0] for variant in font ] addMapping(regular, 0, 0, regular) addMapping(regular, 0, 1, italic) addMapping(regular, 1, 0, bold) addMapping(regular, 1, 1, bolditalic) else: # A Type 1 font # For type 1 fonts we require # [FontName,regular,italic,bold,bolditalic] # where each variant is a (pfbfile,afmfile) pair. # For example, for the URW palladio from TeX: # ["Palatino",("uplr8a.pfb","uplr8a.afm"), # ("uplri8a.pfb","uplri8a.afm"), # ("uplb8a.pfb","uplb8a.afm"), # ("uplbi8a.pfb","uplbi8a.afm")] faceName = font[0] regular = pdfmetrics.EmbeddedType1Face(*font[1]) italic = pdfmetrics.EmbeddedType1Face(*font[2])
enc = 'UTF-8' #repeat these for all the fonts needed pdfmetrics.registerFont(TTFont('Kinnari', 'Kinnari.ttf',enc)) pdfmetrics.registerFont(TTFont('Kinnari-Bold', 'Kinnari-Bold.ttf',enc)) pdfmetrics.registerFont(TTFont('Kinnari-Italic', 'Kinnari-Italic.ttf',enc)) pdfmetrics.registerFont(TTFont('Kinnari-BoldItalic', 'Kinnari-BoldItalic.ttf',enc)) pdfmetrics.registerFont(TTFont('THSarabun', 'THSarabun.ttf',enc)) pdfmetrics.registerFont(TTFont('THSarabun Bold', 'THSarabun Bold.ttf',enc)) pdfmetrics.registerFont(TTFont('THSarabun Italic', 'THSarabun Italic.ttf',enc)) pdfmetrics.registerFont(TTFont('THSarabun BoldItalic', 'THSarabun BoldItalic.ttf',enc)) from reportlab.lib.fonts import addMapping #repeat these for all the fonts needed addMapping('Kinnari', 0, 0, 'Kinnari') #normal addMapping('Kinnari-Bold', 1, 0, 'Kinnari-Bold') #bold addMapping('Kinnari-Italic', 0, 1, 'Kinnari-Italic') #italic addMapping('Kinnari-BoldItalic', 1, 1, 'Kinnari-BoldItalic') #italic and bold addMapping('THSarabun', 0, 0, 'THSarabun') #normal addMapping('THSarabun Bold', 1, 0, 'THSarabun Bold') #bold addMapping('THSarabun Italic', 0, 1, 'THSarabun Italic') #italic addMapping('THSarabun BoldItalic', 1, 1, 'THSarabun BoldItalic') #italic and bold #.apidoc title: RML to PDF engine # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
import copy from reportlab.pdfbase import pdfmetrics from reportlab.pdfbase.ttfonts import TTFont from reportlab.lib.styles import getSampleStyleSheet from reportlab.lib import colors from reportlab.lib import fonts from reportlab.lib.enums import TA_CENTER from reportlab.lib.pagesizes import letter from reportlab.platypus import Paragraph, SimpleDocTemplate, Table, TableStyle pdfmetrics.registerFont(TTFont('Heiti', 'STHeiti Light.ttc')) pdfmetrics.registerFont(TTFont('Heiti-Bold', 'STHeiti Medium.ttc')) fonts.addMapping('heiti', 0, 0, 'Heiti') fonts.addMapping('heiti', 1, 0, 'Heiti-Bold') heiti_font_name = fonts.tt2ps('heiti', 0, 0) heiti_font_name_b = fonts.tt2ps(heiti_font_name, 1, 0) style = copy.deepcopy(getSampleStyleSheet()['Normal']) style.fontName = heiti_font_name style.alignment = TA_CENTER style_bold = copy.deepcopy(getSampleStyleSheet()['Normal']) style_bold.fontName = heiti_font_name_b style_bold.alignment = TA_CENTER data = [ ['股票代码', '股票名称', '调研机构'], [