def setUp(self): self.vera = TTFont("Vera", "Vera.ttf") pdfmetrics.registerFont(self.vera) self.styNormal = ParagraphStyle(name='Helvetica', fontName='Helvetica-Oblique') self.styTrueType = ParagraphStyle(name='TrueType', fontName='Vera')
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>"))
import os from reportlab.pdfbase import pdfmetrics from reportlab.pdfbase.ttfonts import TTFont from reportlab.lib import colors from reportlab.lib.styles import ParagraphStyle from reportlab.lib.units import cm from reportlab.lib.enums import TA_JUSTIFY, TA_LEFT, TA_RIGHT, TA_CENTER assetsDir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "assets") arimoDir = os.path.join(assetsDir, "Arimo") # Choosing font pdfmetrics.registerFont( TTFont('Symbols', os.path.join(assetsDir, "FontAwesome.ttf"))) pdfmetrics.registerFont( TTFont('Arimo', os.path.join(arimoDir, "Arimo-Regular.ttf"))) pdfmetrics.registerFont( TTFont('ArimoBold', os.path.join(arimoDir, "Arimo-Bold.ttf"))) pdfmetrics.registerFont( TTFont('ArimoItalic', os.path.join(arimoDir, "Arimo-Italic.ttf"))) pdfmetrics.registerFont( TTFont('ArimoBoldItalic', os.path.join(arimoDir, "Arimo-BoldItalic.ttf"))) pdfmetrics.registerFontFamily("Arimo", normal="Arimo", bold="ArimoBold", italic="ArimoItalic", boldItalic="ArimoBoldItalic") styles = {} # margins
#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)
from cgi import escape as escape_html from reportlab.lib.units import inch from reportlab.lib.styles import TA_CENTER, ParagraphStyle from reportlab.platypus import Paragraph, Frame from pdfrw import PdfReader from pdfrw.buildxobj import pagexobj from pdfrw.toreportlab import makerl from reportlab.pdfbase import pdfmetrics from reportlab.pdfbase.ttfonts import TTFont from .conf import settings pdfmetrics.registerFont(TTFont(*settings.ARTSHOW_BARCODE_FONT)) default_style = ParagraphStyle("default", fontName="Helvetica", fontSize=18, leading=18, alignment=TA_CENTER, allowWidows=0, allowOrphans=0) def squeeze_text_into_box(canvas, text, x0, y0, x1, y1, units=inch, style=default_style,
def exportPDF(request, slug): '''Exports recipes to a pdf''' pdfmetrics.registerFont(TTFont('Vera', 'Vera.ttf')) pdfmetrics.registerFont(TTFont('VeraBd', 'VeraBd.ttf')) pdfmetrics.registerFont(TTFont('VeraIt', 'VeraIt.ttf')) pdfmetrics.registerFont(TTFont('VeraBI', 'VeraBI.ttf')) registerFontFamily('Vera', normal='Vera', bold='VeraBd', italic='VeraIt', boldItalic='VeraBI') recipe = get_object_or_404(Recipe, slug=slug) # Create the HttpResponse object with the appropriate PDF headers. response = HttpResponse(mimetype='application/pdf') response[ 'Content-Disposition'] = 'attachment; filename=' + recipe.slug + '.pdf' # Our container for 'Flowable' objects elements = [] #set up our styles styles = getSampleStyleSheet() styleH1 = styles['Heading1'] styleH1.textColor = colors.green styleH1.fontName = 'VeraBd' styleH2 = styles['Heading2'] styleH2.textColor = colors.goldenrod styleH2.fontName = 'Vera' styleNormal = styles['Normal'] styleNormal.fontName = 'Vera' styleBullet = styles['Bullet'] styleBullet.fontName = 'VeraIt' #create the pdf doc doc = SimpleDocTemplate(response) #set the openeats logo logo = settings.MEDIA_ROOT + "/" + settings.OELOGO I = Image(logo) I.hAlign = 'LEFT' elements.append(I) elements.append(Spacer(0, 1 * cm)) #add the recipe photo if the recipe has one if recipe.photo: photo = settings.BASE_PATH + recipe.thumbnail_image.url I = Image(photo) I.height = "CENTER" elements.append(I) elements.append(Spacer(0, 0.5 * cm)) # add the meat of the pdf elements.append(Paragraph(recipe.title, styleH1)) elements.append(Paragraph('info', styleH2)) elements.append(Paragraph(recipe.info, styleNormal)) elements.append(Paragraph('ingredients', styleH2)) for ing in recipe.ingredients.all(): ing = "%s %s %s %s" % (ing.quantity, ing.measurement, ing.title, ing.preparation) elements.append(Paragraph(ing, styleBullet)) elements.append(Paragraph('directions', styleH2)) elements.append(Paragraph(recipe.directions, styleNormal)) #build the pdf and return it doc.build(elements) return response
longitude = float(form.getvalue("long")) zone = int(form.getvalue("zone")) name = form.getvalue("name") time = form.getvalue("time") page_width = 21.0 * cm page_height = 29.7 * cm dial_size = 21 * cm response = HttpResponse(content_type='application/pdf') response[ 'Content-Disposition'] = 'inline; name=sundial; filename=sundial.pdf' canv = canvas.Canvas(response) canv.setPageSize((page_width, page_height)) pdfmetrics.registerFont(TTFont("Arial", "../sundial/res/arial.ttf")) canv.setFont("Arial", 17) canv.setTitle("Sundial") lat_string = str(abs(latitude)) + ("N" if (latitude > 0) else "S") long_string = str(abs(longitude)) + ("E" if (latitude > 0) else "W") gmt_string = "GMT" + ("+" if (latitude > 0) else "-") + str(abs(zone)) time_string = time + " time" title_string = "Horizontal Sundial, " + lat_string + ", " + long_string + ", " + gmt_string + ", " + time_string canv.drawString( page_width / 2.0 - stringWidth(title_string, "Arial", 17) / 2.0, page_height - 1 * cm, title_string) sundial = draw_sundial(math.radians(latitude), math.radians(longitude),
def PDFmerge(pdfs, output): # creating pdf file merger object pdfMerger = PyPDF2.PdfFileMerger() # appending pdfs one by one for pdf in pdfs: with open(pdf, 'rb') as f: pdfMerger.append(f) # writing combined pdf to output pdf file with open(output, 'wb') as f: pdfMerger.write(f) pdfmetrics.registerFont(TTFont('Round', 'RoundhandBT.ttf')) packet = StringIO.StringIO() # create a new PDF with Reportlab can = canvas.Canvas(packet, pagesize=letter) can.setFont('Round', 32) can.drawString(200, 510, "Name") can.drawString(225, 438, "Event") can.save() #move to the beginning of the StringIO buffer packet.seek(0) new_pdf = PdfFileReader(packet) # read your existing PDF existing_pdf = PdfFileReader(file("1.pdf", "rb"))
from PyPDF2 import PdfFileWriter, PdfFileReader import io from reportlab.pdfgen import canvas from reportlab.pdfbase import pdfmetrics from reportlab.pdfbase.ttfonts import TTFont pdfmetrics.registerFont(TTFont('Roboto', 'Roboto-Regular.ttf')) pdfmetrics.registerFont(TTFont('Robotomono', 'RobotoMono-Medium.ttf')) packet = io.BytesIO() # create a new PDF with Reportlab def creatpdf(name, event): mid = 559 end = 841 size = 13 can = canvas.Canvas(packet) namesize = (len(name) / 2) * size can.setFont('Roboto', 20) can.drawString(mid - namesize, 300, name) can.setFont('Roboto', 20) can.drawString(245, 210, event) can.save() # move to the beginning of the StringIO buffer packet.seek(0) new_pdf = PdfFileReader(packet) # read your existing PDF existing_pdf = PdfFileReader(open("document.pdf", "rb"))
def add_ingredients_to_recipe(recipe, ingredients): Recipe.ingredients.through.objects.bulk_create([ Recipe.ingredients.through( recipe=recipe, ingredient=get_object_or_404( Ingredient, title=ingredient["title"], ), quantity=ingredient["quantity"], ) for ingredient in ingredients ], ) pdfmetrics.registerFont( TTFont( "GOST_Common", os.path.join("font/GOST_Common.ttf"), )) def generate_pdf(user): buffer = io.BytesIO() canvas = Canvas(buffer, bottomup=0) title = "Список покупок" canvas.setTitle(title) canvas.setFont(FONT, FONT_SIZE) canvas.drawString(X_COORDINATE, Y_COORDINATE_TITLE, title) canvas.setFont(FONT, FONT_SIZE) canvas.drawString(X_COORDINATE, Y_COORDINATE_TITLE + SIZE_DOWN_TITLE,
def get_canvas_data(selection: str, sb_or_count: str, page_num: int, ini_object) -> BytesIO: # SB rect info sb_rect_props = ini_object.get_sb_rect_props() # Ins rect info ins_rect_props = ini_object.get_ins_rect_props() # sb info sb_props = ini_object.get_sb_props() # instruction info instruction_props = ini_object.get_instruction_props() # Read SB RECT sb_rect_start_x = float(sb_rect_props['x']) sb_rect_start_y = float(sb_rect_props['y']) sb_rect_width = float(sb_rect_props['width']) sb_rect_height = float(sb_rect_props['height']) # Read SB RECT ins_rect_start_x = float(ins_rect_props['x']) ins_rect_start_y = float(ins_rect_props['y']) ins_rect_width = float(ins_rect_props['width']) ins_rect_height = float(ins_rect_props['height']) # Read SB sb_start_x = float(sb_props["x"]) sb_start_y = float(sb_props["y"]) sb_font_size = int(sb_props["font_size"]) # Read Instruction ins_start_x = float(instruction_props["x"]) ins_start_y = float(instruction_props["y"]) ins_font_size = int(instruction_props["font_size"]) # Draw String font_name = "IPA Gothic" font_path = u'C:/Windows/Fonts/msgothic.ttc' pdfmetrics.registerFont(TTFont(font_name, font_path)) # SB or Instruction usage if selection == '1': # Create a new PDF with reportlab data = BytesIO() can = canvas.Canvas(data, pagesize=A4) # String for print string = u"管理番号:{} P.{}".format( sb_or_count, page_num) # Set SB RECT rect_start_x = sb_rect_start_x * mm rect_start_y = sb_rect_start_y * mm rect_width = sb_rect_width * mm rect_height = sb_rect_height * mm # Draw a rectangle can.setFillColor(white) can.rect(rect_start_x, rect_start_y, rect_width, rect_height, fill=True, stroke=False) # Draw String can.setFillColor(black) can.setFont(font_name, sb_font_size) can.drawString(sb_start_x * mm, sb_start_y * mm, string) can.showPage() can.save() data.seek(0) return data elif selection == '2': # Create a new PDF with reportlab data = BytesIO() can = canvas.Canvas(data, pagesize=landscape(A3)) # String for print string = u"別紙({}/{})".format(page_num, sb_or_count) # Set SB RECT rect_start_x = ins_rect_start_x * mm rect_start_y = ins_rect_start_y * mm rect_width = ins_rect_width * mm rect_height = ins_rect_height * mm # Draw a rectangle can.setFillColor(white) can.rect(rect_start_x, rect_start_y, rect_width, rect_height, fill=True, stroke=False) # Draw String can.setFillColor(black) can.setFont(font_name, ins_font_size) can.drawString(ins_start_x * mm, ins_start_y * mm, string) can.showPage() can.save() data.seek(0) return data else: pass
def generate_pdf(self): path = os.getcwd() + "\\User_Files\\Reports\\Results\\" path = r"{}".format(path) pdfmetrics.registerFont( TTFont('polishFont', 'Bookmarks\\AbhayaLibre-Regular.ttf')) styles = getSampleStyleSheet() styles.add( ParagraphStyle(name='RegularDownloaded', alignment=TA_JUSTIFY, fontName='polishFont', fontSize=12, borderWidth=0.5)) styles.add( ParagraphStyle(name='CategoryName', alignment=TA_CENTER, fontName='polishFont', fontSize=17, borderWidth=3)) pdf = SimpleDocTemplate(path + self.category_name + ".pdf", pagesize=letter, rightMargin=72, leftMargin=72, topMargin=72, bottomMargin=18) body = [ Paragraph('<b> %s </b>' % ('Kategoria: ' + self.category_name), styles["CategoryName"]), Spacer(1, 20) ] data = [["Nr.", "Imię i nazwisko", "Klub", "Numer licencji"]] for idx, competitor in enumerate(self.competitors): if idx in [2, 3]: idx = 2 elif idx in [4, 5]: idx = 4 elif idx in [6, 7]: idx = 6 elif idx in [8, 9]: idx = 8 elif idx in [8, 9]: idx = 10 elif idx in [10, 11]: idx = 12 elif idx in [12, 13]: idx = 14 data.append([ str(idx + 1), competitor.get_first_name() + " " + competitor.get_surname(), competitor.get_club(), competitor.get_licence_no() ]) t = Table(data) t.setStyle( TableStyle([('GRID', (0, 0), (-1, -1), 0.5, colors.black), ('FONT', (0, 0), (-1, -1), 'polishFont'), ('BACKGROUND', (0, 1), (3, 1), colors.gold), ('BACKGROUND', (0, 2), (3, 2), colors.lightgrey), ('BACKGROUND', (0, 3), (3, 4), colors.Color(red=(179.0 / 255), green=(140.0 / 255), blue=(82.0 / 255)))])) body.append(t) pdf.build(body)
y, width=draw_width, height=draw_height, preserveAspectRatio=False) # c=canvas.Canvas("vishal.pdf",letter) # fill_page_with_image(0,0,432,842,"frame1.png",c) # fill_page_with_image(432,0,595-410,842,"frame2.jpg",c) #opening my json file data for some use with open("./extras/resumeStructure.json") as json_data: resume_data = json.load(json_data) # registering inconsolata font which is used in making font in resume pdf registerFont(TTFont('Inconsolata', 'fonts/Inconsolata-Regular.ttf')) registerFont(TTFont('InconsolataBold', 'fonts/Inconsolata-Bold.ttf')) registerFontFamily('Inconsolata', normal='Inconsolata', bold='InconsolataBold') #raw data data = { 'objective': ' '.join([ 'Seeking co-operative employment', 'in the field of software development,', 'preferably working in python and web backend infrastructure or distributed computing, ', 'to start June 2016.' ]), 'summary': ' '.join([ 'I love to use programming to solve interesting problems.', 'I love working in Python (which is why I generated this resume in Python using ReportLab), but I am comfortable working in a variety of languages.',
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
else: qmean = math.floor(qmean) # Insert commas every three digits qmean = "{:,}".format(qmean) # Load the answer # Convert the PNG image to a Reportlab Flowable object im = PIL.Image.open(filename) buf = BytesIO() im.save(buf, 'PNG') im = Image(buf) # Draw the PDF canvas using the Arial font in Slalom blue c = canvas.Canvas("question-%02d.pdf" % i, pagesize=(pagex, pagey)) pdfmetrics.registerFont(TTFont('Arial', 'Arial.ttf')) pdfmetrics.registerFont(TTFont('Arial Bold', 'Arial Bold.ttf')) # Draw the titles # The way Reportlabs processes RGB values is so strange... The value must # be between 0 and 1, so just take your RGB values and multiply them each # by (1/255). c.setFillColorRGB(0.17647059, 0.44705882, 0.75686275) c.setFont('Arial', 58) c.drawCentredString(pagex / 2.0, pagey - 100, qna[str(i)]['q']) c.drawCentredString((pagex / 8.0 * 6), (pagey / 8.0) * 5 + 60, "Wisdom of the Crowd") c.drawCentredString((pagex / 8.0 * 6), (pagey / 8.0) * 3 + 25, "Actual Answer") # Draw the numbers
import common from common.reportlab_styles import extend_style, extend_table_style from reportlab.lib.enums import TA_LEFT, TA_CENTER, TA_RIGHT from reportlab.lib.fonts import ps2tt from reportlab.lib.styles import ParagraphStyle from reportlab.pdfbase.pdfmetrics import registerFont, registerFontFamily from reportlab.pdfbase.ttfonts import TTFont from reportlab.platypus import TableStyle import os FONT_DIR = os.path.join(os.path.dirname(common.__file__), "fonts") try: ps2tt("LiberationSans") except ValueError: registerFont(TTFont("LiberationSans", os.path.join(FONT_DIR, "LiberationSans-Regular.ttf"))) registerFont(TTFont("LiberationSans-Bold", os.path.join(FONT_DIR, "LiberationSans-Bold.ttf"))) registerFont(TTFont("LiberationSans-Italic", os.path.join(FONT_DIR, "LiberationSans-Italic.ttf"))) registerFont(TTFont("LiberationSans-BoldItalic", os.path.join(FONT_DIR, "LiberationSans-BoldItalic.ttf"))) registerFontFamily( "LiberationSans", normal="LiberationSans", bold="LiberationSans-Bold", italic="LiberationSans-Italic", boldItalic="LiberationSans-BoldItalic", ) try: ps2tt("LiberationSansNarrow") except ValueError: registerFont(TTFont("LiberationSansNarrow", os.path.join(FONT_DIR, "LiberationSansNarrow-Regular.ttf")))
from reportlab.lib.units import inch from reportlab.pdfgen.canvas import Canvas from reportlab.pdfbase import pdfmetrics from reportlab.pdfbase.cidfonts import UnicodeCIDFont pdfmetrics.registerFont(UnicodeCIDFont('STSong-Light')) from reportlab.pdfbase.ttfonts import TTFont pdfmetrics.registerFont(TTFont('hei', 'SIMHEI.TTF')) from reportlab.lib.styles import getSampleStyleSheet from reportlab.lib import colors from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Image, Table, TableStyle import time elements = [] # TableStyle Commands # BACKGROUND, and TEXTCOLOR commands data = [['00', '01', '02', '03', '07'], ['10', '11', '12', '13', '14'], ['20', '21', '22', '23', '24'], ['30', '31', '32', '33', '34']] t = Table(data, colWidths=[100, 100, 100, 100, 100]) t.setStyle( TableStyle([('BACKGROUND', (1, 1), (-1, -1), colors.green), ('TEXTCOLOR', (0, 0), (1, -1), colors.red)])) elements.append(t) data = [['00', '01', '02', '03', '04'], ['10', '11', '12', '13', '14'], ['20', '21', '22', '23', '24'], ['30', '31', '32', '33', '34']] t = Table(data, colWidths=[100, 100, 100, 100, 100],
def reporteador(self, obj_move): import sys reload(sys) sys.setdefaultencoding('iso-8859-1') pdfmetrics.registerFont(TTFont('Calibri', 'Calibri.ttf')) pdfmetrics.registerFont(TTFont('Calibri-Bold', 'CalibriBold.ttf')) width, height = A4 # 595 , 842 wReal = width - 30 hReal = height - 40 direccion = self.env['main.parameter'].search([])[0].dir_create_file c = canvas.Canvas(direccion + "AsientoContable.pdf", pagesize=A4) inicio = 0 pos_inicial = hReal - 83 libro = None voucher = None total = 0 debeTotal = 0 haberTotal = 0 pagina = 1 textPos = 0 self.cabezera(c, wReal, hReal, obj_move, 1) posicion_indice = 1 for i in obj_move.line_ids: c.setFont("Calibri", 8) pagina, pos_inicial = self.verify_linea(c, wReal, hReal, pos_inicial, 12, pagina, 1, obj_move) c.drawString(10, pos_inicial, str(posicion_indice)) c.drawString(22, pos_inicial, self.particionar_text(i.name, 70)) c.drawString( 102, pos_inicial, self.particionar_text( i.partner_id.name if i.partner_id.id else '', 100)) c.drawString( 222, pos_inicial, self.particionar_text( i.nro_comprobante if i.nro_comprobante else '', 70)) c.drawString( 302, pos_inicial, self.particionar_text( (i.account_id.code + ' - ' + i.account_id.name) if i.account_id.id else '', 75)) c.drawString( 392, pos_inicial, self.particionar_text( i.date_maturity if i.date_maturity else '', 40)) c.drawRightString( 498, pos_inicial, '{:,.2f}'.format(decimal.Decimal("%0.2f" % i.debit))) c.drawRightString( 558, pos_inicial, '{:,.2f}'.format(decimal.Decimal("%0.2f" % i.credit))) c.drawString( 562, pos_inicial, self.particionar_text( i.type_document_it.code if i.type_document_it.id else '', 20)) c.line(20, pos_inicial - 2, 585, pos_inicial - 2) tamanios_x = [80, 120, 80, 90, 50, 60, 60, 25] acum_tx = 20 for i in tamanios_x: c.line(acum_tx, pos_inicial - 2, acum_tx, pos_inicial + 12) acum_tx += i c.line(acum_tx, pos_inicial - 2, acum_tx, pos_inicial + 12) posicion_indice += 1 posicion_indice = 1 pagina, pos_inicial = self.verify_linea(c, wReal, hReal, pos_inicial, 36, pagina, 2, obj_move) style = getSampleStyleSheet()["Normal"] style.leading = 8 style.alignment = 1 paragraph1 = Paragraph("<font size=8><b>Nombre</b></font>", style) paragraph2 = Paragraph("<font size=8><b>Empresa</b></font>", style) paragraph3 = Paragraph("<font size=8><b>Comprobante</b></font>", style) paragraph4 = Paragraph("<font size=8><b>Cuenta</b></font>", style) paragraph5 = Paragraph("<font size=8><b>Fecha V.</b></font>", style) paragraph6 = Paragraph("<font size=8><b>Debe</b></font>", style) paragraph7 = Paragraph("<font size=8><b>Haber</b></font>", style) paragraph8 = Paragraph("<font size=8><b>Cta. Analítica</b></font>", style) paragraph9 = Paragraph("<font size=8><b>Importe Divisa</b></font>", style) paragraph10 = Paragraph("<font size=8><b>Divisa</b></font>", style) paragraph11 = Paragraph("<font size=8><b>TC SUNAT</b></font>", style) paragraph12 = Paragraph("<font size=8><b>TD</b></font>", style) data = [[paragraph8, paragraph9, paragraph10, paragraph11]] t = Table(data, colWidths=(100, 100, 50, 60), rowHeights=(9)) t.setStyle( TableStyle([('GRID', (0, 0), (-1, -1), 1, colors.black), ('ALIGN', (0, 0), (-1, -1), 'LEFT'), ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), ('TEXTFONT', (0, 0), (-1, -1), 'Calibri-Bold'), ('FONTSIZE', (0, 0), (-1, -1), 4), ('BACKGROUND', (0, 0), (-1, -1), colors.gray)])) t.wrapOn(c, 20, pos_inicial) t.drawOn(c, 20, pos_inicial) for i in obj_move.line_ids: c.setFont("Calibri", 8) pagina, pos_inicial = self.verify_linea(c, wReal, hReal, pos_inicial, 12, pagina, 2, obj_move) c.drawString(10, pos_inicial, str(posicion_indice)) c.drawString( 22, pos_inicial, self.particionar_text( i.analytic_account_id.name if i.analytic_account_id.id else '', 43)) c.drawRightString( 218, pos_inicial, '{:,.2f}'.format(decimal.Decimal("%0.2f" % i.amount_currency))) c.drawString( 222, pos_inicial, self.particionar_text( i.currency_id.name if i.currency_id.id else '', 24)) c.drawRightString(328, pos_inicial, "%0.3f" % i.tc) c.line(20, pos_inicial - 2, 330, pos_inicial - 2) tamanios_x = [100, 100, 50, 60] acum_tx = 20 for i in tamanios_x: c.line(acum_tx, pos_inicial - 2, acum_tx, pos_inicial + 12) acum_tx += i c.line(acum_tx, pos_inicial - 2, acum_tx, pos_inicial + 12) posicion_indice += 1 pagina, pos_inicial = self.verify_linea(c, wReal, hReal, pos_inicial, 24, pagina, 2, obj_move) c.drawString(10, pos_inicial, 'HECHO POR:') c.drawString( 60, pos_inicial, obj_move.create_uid.name if obj_move.create_uid.id else self.env.uid.name) pagina, pos_inicial = self.verify_linea(c, wReal, hReal, pos_inicial, 50, pagina, 3, obj_move) c.line(125 - 47, pos_inicial + 10, 125 + 47, pos_inicial + 10) c.line(290 - 47, pos_inicial + 10, 290 + 47, pos_inicial + 10) c.line(165 + 290 - 47, pos_inicial + 10, 165 + 290 + 47, pos_inicial + 10) c.drawCentredString(125, pos_inicial, 'HECHO POR:') c.drawCentredString(165 + 290, pos_inicial, 'REVISADO:') c.drawCentredString(290, pos_inicial, 'APROBADO:') c.save()
from reportlab.pdfbase.ttfonts import TTFont from google.appengine.api import mail #python /home/cameron/Desktop/GAE/google_appengine/dev_appserver.py /home/cameron/Projects/'Google App Engine'/helloworld/ def sendmail(sender, recipient, certified): mail.send_mail( sender=sender, to=recipient, subject='Belladonna Certification', body='A new certificate has been purchased and awarded to ' + certified + '.') pdfmetrics.registerFont(TTFont('Tangerine_Bold', 'Tangerine_Bold.ttf')) pdfmetrics.registerFont(TTFont('VeraBd', 'VeraBd.ttf')) template_dir = os.path.join(os.path.dirname(__file__), 'templates') jinja_env = jinja2.Environment(loader=jinja2.FileSystemLoader(template_dir), autoescape=True) # name = 'Cameron Sima' date = strftime("%m-%d-%Y-%H-%M") print date.split('-')[2] dates = { '01': 'first', '02': 'second', '03': 'third', '04': 'fourth',
def generate_envelopes(cls, qs): # Define envelope size C5_envelope = (22.9 * cm, 16.2 * cm) error_count = 0 # Font registration and settings reportlab.rl_config.warnOnMissingFontGlyphs = 0 pdfmetrics.registerFont( TTFont('DejaVu', '/usr/share/fonts/truetype/ttf-dejavu/DejaVuSerif.ttf')) pdfmetrics.registerFont( TTFont( 'DejaVuBold', '/usr/share/fonts/truetype/ttf-dejavu/DejaVuSerif-Bold.ttf')) pdfmetrics.registerFont( TTFont( 'DejaVuItalic', '/usr/share/fonts/truetype/ttf-dejavu/DejaVuSerif-Italic.ttf')) pdfmetrics.registerFont( TTFont( 'DejaVuBoldItalic', '/usr/share/fonts/truetype/ttf-dejavu/DejaVuSerif-BoldItalic.ttf' )) registerFontFamily('DejaVu', normal='DejaVu', bold='DejaVuBold', italic='DejaVuItalic', boldItalic='DejaVuBoldItalic') # The Story is commonly used in flowing reportlab documents to contain all flowables Story = [] buff = BytesIO() document_settings = { "rightMargin": 1 * cm, "leftMargin": 12 * cm, "topMargin": 9 * cm, "bottomMargin": 1.5 * cm, "pagesize": C5_envelope } doc = SimpleDocTemplate(buff, **document_settings) styles = getSampleStyleSheet() styles.add( ParagraphStyle(name='Justify', fontName="DejaVu", alignment=TA_JUSTIFY, leading=0.65 * cm)) styles["Normal"].fontName = "DejaVu" styles["Normal"].leading = 0.5 * cm qs = list(qs) camp_params = dict( eveniment=qs[0].eveniment, nume="Plic C5 export stats", slug="plic_c5_export_stats", tip_camp="text", ) camp, _ = CampArbitrarParticipareEveniment.objects.get_or_create( **camp_params) error_count = 0 record = {} for participare in qs: if participare.membru: destinatar = u"%s" % participare.membru elif participare.nonmembru: destinatar = participare.nonmembru.get_full_name() adresa_postala = participare.membru.adresa_postala if participare.membru else participare.nonmembru.adresa_postala adresa_internationala = False # verifica adresa internationala if participare.membru: adresa = participare.membru.get_contact( u"Adresa corespondență", just_value=False) adresa = adresa.first() if adresa.informatii_suplimentare and any( i in adresa.informatii_suplimentare for i in ["adresa internationala", u"adresă internațională"]): adresa_internationala = True try: adresa = AdresaPostala.parse_address(adresa_postala, fail_silently=False) except Exception as e: if not adresa_internationala: logger.error(u"%s: %s (%s)" % (cls.__name__, e, traceback.format_exc())) record[destinatar] = u"Adresă rea (%s)" % e error_count += 1 else: record[destinatar] = u"OK, international" participare.add_to_custom_field(camp.slug, record[destinatar]) continue try: if not adresa.are_cod(): adresa.determine_cod() except Exception as e: logger.error("%s: %s (%s)" % (cls.__name__, e, traceback.format_exc())) error_count += 1 record[destinatar] = u"Eroare la Cod Poștal (%s)" % e participare.add_to_custom_field(camp.slug, record[destinatar]) continue if not adresa.are_cod(): error_count += 1 record[destinatar] = u"Codul Poștal nu a putut fi determinat" participare.add_to_custom_field(camp.slug, record[destinatar]) continue record[destinatar] = u"OK" participare.add_to_custom_field(camp.slug, record[destinatar]) cod_postal = adresa.cod judet = adresa.judet localitate = adresa.localitate if not adresa.is_adresa_sat( ) else adresa.localitate + ", " + adresa.comuna adresa_strada = adresa.__unicode__(short=True) Story.append(Paragraph(u"<b>Destinatar:</b>", styles['Justify'])) Story.append( Paragraph(u"<b>%s</b>" % destinatar, styles['Justify'])) Story.append(Paragraph(u"%s" % adresa_strada, styles['Justify'])) if localitate: linie_localitate = u"{0}".format(localitate) if cod_postal: linie_localitate = u"{0}, ".format( cod_postal) + linie_localitate Story.append(Paragraph(linie_localitate, styles['Justify'])) Story.append(Paragraph(u"Județ %s" % judet, styles['Justify'])) Story.append(PageBreak()) raport = u"<b>Total participanti: </b> %d<br /><b>Total erori:</b> %d<br /><b>Total OK:</b> %d<br />" % ( len(qs), error_count, len(qs) - error_count) Story.append(Paragraph(raport, styles['Justify'])) Story.append(PageBreak()) doc.build(Story) response = HttpResponse(content_type="application/pdf") response[ 'Content-Disposition'] = 'attachment; filename="export_C5.pdf"' pdf = buff.getvalue() buff.close() response.write(pdf) return response
def get_overlay_canvas(character: "Character", skip_name=False) -> io.BytesIO: data = io.BytesIO() pdf = canvas.Canvas(data) pdfmetrics.registerFont(TTFont('FreeSans', 'FreeSans.ttf')) if not skip_name: write_in_pdf(character.xml.name, pdf, 'name') write_in_pdf(character.xml.abilities.strength.bonus, pdf, 'strength') write_in_pdf(character.xml.abilities.strength.score, pdf, 'strength.value') write_in_pdf(character.xml.abilities.dexterity.bonus, pdf, 'dexterity') write_in_pdf(character.xml.abilities.dexterity.score, pdf, 'dexterity.value') write_in_pdf(character.xml.abilities.constitution.bonus, pdf, 'constitution') write_in_pdf(character.xml.abilities.constitution.score, pdf, 'constitution.value') write_in_pdf(character.xml.abilities.intelligence.bonus, pdf, 'intellect') write_in_pdf(character.xml.abilities.intelligence.score, pdf, 'intellect.value') write_in_pdf(character.xml.abilities.wisdom.bonus, pdf, 'wisdom') write_in_pdf(character.xml.abilities.wisdom.score, pdf, 'wisdom.value') write_in_pdf(character.xml.abilities.charisma.bonus, pdf, 'charisma') write_in_pdf(character.xml.abilities.charisma.score, pdf, 'charisma.value') write_in_pdf(character.xml.perception, pdf, 'passive_perception') write_in_pdf(character.xml.profbonus, pdf, 'profbonus') if character.xml.abilities.strength.saveprof == '1': write_in_pdf('v', pdf, 'strength.saveprof') if character.xml.abilities.dexterity.saveprof == '1': write_in_pdf('v', pdf, 'dexterity.saveprof') if character.xml.abilities.constitution.saveprof == '1': write_in_pdf('v', pdf, 'constitution.saveprof') if character.xml.abilities.intelligence.saveprof == '1': write_in_pdf('v', pdf, 'intellect.saveprof') if character.xml.abilities.wisdom.saveprof == '1': write_in_pdf('v', pdf, 'wisdom.saveprof') if character.xml.abilities.charisma.saveprof == '1': write_in_pdf('v', pdf, 'charisma.saveprof') write_in_pdf(character.xml.abilities.strength.save, pdf, 'strength.save') write_in_pdf(character.xml.abilities.dexterity.save, pdf, 'dexterity.save') write_in_pdf(character.xml.abilities.constitution.save, pdf, 'constitution.save') write_in_pdf(character.xml.abilities.intelligence.save, pdf, 'intellect.save') write_in_pdf(character.xml.abilities.wisdom.save, pdf, 'wisdom.save') write_in_pdf(character.xml.abilities.charisma.save, pdf, 'charisma.save') try: if hasattr(character.xml.skilllist, 'acrobatics') and character.xml.skilllist.acrobatics.prof == '1': write_in_pdf('v', pdf, 'acrobatics.prof') if hasattr(character.xml.skilllist, 'investigation') and character.xml.skilllist.investigation.prof == '1': write_in_pdf('v', pdf, 'investigation.prof') if hasattr(character.xml.skilllist, 'athletic') and character.xml.skilllist.athletics.prof == '1': write_in_pdf('v', pdf, 'athletic.prof') if hasattr(character.xml.skilllist, 'perception') and character.xml.skilllist.perception.prof == '1': write_in_pdf('v', pdf, 'perception.prof') if hasattr(character.xml.skilllist, 'survival') and character.xml.skilllist.survival.prof == '1': write_in_pdf('v', pdf, 'survival.prof') if hasattr(character.xml.skilllist, 'performance') and character.xml.skilllist.performance.prof == '1': write_in_pdf('v', pdf, 'performance.prof') if hasattr(character.xml.skilllist, 'intimidation') and character.xml.skilllist.intimidation.prof == '1': write_in_pdf('v', pdf, 'intimidation.prof') if hasattr(character.xml.skilllist, 'history') and character.xml.skilllist.history.prof == '1': write_in_pdf('v', pdf, 'history.prof') if hasattr(character.xml.skilllist, 'sleight_of_hand') and character.xml.skilllist.sleight_of_hand.prof == '1': write_in_pdf('v', pdf, 'sleight_of_hand.prof') if hasattr(character.xml.skilllist, 'arcana') and character.xml.skilllist.arcana.prof == '1': write_in_pdf('v', pdf, 'arcana.prof') if hasattr(character.xml.skilllist, 'medicine') and character.xml.skilllist.medicine.prof == '1': write_in_pdf('v', pdf, 'medicine.prof') if hasattr(character.xml.skilllist, 'deception') and character.xml.skilllist.deception.prof == '1': write_in_pdf('v', pdf, 'deception.prof') if hasattr(character.xml.skilllist, 'nature') and character.xml.skilllist.nature.prof == '1': write_in_pdf('v', pdf, 'nature.prof') if hasattr(character.xml.skilllist, 'insight') and character.xml.skilllist.insight.prof == '1': write_in_pdf('v', pdf, 'insight.prof') if hasattr(character.xml.skilllist, 'religion') and character.xml.skilllist.religion.prof == '1': write_in_pdf('v', pdf, 'religion.prof') if hasattr(character.xml.skilllist, 'stealth') and character.xml.skilllist.stealth.prof == '1': write_in_pdf('v', pdf, 'stealth.prof') if hasattr(character.xml.skilllist, 'persuasion') and character.xml.skilllist.persuasion.prof == '1': write_in_pdf('v', pdf, 'persuasion.prof') if hasattr(character.xml.skilllist, 'animal_handling') and character.xml.skilllist.animal_handling.prof == '1': write_in_pdf('v', pdf, 'animal_handling.prof') except AttributeError: pass # write_in_pdf(character.xml.skilllist.acrobatics.total, pdf, 'acrobatics') # write_in_pdf(character.xml.skilllist.investigation.total, pdf, 'investigation') # write_in_pdf(character.xml.skilllist.athletics.total, pdf, 'athletic') # write_in_pdf(character.xml.skilllist.perception.total, pdf, 'perception') # write_in_pdf(character.xml.skilllist.survival.total, pdf, 'survival') # write_in_pdf(character.xml.skilllist.performance.total, pdf, 'performance') # write_in_pdf(character.xml.skilllist.intimidation.total, pdf, 'intimidation') # write_in_pdf(character.xml.skilllist.history.total, pdf, 'history') # write_in_pdf(character.xml.skilllist.sleight_of_hand.total, pdf, 'sleight_of_hand') # write_in_pdf(character.xml.skilllist.arcana.total, pdf, 'arcana') # write_in_pdf(character.xml.skilllist.medicine.total, pdf, 'medicine') # write_in_pdf(character.xml.skilllist.deception.total, pdf, 'deception') # write_in_pdf(character.xml.skilllist.nature.total, pdf, 'nature') # write_in_pdf(character.xml.skilllist.insight.total, pdf, 'insight') # write_in_pdf(character.xml.skilllist.religion.total, pdf, 'religion') # write_in_pdf(character.xml.skilllist.stealth.total, pdf, 'stealth') # write_in_pdf(character.xml.skilllist.persuasion.total, pdf, 'persuasion') # write_in_pdf(character.xml.skilllist.animal_handling.total, pdf, 'animal_handling') write_in_pdf(character.xml.defenses.ac.total, pdf, 'armor') write_in_pdf(character.xml.initiative.total, pdf, 'initiative') write_in_pdf(str(int(character.xml.speed.total) // 5), pdf, 'speed') class_level_string = '' dice = [] for class_ in character.xml.classes: class_level_string += f', {class_.name} {class_.level}' dice.extend(str((class_.hddie + ' ') * int(class_.level)).split()) class_level_string = class_level_string[2:] write_in_pdf(class_level_string, pdf, 'class_level') write_in_pdf(character.xml.race, pdf, 'race') try: write_in_pdf(character.xml.alignment, pdf, 'alignment') except AttributeError: pass try: write_in_pdf(character.xml.background, pdf, 'background') except AttributeError: pass write_in_pdf(character.xml.hp.total, pdf, 'hp_max') write_in_pdf(str(len(dice)), pdf, 'total_dice') write_in_pdf(' '.join(dice), pdf, 'dice') spellcasting_ability_string = None character.xml.featurelist: DefaultNamedtuple for feature_name in character.xml.featurelist._asdict().keys(): if 'spellcasting' in feature_name: spellcasting_ability_text = getattr(character.xml.featurelist, feature_name).text spellcasting_ability_string = re.search(r'(\w+) is your spellcasting ability', spellcasting_ability_text) if spellcasting_ability_string: spellcasting_ability_string = spellcasting_ability_string.group(1).lower() else: spellcasting_ability_string = None if not spellcasting_ability_string: spellcasting_ability_string = 'intelligence' spellcasting_ability = getattr(character.xml.abilities, spellcasting_ability_string) magic_attacks_modifier = int(character.xml.profbonus) + int(spellcasting_ability.bonus) if magic_attacks_modifier > 0: magic_attacks_modifier = '+' + str(magic_attacks_modifier) write_in_pdf(f'Модификатор магических атак: {magic_attacks_modifier}', pdf, 'magic1', fixed_font_size=6) write_in_pdf(f'Бонус мастерства ({character.xml.profbonus}) + ' f'Модификатор {getattr(abilities_translation, spellcasting_ability_string).родительный.capitalize()} ' f'({spellcasting_ability.bonus})', pdf, 'magic2', fixed_font_size=6) write_in_pdf(f'Сложность спасброска: {10 + int(spellcasting_ability.bonus)}', pdf, 'magic3', fixed_font_size=6) write_in_pdf(f'10 + Модификатор ' f'{getattr(abilities_translation, spellcasting_ability_string).родительный.capitalize()} ' f'({spellcasting_ability.bonus})', pdf, 'magic4', fixed_font_size=6) write_in_pdf(f'Атака: Бонус мастерства ({character.xml.profbonus}), если проф. владение+', pdf, 'magic5', fixed_font_size=6) write_in_pdf(f'Модификатор Силы({character.xml.abilities.strength.bonus}) или ' f'Ловкости({character.xml.abilities.dexterity.bonus}), если фехтовальное', pdf, 'magic6', fixed_font_size=6) write_in_pdf(f'Урон: Модификатор Силы ({character.xml.abilities.strength.bonus}) или ' f'Ловкости({character.xml.abilities.dexterity.bonus}), если фехтовальное', pdf, 'magic7', fixed_font_size=5) dexterity_included = character.xml.abilities.dexterity.bonus try: if character.xml.defenses.ac.dexbonus == 'no': dexterity_included = 'no' except AttributeError: pass ac_string = f'КД: Осн(10) + Броня({character.xml.defenses.ac.armor}) + ' \ f'Ловк({dexterity_included}) + Щит({character.xml.defenses.ac.shield})' if character.xml.defenses.ac.misc != 0: ac_string += f' + Доп({character.xml.defenses.ac.misc})' write_in_pdf(ac_string, pdf, 'magic8', fixed_font_size=6) damage_translations_dict = {'slashing': 'рубящий', 'piercing': 'колющий', 'bludgeoning': 'дробящий', 'cold': 'холод', 'acid': 'кислота', 'fire': 'огонь', 'magic': 'магический', 'poison': 'яд', 'force': 'сил. поле', 'necrotic': 'некротика', 'lightning': 'молния', 'psychic': 'психический', 'radiant': 'излучение', 'thunder': 'звук', } # weapons = character.xml.weaponlist # for number, weapon in enumerate(weapons): # if number > 2: # break # damage_type = damage_translations_dict[weapon.damagelist[0].type.lower()] \ # if weapon.damagelist[0].type.lower() in damage_translations_dict else weapon.damagelist[0].type.lower() # # attack_bonus = 0 # damage_bonus = 0 # # if hasattr(weapon, 'prof') and weapon.prof == '1': # if need to add proficiency # attack_bonus += int(character.xml.profbonus) # if hasattr(weapon, 'properties') and 'finesse' in weapon.properties.lower(): # attack_bonus += max(int(character.xml.abilities.strength.bonus), # int(character.xml.abilities.dexterity.bonus)) # damage_bonus += max(int(character.xml.abilities.strength.bonus), # int(character.xml.abilities.dexterity.bonus)) # # elif hasattr(weapon, 'properties') and 'range' in weapon.properties.lower() and '/' in weapon.properties.lower(): # attack_bonus += int(character.xml.abilities.dexterity.bonus) # damage_bonus += int(character.xml.abilities.dexterity.bonus) # elif hasattr(weapon, 'attackstat'): # attack_bonus += int(getattr(character.xml.abilities, weapon.attackstat).bonus) # damage_bonus += int(getattr(character.xml.abilities, weapon.attackstat).bonus) # else: # attack_bonus += int(character.xml.abilities.strength.bonus) # damage_bonus += int(character.xml.abilities.strength.bonus) # # if hasattr(weapon, 'attackbonus'): # attack_bonus += int(weapon.attackbonus) # # if hasattr(weapon.damagelist[0], 'bonus'): # damage_bonus += int(weapon.damagelist[0].bonus) # # if damage_bonus > 0: # damage_bonus = '+' + str(damage_bonus) # elif damage_bonus == 0: # damage_bonus = '' # damage_dice_string = '' # damage_dice_list = weapon.damagelist[0].dice.split(',') # type:list # for unique_dice in set(damage_dice_list): # if damage_dice_list.count(unique_dice) == 1: # damage_dice_string += f'{unique_dice} + ' # else: # damage_dice_string += f'{damage_dice_list.count(unique_dice)}{unique_dice} + ' # # damage_dice_string = damage_dice_string[:-2] # to cut plus and space in the end # # write_in_pdf(weapon.name, pdf, f'weapon{number}.name') # write_in_pdf(str(attack_bonus), pdf, f'weapon{number}.attack') # write_in_pdf(f'{damage_dice_string}{damage_bonus} {damage_type}', pdf, f'weapon{number}.damage') feature_list_position = 0 for number, feature in enumerate(character.xml.featurelist, 1): feature_list_position += 1 try: level = feature.level except AttributeError: level = '' text_to_write = f'{feature.name} (от {feature.source} {level})' if len(text_to_write) > 64: write_in_pdf(text_to_write[:64], pdf, f'feature{number * 2 - 1}', fixed_font_size=5) write_in_pdf(text_to_write[64:], pdf, f'feature{number * 2}', fixed_font_size=5) else: write_in_pdf(text_to_write, pdf, f'feature{number * 2 - 1}', fixed_font_size=5) if hasattr(character.xml, 'featlist'): for number, feature in enumerate(character.xml.featlist, feature_list_position + 1): if not hasattr(feature, 'name'): continue text_to_write = f'{feature.name} (черта)' if len(text_to_write) > 64: write_in_pdf(text_to_write[:64], pdf, f'feature{number * 2 - 1}', fixed_font_size=5) write_in_pdf(text_to_write[64:], pdf, f'feature{number * 2}', fixed_font_size=5) else: write_in_pdf(text_to_write, pdf, f'feature{number * 2 - 1}', fixed_font_size=5) # write_in_pdf(f'{feature.name} (черта)', pdf, f'feature{number * 2 - 1}') language_translation_dict = {'Common': 'Общий', 'Dwarvish': 'Дворфский', 'Elvish': 'Эльфийский', 'Abyssal': 'Бездны', 'Aquan': 'Водный', 'Celestial': 'Небесный', 'Deep Speech': 'Глубинный', 'Draconic': 'Драконий', 'Giant': 'Великаний', 'Gnomish': 'Гномий', 'Goblin': 'Гоблинский', 'Halfling': 'Полуросликов', 'Ingan': 'Огненный', 'Infernal': 'Инфернальный', 'Orc': 'Орочий', 'Primordal': 'Первородный', 'Sylvan': 'Лесной', 'Terran': 'Земной', 'UnderCommon': 'Глубинный Общий'} for number, language in enumerate(character.xml.languagelist, 1): try: language_name = language.name.strip() if language_name in language_translation_dict: language_name = language_translation_dict[language_name] write_in_pdf(f'{language_name} язык', pdf, f'language{number}') except Exception as e: print(e) pdf.save() data.seek(0) return data
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) 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
#!/usr/bin/env python # -*- coding: utf8 -*- from PyPDF2 import PdfFileWriter, PdfFileReader from reportlab.pdfgen import canvas from reportlab.lib.pagesizes import letter # TODO: register all unicode fonts from reportlab.pdfbase import pdfmetrics from reportlab.pdfbase.ttfonts import TTFont font = TTFont('Condensed', 'DejaVuSansCondensed.ttf') pdfmetrics.registerFont(font) font_name = 'Condensed' from reportlab.pdfbase.pdfmetrics import stringWidth from reportlab.rl_config import defaultPageSize PAGE_WIDTH = defaultPageSize[0] PAGE_HEIGHT = defaultPageSize[1] from os.path import isfile def generate_filename(details, encrypt=False): filename = u"{}_{}_{}_{}".format(details['surname'], details['name'], details['year'], details['id']) if encrypt: from hashlib import md5 filename = md5(filename.encode('utf-8')).hexdigest() filename = unicode(filename) filename = filename[-10:]
def create_pdfs(self): # ?????????????????????????????????????? # ?????????????????????????????????????? # zmienić ścieżkę # ?????????????????????????????????????? # ?????????????????????????????????????? # ?????????????????????????????????????? pdfmetrics.registerFont( TTFont('polishFont', 'Bookmarks/AbhayaLibre-Regular.ttf')) categories_for_pdf = self.prepare_categories_to_pdf() styles = getSampleStyleSheet() styles.add( ParagraphStyle(name='RegularDownloaded', alignment=TA_JUSTIFY, fontName='polishFont', fontSize=12)) styles.add( ParagraphStyle(name='WeightName', alignment=TA_JUSTIFY, fontName='polishFont', fontSize=17)) path = os.getcwd() + "\\User_Files\\Categories_to_draw_lots\\" path = r"{}".format(path) for pdf_data in categories_for_pdf: pdf = SimpleDocTemplate(path + pdf_data[0] + "_" + pdf_data[1] + ".pdf", pagesize=letter, rightMargin=72, leftMargin=72, topMargin=72, bottomMargin=18) body = [] for category in categories_for_pdf[pdf_data]: body.append( Paragraph( '<font size="17"> %s </font>' % ('Kategoria: ' + category.gender + "-" + category.age + "-" + category.category + " kg"), styles["WeightName"])) body.append(Spacer(1, 10)) for competitor in categories_for_pdf[pdf_data][category]: body.append( Paragraph( competitor.get_surname() + " " + competitor.get_first_name() + " | " + competitor.get_club() + '|' + competitor.get_licence_no(), styles["RegularDownloaded"])) body.append(Spacer(1, 10)) # Save the PDF file pdf.build(body) print("Zakończono generowanie pdfów")
from reportlab.pdfbase import pdfmetrics from reportlab.pdfbase.ttfonts import TTFont from reportlab.pdfgen import canvas import os from reportlab.lib.enums import TA_JUSTIFY, TA_LEFT, TA_CENTER, TA_RIGHT from reportlab.graphics.shapes import Drawing, Line import arabic_reshaper from bidi.algorithm import get_display import Bahr_template PAGESIZE = (140 * mm, 216 * mm) BASE_MARGIN = 2 * mm # BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) pdfmetrics.registerFont(TTFont('Arabic', 'arabic.ttf')) class BahrTemplateGenerator: def add_page_number(self, canvas, doc): canvas.saveState() canvas.setFont('Times-Roman', 10) page_number_text = "%d" % (doc.page) canvas.drawCentredString(0.75 * inch, 0.75 * inch, page_number_text) canvas.restoreState() def draw_line(self, x1, y1, x2, y2, line_color=colors.black): drawable_line = Drawing(x1, y1) drawable_line.add(Line(0, 0, x2, y2, fillColor=line_color)) return drawable_line
def informe_gsm(archivo, datos, x, y): #TTFont(nombre, archivo) print(datos) pdfmetrics.registerFont(TTFont('verdana', 'verdana.ttf')) styles = getSampleStyleSheet() styles.add( ParagraphStyle(name='center', alignment=TA_CENTER, fontSize=36, fontName="verdana")) doc = SimpleDocTemplate(archivo, pagesize=A4) # container for the 'Flowable' objects elements = [] ptitulo1 = '<font size=36>ADENEIRA</font>' ptitulo2 = '<font size=36>el mejor albariño</font>' ptitulo3 = '<font size=36>que puedas imaginar</font>' elements.append(Paragraph(ptitulo1, styles["center"])) elements.append(Spacer(1, 36)) elements.append(Paragraph(ptitulo2, styles["center"])) elements.append(Spacer(1, 36)) elements.append(Paragraph(ptitulo3, styles["center"])) elements.append(Spacer(1, 36)) data = [[ datos[1][0], datos[1][1], datos[1][2], datos[1][3], datos[1][4], datos[1][5], datos[1][6], datos[1][7], datos[1][8], datos[1][9], datos[1][10], datos[1][11], datos[1][12], datos[1][13], datos[1][14], datos[1][15] ], [ datos[2][0], datos[2][1], datos[2][2], datos[2][3], datos[2][4], datos[2][5], datos[2][6], datos[2][7], datos[2][8], datos[2][9], datos[2][10], datos[2][11], datos[2][12], datos[2][13], datos[2][14], datos[2][15] ], [ datos[3][0], datos[3][1], datos[3][2], datos[3][3], datos[3][4], datos[3][5], datos[3][6], datos[3][7], datos[3][8], datos[3][9], datos[3][10], datos[3][11], datos[3][12], datos[3][13], datos[3][14], datos[3][15] ], [ datos[4][0], datos[4][1], datos[4][2], datos[4][3], datos[4][4], datos[4][5], datos[4][6], datos[4][7], datos[4][8], datos[4][9], datos[4][10], datos[4][11], datos[4][12], datos[4][13], datos[4][14], datos[4][15] ], [ datos[5][0], datos[5][1], datos[5][2], datos[5][3], datos[5][4], datos[5][5], datos[5][6], datos[5][7], datos[5][8], datos[5][9], datos[5][10], datos[5][11], datos[5][12], datos[5][13], datos[5][14], datos[5][15] ], [ datos[6][0], datos[6][1], datos[6][2], datos[6][3], datos[6][4], datos[6][5], datos[6][6], datos[6][7], datos[6][8], datos[6][9], datos[6][10], datos[6][11], datos[6][12], datos[6][13], datos[6][14], datos[6][15] ], [ datos[7][0], datos[7][1], datos[7][2], datos[7][3], datos[7][4], datos[7][5], datos[7][6], datos[7][7], datos[7][8], datos[7][9], datos[7][10], datos[7][11], datos[7][12], datos[7][13], datos[7][14], datos[7][15] ], [ datos[8][0], datos[8][1], datos[8][2], datos[8][3], datos[8][4], datos[8][5], datos[8][6], datos[8][7], datos[8][8], datos[8][9], datos[8][10], datos[8][11], datos[8][12], datos[8][13], datos[8][14], datos[8][15] ]] print("x:" + str(x), "y:" + str(y)) t = Table(data) t.setStyle( TableStyle([ ('ALIGN', (x, y), (0, 0), 'CENTER'), ('TEXTCOLOR', (x, y), (0, 0), colors.black), ('VALIGN', (x, y), (0, 0), 'MIDDLE'), ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black), ('BOX', (0, 0), (-1, -1), 0.25, colors.black), ])) elements.append(t) # write the document to disk doc.build(elements)
# -*- coding: utf-8 -*- import pdfrw from reportlab.pdfgen import canvas from datetime import date from bidi.algorithm import get_display from reportlab.pdfbase import pdfmetrics from reportlab.pdfbase.ttfonts import TTFont import os pdfmetrics.registerFont(TTFont('Hebrew', 'ArialHB.ttf')) def create_overlay(child): today = date.today() today_str = today.strftime("%d/%m/%Y") health_canvas = canvas.Canvas(child.child_id + "_overlay.pdf") health_canvas.setFont("Hebrew", 14) health_canvas.drawString(395, 548, get_display(child.child_name)) health_canvas.drawString(280, 548, get_display(child.child_id)) health_canvas.drawString(450, 402, get_display(child.parent_name)) health_canvas.drawString(330, 402, get_display(child.parent_id)) health_canvas.drawString(210, 402, today_str) health_canvas.save() def merge_pdfs(child, output): create_overlay(child)
import sys from subprocess import call from os import devnull from reportlab.pdfgen import canvas from reportlab.pdfbase.pdfmetrics import registerFont from reportlab.pdfbase.ttfonts import TTFont # Register fonts fonts = ['OpenSans-Bold', 'OpenSans-Regular'] for font in fonts: f = TTFont(font, 'fonts/' + font + '.ttf') registerFont(f) lblSize = (216, 72) lblPath = '/tmp/label.pdf' bold = 'OpenSans-Bold' regular = 'OpenSans-Regular' top = 56 left = 4 middle = 32 bottom = 6 def print_label(top_left, center, bottom_left, copies): c = canvas.Canvas(lblPath, pagesize=lblSize) # Draw top left c.setFont(bold, 16) c.drawString(left, top, str(top_left).upper()) # Draw left center
def __load_font_type(self): """__load_font_type will load the provided font """ letters = string.ascii_letters self.fontType = ''.join(random.choice(letters) for i in range(10)) pdfmetrics.registerFont(TTFont(self.fontType, self.font_type_path))
from reportlab.lib.pagesizes import letter, A4 from reportlab.pdfbase import pdfmetrics from reportlab.pdfbase.ttfonts import TTFont from reportlab.pdfgen import canvas # reportlab helper import rltools # python-chess import chess import chess.pgn # reportlab setup pdfmetrics.registerFont(TTFont('ChessAlpha2', 'resources/ChessAlpha2.ttf')) # measuring unitsPerInch = inch inchesPerUnit = 1.0 / unitsPerInch pageWidth = 8.5 * unitsPerInch pageHeight = 11.0 * unitsPerInch print "page area (w,h)=(%d,%d) units" % (pageWidth, pageHeight) margin = MARGIN_INCHES * unitsPerInch diagSpacing = INTER_DIAGRAM_SPACING_INCHES * unitsPerInch diagAreaWidth = pageWidth - 2 * margin diagAreaHeight = pageHeight - 2 * margin - ( HEIGHT_HEADER_INCHES + HEIGHT_FOOTER_INCHES) * unitsPerInch print "diag area (w,h)=(%d,%d) units" % (diagAreaWidth, diagAreaHeight) # diagram locations, numbers