def __init__(self, font_path: str): pdfmetrics.registerFont( ttfonts.TTFont(Transformer.ARIAL_UNICODE, font_path)) self.style_sheet = styles.getSampleStyleSheet() self.style_sheet.add( styles.ParagraphStyle( name='BasicText', fontName=Transformer.ARIAL_UNICODE) # TODO: make configurable )
def _pdf_style_sheet(cfg): settings = cfg.registry.settings try: ffamily = _register_fonts(settings) except ttfonts.TTFError: logger.error( 'Can\'t find or register configured fonts. PDF generation will be disabled.' ) return None if ffamily == 'Times-Roman': fonts = ('Times-Roman', 'Times-Bold', 'Times-Italic', 'Times-BoldItalic') else: fonts = (ffamily, ffamily + '_b', ffamily + '_i', ffamily + '_bi') ss = styles.StyleSheet1() ss.add( styles.ParagraphStyle(name='default', fontName=fonts[0], fontSize=10, leading=12)) ss.add( styles.ParagraphStyle(name='body', parent=ss['default'], spaceBefore=6)) ss.add( styles.ParagraphStyle(name='bold', parent=ss['body'], fontName=fonts[1], alias='strong')) ss.add( styles.ParagraphStyle(name='italic', parent=ss['body'], fontName=fonts[2], alias='em')) ss.add( styles.ParagraphStyle(name='title', parent=ss['body'], fontName=fonts[1], fontSize=14)) ss.add( styles.ParagraphStyle(name='table_header', parent=ss['body'], fontName=fonts[1], alias='th')) custom_ss = make_config_dict(settings, 'netprofile.pdf_styles.') if len(custom_ss) > 0: custom_ss = as_dict(custom_ss) for name in custom_ss: pass # FIXME: write this logger.debug('Loaded preconfigured PDF fonts and styles.') return ss
def get_template(self, url): formatted_time = time.ctime() company = self.application.config['mailer.company_name'] sender = self.application.config['mailer.source_email_alias'] template_file = self.config['template_file'] story = [] click_me = saxutils.escape(self.config['link_text']) link = '<font color=blue><link href="' + url + '">' + click_me + '</link></font>' logo_path = self.config['logo'] if logo_path: img = platypus.Image(logo_path, 2 * inch, inch) story.append(img) style_sheet = styles.getSampleStyleSheet() style_sheet.add( styles.ParagraphStyle(name='Justify', alignment=TA_JUSTIFY)) ptext = '<font size=10>' + formatted_time + '</font>' story.append(platypus.Spacer(1, 12)) story.append(platypus.Paragraph(ptext, style_sheet['Normal'])) story.append(platypus.Spacer(1, 12)) with open(template_file, 'r') as file_h: for line in file_h: story.append(platypus.Paragraph(line, style_sheet['Normal'])) story.append(platypus.Spacer(1, 8)) story.append(platypus.Paragraph(link, style_sheet['Justify'])) story.append(platypus.Spacer(1, 12)) ptext = '<font size=10>Sincerely,</font>' story.append(platypus.Paragraph(ptext, style_sheet['Normal'])) story.append(platypus.Spacer(1, 12)) ptext = '<font size=10>' + sender + '</font>' story.append(platypus.Paragraph(ptext, style_sheet['Normal'])) story.append(platypus.Spacer(1, 12)) ptext = '<font size=10>' + company + '</font>' story.append(platypus.Paragraph(ptext, style_sheet['Normal'])) return story
def _draw_user(self, user): barcode_frame = platypus.Frame(x1=0, y1=0, width=user_width / 2, height=user_height, showBoundary=1) mybarcode = code128.Code128(barWidth=units.inch * 0.015, value=user.get_barcode()) mybarcode.humanReadable = 1 barcode_frame.add(mybarcode, self.canvas) name_frame = platypus.Frame(x1=user_width / 2, y1=0, width=user_width / 2, height=user_height, showBoundary=1) style = styles.ParagraphStyle(name='Normal', fontName='Helvetica', fontSize=10, leading=12, allowOrphan=1) name_paragraph = platypus.Paragraph(u'<b>%s</b>' % user.get_name(), style) name_frame.add(name_paragraph, self.canvas)
def getParagraphStyles(): """Returns a dictionary of styles based on Helvetica""" stylesheet = {} para = styles.ParagraphStyle('Normal', None) #the ancestor of all para.fontName = 'Courier' para.fontSize = 24 para.leading = 28 stylesheet['Normal'] = para para = ParagraphStyle('BodyText', stylesheet['Normal']) para.spaceBefore = 12 stylesheet['BodyText'] = para para = ParagraphStyle('BigCentered', stylesheet['Normal']) para.spaceBefore = 12 para.alignment = enums.TA_CENTER stylesheet['BigCentered'] = para para = ParagraphStyle('Italic', stylesheet['BodyText']) para.fontName = 'Courier-Oblique' stylesheet['Italic'] = para para = ParagraphStyle('Title', stylesheet['Normal']) para.fontName = 'Courier' para.fontSize = 48 para.Leading = 58 para.spaceAfter = 36 para.alignment = enums.TA_CENTER stylesheet['Title'] = para para = ParagraphStyle('Heading1', stylesheet['Normal']) para.fontName = 'Courier-Bold' para.fontSize = 36 para.leading = 44 para.spaceAfter = 36 para.alignment = enums.TA_CENTER stylesheet['Heading1'] = para para = ParagraphStyle('Heading2', stylesheet['Normal']) para.fontName = 'Courier-Bold' para.fontSize = 28 para.leading = 34 para.spaceBefore = 24 para.spaceAfter = 12 stylesheet['Heading2'] = para para = ParagraphStyle('Heading3', stylesheet['Normal']) para.fontName = 'Courier-BoldOblique' para.spaceBefore = 24 para.spaceAfter = 12 stylesheet['Heading3'] = para para = ParagraphStyle('Bullet', stylesheet['Normal']) para.firstLineIndent = -18 para.leftIndent = 72 para.spaceBefore = 6 #para.bulletFontName = 'Symbol' para.bulletFontSize = 24 para.bulletIndent = 36 stylesheet['Bullet'] = para para = ParagraphStyle('Definition', stylesheet['Normal']) #use this for definition lists para.firstLineIndent = 0 para.leftIndent = 72 para.bulletIndent = 0 para.spaceBefore = 12 para.bulletFontName = 'Couruer-BoldOblique' stylesheet['Definition'] = para para = ParagraphStyle('Code', stylesheet['Normal']) para.fontName = 'Courier' para.fontSize = 16 para.leading = 18 para.leftIndent = 36 stylesheet['Code'] = para return stylesheet
from . import flowables from . import answers from sdaps import calculate mm = units.mm stylesheet = dict(template.stylesheet) stylesheet['Head'] = styles.ParagraphStyle( 'Head', stylesheet['Normal'], fontSize=12, leading=17, backColor=colors.lightgrey, spaceBefore=5 * mm, ) stylesheet['Question'] = styles.ParagraphStyle( 'Question', stylesheet['Normal'], spaceBefore=3 * mm, fontName='Times-Bold', ) stylesheet['Text'] = styles.ParagraphStyle( 'Text', stylesheet['Normal'], spaceBefore=1 * mm,
from reportlab import platypus from reportlab.lib import styles from reportlab.lib import units from reportlab.lib import pagesizes from reportlab.lib import enums from sdaps import template mm = units.mm stylesheet = template.stylesheet stylesheet['Right'] = styles.ParagraphStyle( 'Right', parent=stylesheet['Normal'], alignment=enums.TA_RIGHT, ) class Box(platypus.Flowable): u'''3d box ''' def __init__(self, a, b, c, margin=0): platypus.Flowable.__init__(self) self.a = float(a) self.b = float(b) self.c = float(c) self.margin = float(margin) self.alpha = 1.0 / 3.0 * math.pi
from sdaps import template from sdaps import model from sdaps import image from sdaps.utils.ugettext import ugettext, ungettext _ = ugettext import flowables mm = units.mm stylesheet = dict(template.stylesheet) stylesheet['Right'] = styles.ParagraphStyle( 'Right', parent=stylesheet['Normal'], alignment=enums.TA_RIGHT, ) stylesheet['Right_Highlight'] = styles.ParagraphStyle( 'Right_Highlight', parent=stylesheet['Right'], textColor=colors.Color(255, 0, 0)) stylesheet['Normal_Highlight'] = styles.ParagraphStyle( 'Normal_Highlight', parent=stylesheet['Normal'], textColor=colors.Color(255, 0, 0)) class Choice(platypus.Flowable):
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
frames=frames, ) self.frames def beforeDrawPage(self, canvas, document): pass def afterDrawPage(self, canvas, document): pass stylesheet = dict() stylesheet['Normal'] = styles.ParagraphStyle( 'Normal', fontName='Times-Roman', fontSize=10, leading=14, ) stylesheet['Title'] = styles.ParagraphStyle( 'Title', parent=stylesheet['Normal'], fontSize=18, leading=22, alignment=styles.TA_CENTER, ) def story_title(survey, info=dict()): story = [ platypus.Paragraph(unicode(line), stylesheet['Title'])
frames=frames, ) self.frames def beforeDrawPage(self, canvas, document): pass def afterDrawPage(self, canvas, document): pass stylesheet = dict() stylesheet['Normal'] = styles.ParagraphStyle( 'Normal', fontName='HeiseiKakuGo-W5', fontSize=10, leading=14, ) stylesheet['Title'] = styles.ParagraphStyle( 'Title', parent=stylesheet['Normal'], fontSize=18, leading=22, alignment=styles.TA_CENTER, ) def story_title(survey, info=dict()): story = [ platypus.Paragraph(str(line), stylesheet['Title'])
def create_pdf(args, input_dir): # read deck data input_name = os.path.basename(input_dir) with open(os.path.join(input_dir, '{}.json'.format(input_name)), 'r') as f: deck = json.load(f) logging.info("Generating PDF") output_dir = input_dir output_name = input_name primary_hsl = args.color if args.color is not None \ else (random.random(), DEFAULT_PRIMARY_S, DEFAULT_PRIMARY_L_RANGE[0] + sum([random.random() for i in range(3)])/3.0 * (DEFAULT_PRIMARY_L_RANGE[1]-DEFAULT_PRIMARY_L_RANGE[0])) secondary_hsl = args.seccolor if args.seccolor is not None \ else desaturated( contrasting_l( adjacent_h(primary_hsl,SECONDARY_HUE_ADJACENCY), SECONDARY_LUM_CONTRAST), SECONDARY_DESATURATION) text_hsl = desaturated(contrasting_l(secondary_hsl, TEXT_LUM_CONTRAST), 1.0) pdf_config = { PdfVars.PAGE_SIZE: getattr(pagesizes, args.pagesize.upper()), PdfVars.PAGE_MARGIN: args.pagemargin * mm, PdfVars.BLEED_MARGIN: args.bleedmargin * mm, PdfVars.ROUND_CORNERS: not args.sqcorners, PdfVars.PRIMARY_HSL: primary_hsl, PdfVars.SECONDARY_HSL: secondary_hsl, PdfVars.TEXT_HSL: text_hsl, PdfVars.BACKS_TYPE: getattr(BacksType, args.backs.upper()), } # establish if portrait or landscape better pdf_config[PdfVars.PAGE_SIZE] = pagesizes.portrait( pdf_config[PdfVars.PAGE_SIZE]) pt_gridsize = grid_size(pdf_config) pdf_config[PdfVars.PAGE_SIZE] = pagesizes.landscape( pdf_config[PdfVars.PAGE_SIZE]) ls_gridsize = grid_size(pdf_config) if pt_gridsize[0] * pt_gridsize[1] > ls_gridsize[0] * ls_gridsize[1]: pdf_config[PdfVars.PAGE_SIZE] = pagesizes.portrait( pdf_config[PdfVars.PAGE_SIZE]) else: pdf_config[PdfVars.PAGE_SIZE] = pagesizes.landscape( pdf_config[PdfVars.PAGE_SIZE]) # load fonts for fontfam in FONT_FALLBACK_ORDER: for fontext in ('.ttf', '.otf'): fargs = {} for fsuff, arg in [('', 'normal'), (FONT_B_SUFFIX, 'bold'), (FONT_I_SUFFIX, 'italic'), (FONT_BI_SUFFIX, 'boldItalic')]: fname = fontfam + fsuff ffile = os.path.join(FONT_DIR, fname + fontext) if not os.path.exists(ffile): continue pdfmetrics.registerFont(ttfonts.TTFont(fname, ffile)) fargs[arg] = fname if len(fargs) > 0: pdfmetrics.registerFontFamily(fontfam, **fargs) break prefront_style = styles.ParagraphStyle( 'prefront-style', fontName=DEFAULT_FONT, fontSize=DECK_PRETITLE_SIZE, alignment=styles.TA_CENTER, textColor=colors.Color(*colors.hsl2rgb(*pdf_config[PdfVars.TEXT_HSL]))) front_style = styles.ParagraphStyle( 'front-style', fontName=DEFAULT_FONT, fontSize=DECK_TITLE_SIZE, alignment=styles.TA_CENTER, leading=DECK_TITLE_SIZE * CARD_LINE_SPACING, textColor=colors.Color(*colors.hsl2rgb(*pdf_config[PdfVars.TEXT_HSL]))) title_style = styles.ParagraphStyle( 'title-style', fontName=DEFAULT_FONT, fontSize=CARD_TITLE_SIZE, alignment=styles.TA_CENTER, textColor=colors.Color(*colors.hsl2rgb(*pdf_config[PdfVars.TEXT_HSL]))) desc_style = styles.ParagraphStyle( 'desc-style', fontName=DEFAULT_FONT, fontSize=CARD_TEXT_SIZE, leading=CARD_TEXT_SIZE * CARD_LINE_SPACING, textColor=colors.Color(*colors.hsl2rgb(*pdf_config[PdfVars.TEXT_HSL]))) creds_style = styles.ParagraphStyle( 'creds-style', fontName=DEFAULT_FONT, fontSize=CARD_TEXT_SIZE, leading=CARD_TEXT_SIZE * CARD_LINE_SPACING, alignment=styles.TA_CENTER, textColor=colors.Color(*colors.hsl2rgb(*contrasting_l( pdf_config[PdfVars.PRIMARY_HSL], TEXT_LUM_CONTRAST)))) stat_style = styles.ParagraphStyle( 'stat-style', fontName=DEFAULT_FONT, fontSize=CARD_STAT_SIZE, leading=CARD_STAT_SIZE, textColor=colors.Color(*colors.hsl2rgb(*pdf_config[PdfVars.TEXT_HSL]))) front_tbl_style = platypus.TableStyle([ ('ALIGN', (0, 0), (-1, -1), 'CENTER'), ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), ('ROWBACKGROUNDS', (0, 0), (-1, 2), [colors.hsl2rgb(*pdf_config[PdfVars.SECONDARY_HSL])]), ('TOPPADDING', (0, 0), (-1, -1), 2 * mm), ('BOTTOMPADDING', (0, 0), (-1, -1), 2 * mm), ('LEFTPADDING', (0, 0), (-1, -1), 2 * mm), ('RIGHTPADDING', (0, 0), (-1, -1), 2 * mm) ]) tbl_style = platypus.TableStyle([ ('ALIGN', (0, 0), (0, 1), 'CENTER'), ('ALIGN', (0, 3), (-1, -1), 'CENTER'), ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), ('ROWBACKGROUNDS', (0, 0), (-1, -1), [colors.hsl2rgb(*pdf_config[PdfVars.SECONDARY_HSL]), None]), ('TOPPADDING', (0, 0), (-1, -1), 0), ('BOTTOMPADDING', (0, 0), (-1, -1), 0), ('LEFTPADDING', (0, 0), (0, -2), 3 * mm), ('RIGHTPADDING', (0, 0), (0, -2), 3 * mm), ('LEFTPADDING', (0, -1), (0, -1), 0), ('RIGHTPADDING', (0, -1), (0, -1), 0) ]) stat_tbl_style = platypus.TableStyle([ ('ALIGN', (0, 0), (0, -1), 'LEFT'), ('ALIGN', (1, 0), (1, -1), 'RIGHT'), ('FONTNAME', (0, 0), (-1, -1), DEFAULT_FONT), ('FONTSIZE', (0, 0), (-1, -1), CARD_STAT_SIZE), ('ROWBACKGROUNDS', (0, 0), (-1, -1), [ colors.hsl2rgb(*lightened(pdf_config[PdfVars.SECONDARY_HSL], SECONDARY_ROW_LUM_VAR / 2)), colors.hsl2rgb(*lightened(pdf_config[PdfVars.SECONDARY_HSL], -SECONDARY_ROW_LUM_VAR / 2)) ]), ('TEXTCOLOR', (0, 0), (-1, -1), colors.hsl2rgb(*pdf_config[PdfVars.TEXT_HSL])), ('LEFTPADDING', (0, 0), (-1, -1), 2 * mm), ('RIGHTPADDING', (0, 0), (-1, -1), 2 * mm), ('TOPPADDING', (0, 0), (-1, -1), 0), ('BOTTOMPADDING', (0, 0), (-1, -1), 0), ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), ('LEADING', (0, 0), (-1, -1), CARD_STAT_SIZE) ]) canv = canvas.Canvas(os.path.join(output_dir, '{}.pdf'.format(output_name)), pagesize=pdf_config[PdfVars.PAGE_SIZE]) canv.setTitle('Trop Tumps ' + deck['name']) canv_itr = card_canv_itr(canv, pdf_config) facesize = CARD_SIZE[0] - CARD_MARGIN * 2, CARD_SIZE[1] - CARD_MARGIN * 2 # title card next(canv_itr) pretitle = platypus.Paragraph('<i>Trop Tumps</i>', prefront_style) title = platypus.Paragraph(tag_font_fallbacks(deck['name']), front_style) desc = platypus.Paragraph(tag_font_fallbacks(deck['description']), desc_style) if deck['description'] else None creds = platypus.Paragraph(DECK_CREDITS, creds_style) tbl = platypus.Table([[pretitle], [title], [desc], [creds]]) tbl.setStyle(front_tbl_style) tblsize = tbl.wrap(*facesize) tbl.wrapOn(canv, *facesize) tbl.drawOn(canv, 0, -facesize[1] * (1 - GOLDEN_RATIO) - tblsize[1] / 2) # cards for card_idx, card in enumerate(deck['cards']): next(canv_itr) title = platypus.Paragraph(tag_font_fallbacks(card['name']), title_style) img = platypus.Image(os.path.join(output_dir, card['image']), facesize[0] - 6 * mm, facesize[1] * (CARD_SECTION_PROPS[1] / sum(CARD_SECTION_PROPS)), kind='proportional') if card['image'] else None desc = platypus.Paragraph(tag_font_fallbacks(card['description']), desc_style) if card['description'] else None stattbl = platypus.Table([[ platypus.Paragraph(tag_font_fallbacks(deck['stats'][i]), stat_style), platypus.Paragraph(tag_font_fallbacks(card['stats'][i]), stat_style) ] for i in range(len(deck['stats']))], rowHeights=CARD_TEXT_SIZE * CARD_STAT_SPACING, colWidths=(None, facesize[0] / 3.0), spaceBefore=0, spaceAfter=0) stattbl.setStyle(stat_tbl_style) tbl = platypus.Table([[title], [img], [desc], [stattbl]], rowHeights=[ facesize[1] * (p / sum(CARD_SECTION_PROPS)) for p in CARD_SECTION_PROPS ]) tbl.setStyle(tbl_style) tblsize = tbl.wrap(*facesize) tbl.wrapOn(canv, *facesize) tbl.drawOn(canv, 0, -tblsize[1]) canv.setFillColorRGB(*colors.hsl2rgb(*contrasting_l( pdf_config[PdfVars.PRIMARY_HSL], TEXT_LUM_CONTRAST))) canv.setFont(DEFAULT_FONT, CARD_SMALLPRINT_SIZE) canv.drawRightString( facesize[0], -facesize[1], "{0} / {1}".format(card_idx + 1, len(deck['cards']))) halt_card_itr(canv_itr) canv.save()
def createPDF(fontSize=13): width, height = A4 #keep for later font = 'Helvetica' lineHeight = fontSize + .75 * fontSize wordSpace = 3 boarder = inch topBoarder = .75 * boarder instrSpaces = 5 chordstyle = styles.ParagraphStyle('chord') chordstyle.fontSize = fontSize hstyle = styles.ParagraphStyle('heading') hstyle.fontSize = fontSize + 1 tstyle = styles.ParagraphStyle('title') tstyle.fontSize = fontSize + 5 copyrightstyle = styles.ParagraphStyle('copyright') copyrightstyle.fontSize = 8 pattern = '\[([\w\d#/]+)\]' y = height - topBoarder - fontSize x = boarder realWidth = width - 2 * boarder c = canvas.Canvas(path + info_dict['title'] + '-' + info_dict['key'] + '.pdf', pagesize=A4) c.setFont(font, fontSize - 1) P1 = Paragraph("<u><b>" + info_dict['title'] + "</b></u>", tstyle) P1.wrap(realWidth, height) P1.drawOn(c, x, y) if info_dict.has_key('key'): P1 = Paragraph("<b>" + info_dict['key'] + "</b>", chordstyle) P1.wrap(realWidth, height) P1.drawOn( c, width - boarder - stringWidth(info_dict['key'], font, chordstyle.fontSize), y) if info_dict.has_key('bpm'): c.drawRightString(width - boarder, y - lineHeight, '%s' % info_dict['bpm']) P1 = Paragraph(info_dict['composer'], copyrightstyle) P1.wrap(realWidth, height) P1.drawOn(c, x, y - lineHeight) c.setFont(font, fontSize) y -= hstyle.fontSize + 2 * lineHeight for key in song_dict: P1 = Paragraph("<b><i>" + key + "</i></b>", hstyle) P1.wrap(realWidth, height) P1.drawOn(c, x, y) xOfLast = boarder lineCount = 0 if re.search(pattern, song_dict.get(key)[0]): y -= 1.8 * ( lineHeight ) #Abstand von Überschrift zu erster Zeile wenn Akkorde else: y -= 1.2 * ( lineHeight ) #Abstand von Überschrift zu erster Zeile wenn keine Akkorde if (key in ["Instrumental", "Intro"]): for line in song_dict.get(key): line = line.replace('[', '').replace(']', '').replace( ' ', ' ' * (instrSpaces)) P1 = Paragraph("<b>" + line + "</b>", chordstyle) P1.wrap(realWidth, height) P1.drawOn(c, x, y) y -= 1.5 * lineHeight #Abstand nach jedem Abschnitt else: for line in song_dict.get(key): if ((xOfLast + stringWidth(line, font, fontSize)) < (width - boarder)) and (lineCount < 2): x = xOfLast lineCount += 1 elif not re.search(pattern, line): y -= 1 * lineHeight else: y -= 1.5 * lineHeight lineCount = 1 line = line.decode('utf-8') last_was_chord = False x_min = 0 cursor = 0 while cursor < len(line): l = line[cursor] if l == ' ': if last_was_chord: x += last_cord_length last_was_chord = False else: x += wordSpace elif l == '[': end = line.find(']', cursor) chord = line[cursor + 1:end] P1 = Paragraph("<b>" + chord + "</b>", chordstyle) P1.wrap(realWidth, height) if x < x_min: x = x_min P1.drawOn(c, x, y + fontSize + 0.01 * fontSize**2) cursor = end last_was_chord = True last_cord_length = stringWidth( chord, font, fontSize) x_min = x + last_cord_length + wordSpace * 7 else: last_was_chord = False c.drawString(x, y, l) x += stringWidth(l, font, fontSize) cursor += 1 xOfLast = x + wordSpace x = boarder y -= 1.5 * lineHeight #Abstand nach jedem Abschnitt P1 = Paragraph( ('© ') + info_dict['copyright'] + '<br/>Gebrauch nur zur Nutzung im Rahmen von Veranstaltungen der City Chapel Stuttgart', copyrightstyle) P1.wrap(realWidth, height) P1.drawOn(c, x, boarder - P1.height) # + lineHeight) c.showPage() c.save() return (y < boarder)
class Pdf(object): PARAGRAPH_STYLE = styles.ParagraphStyle("default", fontSize=12, leading=13) def __init__(self, filename): frame = platypus.Frame(20 * mm, 20 * mm, 170 * mm, 227 * mm, showBoundary=0, topPadding=0, bottomPadding=0, leftPadding=0, rightPadding=0) page = platypus.PageTemplate("main", frames=[frame], onPage=self._decorate_page) self.doc = platypus.BaseDocTemplate(filename, pageTemplates=[page]) self.story = [] self.address = None def _decorate_page(self, canvas, document): text = canvas.beginText(20 * mm, 277 * mm) for line in self.address: text.textLine(line) canvas.drawText(text) def set_store_address(self, address_lines): self.address = address_lines def add_table(self, rows, column_sizes, style=[]): real_style = platypus.TableStyle([ ("GRID", (0, 0), (-1, -1), 0.8, (0, 0, 0)), ("BACKGROUND", (0, 0), (-1, 0), (0.8471, 0.8941, 0.7373)), ] + style) sizes = [s * mm for s in column_sizes] self.story.extend([ platypus.Spacer(1, 3 * mm), platypus.Table(rows, colWidths=sizes, style=real_style), platypus.Spacer(1, 3 * mm), ]) @staticmethod def _find_min_max(data): _min, _max = data[0][0], data[0][0] for d in data: tmp_min = min(d) tmp_max = max(d) _min = _min if _min < tmp_min else tmp_min _max = _max if _max > tmp_max else tmp_max return _min, _max def add_line_chart(self, width, height, labels, data, minv=None, maxv=None): pad = 10 _min, _max = self._find_min_max(data) minv = _min if minv is None else minv maxv = _max if maxv is None else maxv lc = HorizontalLineChart() lc.x = pad * mm lc.y = pad * mm lc.width = (width - 2 * pad) * mm lc.height = (height - 2 * pad) * mm lc.categoryAxis.categoryNames = labels lc.data = data lc.valueAxis.valueMin = minv lc.valueAxis.valueMax = maxv lc.joinedLines = 1 lc.categoryAxis.labels.boxAnchor = "n" lc.lines.strokeWidth = 2 drawing = Drawing(width * mm, height * mm) drawing.hAlign = "CENTER" drawing.add(lc) self.story.append(drawing) def add_pie_chart(self, width, height, labels, data, side_labels=False): pad = 15 pc = Pie() pc.x = pad * mm pc.y = pad * mm pc.width = (width - 2 * pad) * mm pc.height = (height - 2 * pad) * mm pc.labels = labels pc.data = data pc.sideLabels = side_labels drawing = Drawing(width * mm, height * mm) drawing.hAlign = "CENTER" drawing.add(pc) self.story.append(drawing) def add_bar_chart(self, width, height, labels, data, minv=None, maxv=None): pad = 10 _min, _max = self._find_min_max(data) minv = _min if minv is None else minv maxv = _max if maxv is None else maxv bc = VerticalBarChart() bc.x = pad * mm bc.y = pad * mm bc.width = (width - 2 * pad) * mm bc.height = (height - 2 * pad) * mm bc.categoryAxis.categoryNames = labels bc.data = data bc.valueAxis.valueMin = minv bc.valueAxis.valueMax = maxv drawing = Drawing(width * mm, height * mm) drawing.hAlign = "CENTER" drawing.add(bc) self.story.append(drawing) def add_paragraph(self, text): self.story.append(platypus.Paragraph(text, self.PARAGRAPH_STYLE)) def new_page(self): self.story.append(platypus.PageBreak()) def save(self): assert self.address is not None, \ "Use #set_store_address to set address" self.doc.build(self.story)
from django.http import HttpResponse from django.shortcuts import render from reportlab.pdfgen import canvas from reportlab.lib.pagesizes import landscape, A4 from reportlab.platypus import Table, SimpleDocTemplate, TableStyle, PageBreak, Paragraph, Spacer from reportlab.lib import colors, styles from main.models import Pool, Stage, Entry headerStyle = styles.ParagraphStyle('header', fontSize=15, alignment=styles.TA_CENTER) def pools(request, stage: Stage): context = {} pool_list = [] for p in stage.poolstage_set.first().pool_set.order_by('number').all(): pool_list.append(gen_pool_data(p)[1:]) context['pools'] = pool_list return render(request, 'main/pool/pools_filled.html', context) def pools_pdf(request, stage: Stage): """Generates a PDF with one pool sheet to every page""" response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="{}-{}.pdf"'.format(stage.competition.name, stage.number) p = SimpleDocTemplate(response, pagesize=landscape(A4)) basestyle = [('ALIGN', (0, 0), (-1, -1), 'CENTER'), ('INNERGRID', (0, 0), (-1, -1), 0.5, colors.black),
from sdaps import template from sdaps import model from sdaps import image from sdaps.utils.ugettext import ugettext, ungettext _ = ugettext from . import flowables mm = units.mm stylesheet = dict(template.stylesheet) stylesheet['Right'] = styles.ParagraphStyle( 'Right', parent=stylesheet['Normal'], alignment=enums.TA_RIGHT, fontName='HeiseiKakuGo-W5', ) stylesheet['Right_Highlight'] = styles.ParagraphStyle( 'Right_Highlight', parent=stylesheet['Right'], textColor=colors.Color(255, 0, 0), fontName='HeiseiKakuGo-W5', ) stylesheet['Normal_Highlight'] = styles.ParagraphStyle( 'Normal_Highlight', parent=stylesheet['Normal'], textColor=colors.Color(255, 0, 0), fontName='HeiseiKakuGo-W5')