Python reportlab.pdfbase.ttfonts.TTFont() Examples

The following are 14 code examples of reportlab.pdfbase.ttfonts.TTFont(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module reportlab.pdfbase.ttfonts , or try the search function .
Example #1
Source File: generatereport.py    From kobo-predict with BSD 2-Clause "Simplified" License 7 votes vote down vote up
def __init__(self, filename, **kw):
         self.allowSplitting = 1
         apply(SimpleDocTemplate.__init__, (self, filename), kw)
         pdfmetrics.registerFont(TTFont('arialuni', 'ARIALUNI.TTF'))

# Entries to the table of contents can be done either manually by
# calling the addEntry method on the TableOfContents object or automatically
# by sending a 'TOCEntry' notification in the afterFlowable method of
# the DocTemplate you are using. The data to be passed to notify is a list
# of three or four items countaining a level number, the entry text, the page
# number and an optional destination key which the entry should point to.
# This list will usually be created in a document template's method like
# afterFlowable(), making notification calls using the notify() method
# with appropriate data. 
Example #2
Source File: pdf.py    From blockdiag with Apache License 2.0 6 votes vote down vote up
def set_font(self, font):
        if font.path is None:
            msg = "Could not detect fonts, use --font opiton\n"
            raise RuntimeError(msg)

        if font.path not in self.fonts:
            path, index = parse_fontpath(font.path)
            if index:
                ttfont = TTFont(font.path, path, subfontIndex=index)
            else:
                ttfont = TTFont(font.path, path)
            pdfmetrics.registerFont(ttfont)

            self.fonts[font.path] = ttfont

        self.canvas.setFont(font.path, font.size) 
Example #3
Source File: letters.py    From coursys with GNU General Public License v3.0 5 votes vote down vote up
def _media_setup(self):
        "Get all of the media needed for the letterhead"
        # fonts and logo
        ttfFile = os.path.join(media_path, 'BemboMTPro-Regular.ttf')
        pdfmetrics.registerFont(TTFont("BemboMTPro", ttfFile))
        ttfFile = os.path.join(media_path, 'BemboMTPro-Bold.ttf')
        pdfmetrics.registerFont(TTFont("BemboMTPro-Bold", ttfFile))
        ttfFile = os.path.join(media_path, 'DINPro-Regular.ttf')
        pdfmetrics.registerFont(TTFont("DINPro", ttfFile))
        ttfFile = os.path.join(media_path, 'DINPro-Bold.ttf')
        pdfmetrics.registerFont(TTFont("DINPro-Bold", ttfFile))

        # graphic standards colours
        self.sfu_red = CMYKColor(0, 1, 0.79, 0.2)
        self.sfu_grey = CMYKColor(0, 0, 0.15, 0.82)
        self.sfu_blue = CMYKColor(1, 0.68, 0, 0.12)

        # translate digits to old-style numerals (in their Bembo character positions)
        self.digit_trans = {}
        for d in range(10):
            self.digit_trans[48+d] = chr(0xF643 + d)

        self.sc_trans_bembo = {}
        # translate letters to smallcaps characters (in their [strange] Bembo character positions)
        for d in range(26):
            if d<3: # A-C
                offset = d
            elif d<4: # D
                offset = d+2
            elif d<21: # E-U
                offset = d+3
            else: # V-Z
                offset = d+4
            self.sc_trans_bembo[65+d] = chr(0xE004 + offset)
            self.sc_trans_bembo[97+d] = chr(0xE004 + offset) 
Example #4
Source File: report.py    From flask-restful-example with MIT License 5 votes vote down vote up
def pdf_write(generated_pdf_path):
    """
    生成pdf
    :return:
    """
    # 增加的字体,支持中文显示,需要自行下载支持中文的字体
    font_path = current_app.config.get("SIM_SUN")

    pdfmetrics.registerFont(TTFont('SimSun', os.path.join(font_path, 'SimSun.ttf')))
    styles = getSampleStyleSheet()
    styles.add(ParagraphStyle(fontName='SimSun', name='SimSun', leading=20, fontSize=12))
    data = list()
    # 添加一段文字
    paragraph = paragraph_model("测试添加一段文字")
    data.append(paragraph)
    data.append(PageBreak())  # 分页标识
    # 添加table和图片
    table = table_model()
    data.append(table)
    data.append(PageBreak())  # 分页标识
    img = image_model()
    data.append(img)

    # 设置生成pdf的名字和编剧
    pdf = SimpleDocTemplate(generated_pdf_path, rightMargin=0, leftMargin=0, topMargin=40, bottomMargin=0, )
    # 设置pdf每页的大小
    pdf.pagesize = (9 * inch, 10 * inch)

    pdf.multiBuild(data)
    return generated_pdf_path 
Example #5
Source File: reporting.py    From attack_monitor with GNU General Public License v3.0 5 votes vote down vote up
def load_font(self):
        cc = configer.Config()

        freeserif_font = cc.get_font_path()
        pdfmetrics.registerFont(TTFont("freeserif", freeserif_font)) 
Example #6
Source File: testshapes.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def _setup():
    from reportlab.pdfbase import pdfmetrics, ttfonts
    pdfmetrics.registerFont(ttfonts.TTFont("Vera", "Vera.ttf"))
    pdfmetrics.registerFont(ttfonts.TTFont("VeraBd", "VeraBd.ttf"))
    pdfmetrics.registerFont(ttfonts.TTFont("VeraIt", "VeraIt.ttf"))
    pdfmetrics.registerFont(ttfonts.TTFont("VeraBI", "VeraBI.ttf"))
    F = ['Times-Roman','Courier','Helvetica','Vera', 'VeraBd', 'VeraIt', 'VeraBI']
    if sys.platform=='win32':
        for name, ttf in [
            ('Adventurer Light SF','Advlit.ttf'),('ArialMS','ARIAL.TTF'),
            ('Arial Unicode MS', 'ARIALUNI.TTF'),
            ('Book Antiqua','BKANT.TTF'),
            ('Century Gothic','GOTHIC.TTF'),
            ('Comic Sans MS', 'COMIC.TTF'),
            ('Elementary Heavy SF Bold','Vwagh.ttf'),
            ('Firenze SF','flot.ttf'),
            ('Garamond','GARA.TTF'),
            ('Jagger','Rols.ttf'),
            ('Monotype Corsiva','MTCORSVA.TTF'),
            ('Seabird SF','seag.ttf'),
            ('Tahoma','TAHOMA.TTF'),
            ('VerdanaMS','VERDANA.TTF'),
            ]:
            for D in ('c:\WINNT','c:\Windows'):
                fn = os.path.join(D,'Fonts',ttf)
                if os.path.isfile(fn):
                    try:
                        f = ttfonts.TTFont(name, fn)
                        pdfmetrics.registerFont(f)
                        F.append(name)
                    except:
                        pass
    return F 
Example #7
Source File: svglib.py    From svglib with GNU Lesser General Public License v3.0 5 votes vote down vote up
def find_font(font_name):
    """Return the font and a Boolean indicating if the match is exact."""
    if font_name in STANDARD_FONT_NAMES:
        return font_name, True
    elif font_name in _registered_fonts:
        return font_name, _registered_fonts[font_name]

    NOT_FOUND = (None, False)
    try:
        # Try first to register the font if it exists as ttf,
        # based on ReportLab font search.
        registerFont(TTFont(font_name, '%s.ttf' % font_name))
        _registered_fonts[font_name] = True
        return font_name, True
    except TTFError:
        # Try searching with Fontconfig
        try:
            pipe = subprocess.Popen(
                ['fc-match', '-s', '--format=%{file}\\n', font_name],
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE,
            )
            output = pipe.communicate()[0].decode(sys.getfilesystemencoding())
            font_path = output.split('\n')[0]
        except OSError:
            return NOT_FOUND
        try:
            registerFont(TTFont(font_name, font_path))
        except TTFError:
            return NOT_FOUND
        # Fontconfig may return a default font totally unrelated with font_name
        exact = font_name.lower() in os.path.basename(font_path).lower()
        _registered_fonts[font_name] = exact
        return font_name, exact 
Example #8
Source File: testshapes.py    From stdm with GNU General Public License v2.0 5 votes vote down vote up
def _setup():
    from reportlab.pdfbase import pdfmetrics, ttfonts
    pdfmetrics.registerFont(ttfonts.TTFont("Vera", "Vera.ttf"))
    pdfmetrics.registerFont(ttfonts.TTFont("VeraBd", "VeraBd.ttf"))
    pdfmetrics.registerFont(ttfonts.TTFont("VeraIt", "VeraIt.ttf"))
    pdfmetrics.registerFont(ttfonts.TTFont("VeraBI", "VeraBI.ttf"))
    F = ['Times-Roman','Courier','Helvetica','Vera', 'VeraBd', 'VeraIt', 'VeraBI']
    if sys.platform=='win32':
        for name, ttf in [
            ('Adventurer Light SF','Advlit.ttf'),('ArialMS','ARIAL.TTF'),
            ('Arial Unicode MS', 'ARIALUNI.TTF'),
            ('Book Antiqua','BKANT.TTF'),
            ('Century Gothic','GOTHIC.TTF'),
            ('Comic Sans MS', 'COMIC.TTF'),
            ('Elementary Heavy SF Bold','Vwagh.ttf'),
            ('Firenze SF','flot.ttf'),
            ('Garamond','GARA.TTF'),
            ('Jagger','Rols.ttf'),
            ('Monotype Corsiva','MTCORSVA.TTF'),
            ('Seabird SF','seag.ttf'),
            ('Tahoma','TAHOMA.TTF'),
            ('VerdanaMS','VERDANA.TTF'),
            ]:
            for D in ('c:\WINNT','c:\Windows'):
                fn = os.path.join(D,'Fonts',ttf)
                if os.path.isfile(fn):
                    try:
                        f = ttfonts.TTFont(name, fn)
                        pdfmetrics.registerFont(f)
                        F.append(name)
                    except:
                        pass
    return F 
Example #9
Source File: font.py    From tia with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def try_load(self, default=None):
        try:
            pdfmetrics.registerFont(TTFont(self.name, self.filename))
            return self.name
        except:
            return default 
Example #10
Source File: pdfs.py    From hypha with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def prepare_fonts():
    global PREPARED_FONTS
    if PREPARED_FONTS:
        return
    pdfmetrics.registerFont(TTFont('Montserrat', font('Montserrat-Regular.ttf')))
    pdfmetrics.registerFont(TTFont('MontserratBold', font('Montserrat-Bold.ttf')))
    pdfmetrics.registerFont(TTFont('MontserratItalic', font('Montserrat-Italic.ttf')))
    pdfmetrics.registerFont(TTFont('MontserratBoldItalic', font('Montserrat-BoldItalic.ttf')))
    pdfmetrics.registerFontFamily(
        'Montserrat',
        normal='Montserrat',
        bold='MontserratBold',
        italic='MontserratItalic',
        boldItalic='MontserratBoldItalic'
    )

    pdfmetrics.registerFont(TTFont('NotoSans', font('NotoSans-Regular.ttf')))
    pdfmetrics.registerFont(TTFont('NotoSansBold', font('NotoSans-Bold.ttf')))
    pdfmetrics.registerFont(TTFont('NotoSansItalic', font('NotoSans-Italic.ttf')))
    pdfmetrics.registerFont(TTFont('NotoSansBoldItalic', font('NotoSans-BoldItalic.ttf')))
    pdfmetrics.registerFontFamily(
        'NotoSans',
        normal='NotoSans',
        bold='NotoSansBold',
        italic='NotoSansItalic',
        boldItalic='NotoSansBoldItalic'
    )
    PREPARED_FONTS = True 
Example #11
Source File: txt2pdf.py    From txt2pdf with MIT License 4 votes vote down vote up
def __init__(self, args, margins):
        pageWidth, pageHeight = reportlab.lib.pagesizes.__dict__[args.media]
        if args.landscape:
            pageWidth, pageHeight = reportlab.lib.pagesizes.landscape(
                (pageWidth, pageHeight))
        self.author = args.author
        self.title = args.title
        self.keywords = args.keywords
        self.subject = args.subject
        self.canvas = Canvas(args.output, pagesize=(pageWidth, pageHeight))
        self.canvas.setCreator(self.appName)
        if len(args.author) > 0:
            self.canvas.setAuthor(args.author)
        if len(args.title) > 0:
            self.canvas.setTitle(args.title)
        if len(args.subject) > 0:
            self.canvas.setSubject(args.subject)
        if len(args.keywords) > 0:
            self.canvas.setKeywords(args.keywords)
        self.fontSize = args.font_size
        if args.font not in ('Courier'):
            self.font = 'myFont'
            pdfmetrics.registerFont(TTFont('myFont', args.font))
        else:
            self.font = args.font
        self.kerning = args.kerning
        self.margins = margins
        self.leading = (args.extra_vertical_space + 1.2) * self.fontSize
        self.linesPerPage = int(
            (self.leading + pageHeight
             - margins.top - margins.bottom - self.fontSize) / self.leading)
        self.lppLen = len(str(self.linesPerPage))
        fontWidth = self.canvas.stringWidth(
            ".", fontName=self.font, fontSize=self.fontSize)
        self.lineNumbering = args.line_numbers
        if self.lineNumbering:
            margins.adjustLeft(fontWidth * (self.lppLen + 2))
        contentWidth = pageWidth - margins.left - margins.right
        self.charsPerLine = int(
            (contentWidth + self.kerning) / (fontWidth + self.kerning))
        self.top = pageHeight - margins.top - self.fontSize
        self.filename = args.filename
        self.verbose = not args.quiet
        self.breakOnBlanks = args.break_on_blanks
        self.encoding = args.encoding
        self.pageNumbering = args.page_numbers
        if self.pageNumbering:
            self.pageNumberPlacement = \
               (pageWidth / 2, margins.bottom / 2) 
Example #12
Source File: txt2pdf.py    From PyExfil with MIT License 4 votes vote down vote up
def __init__(self, args, margins):
        pageWidth, pageHeight = reportlab.lib.pagesizes.__dict__[args.media]
        if args.landscape:
            pageWidth, pageHeight = reportlab.lib.pagesizes.landscape(
                (pageWidth, pageHeight))
        self.author = args.author
        self.title = args.title
        self.keywords = args.keywords
        self.subject = args.subject
        self.canvas = Canvas(args.output, pagesize=(pageWidth, pageHeight))
        self.canvas.setCreator(self.appName)
        if len(args.author) > 0:
            self.canvas.setAuthor(args.author)
        if len(args.title) > 0:
            self.canvas.setTitle(args.title)
        if len(args.subject) > 0:
            self.canvas.setSubject(args.subject)
        if len(args.keywords) > 0:
            self.canvas.setKeywords(args.keywords)
        self.fontSize = args.font_size
        if args.font not in ('Courier'):
            self.font = 'myFont'
            pdfmetrics.registerFont(TTFont('myFont', args.font))
        else:
            self.font = args.font
        self.kerning = args.kerning
        self.margins = margins
        self.leading = (args.extra_vertical_space + 1.2) * self.fontSize
        self.linesPerPage = int(
            (self.leading + pageHeight
             - margins.top - margins.bottom - self.fontSize) / self.leading)
        self.lppLen = len(str(self.linesPerPage))
        fontWidth = self.canvas.stringWidth(
            ".", fontName=self.font, fontSize=self.fontSize)
        self.lineNumbering = args.line_numbers
        if self.lineNumbering:
            margins.adjustLeft(fontWidth * (self.lppLen + 2))
        contentWidth = pageWidth - margins.left - margins.right
        self.charsPerLine = int(
            (contentWidth + self.kerning) / (fontWidth + self.kerning))
        self.top = pageHeight - margins.top - self.fontSize
        self.filename = args.filename
        self.verbose = not args.quiet
        self.breakOnBlanks = args.break_on_blanks
        self.encoding = args.encoding
        self.pageNumbering = args.page_numbers
        if self.pageNumbering:
            self.pageNumberPlacement = \
               (pageWidth / 2, margins.bottom / 2) 
Example #13
Source File: math_flowable.py    From rst2pdf with MIT License 4 votes vote down vote up
def drawOn(self, canv, x, y, _sW=0):
        if _sW and hasattr(self, 'hAlign'):
            from reportlab.lib.enums import TA_LEFT, TA_CENTER, TA_RIGHT, TA_JUSTIFY

            a = self.hAlign
            if a in ('CENTER', 'CENTRE', TA_CENTER):
                x = x + 0.5 * _sW
            elif a in ('RIGHT', TA_RIGHT):
                x = x + _sW
            elif a not in ('LEFT', TA_LEFT):
                raise ValueError("Bad hAlign value " + str(a))
        height = 0
        if HAS_MATPLOTLIB:
            global fonts
            canv.saveState()
            canv.translate(x, y)
            try:
                (
                    width,
                    height,
                    descent,
                    glyphs,
                    rects,
                    used_characters,
                ) = self.parser.parse(
                    enclose(self.s), 72, prop=FontProperties(size=self.fontsize)
                )
                for ox, oy, fontname, fontsize, num, symbol_name in glyphs:
                    if not fontname in fonts:
                        fonts[fontname] = fontname
                        pdfmetrics.registerFont(TTFont(fontname, fontname))
                    canv.setFont(fontname, fontsize)
                    col_conv = ColorConverter()
                    rgb_color = col_conv.to_rgb(self.color)
                    canv.setFillColorRGB(rgb_color[0], rgb_color[1], rgb_color[2])
                    canv.drawString(ox, oy, chr(num))

                canv.setLineWidth(0)
                canv.setDash([])
                for ox, oy, width, height in rects:
                    canv.rect(ox, oy + 2 * height, width, height, fill=1)
            except:
                # FIXME: report error
                col_conv = ColorConverter()
                rgb_color = col_conv.to_rgb(self.color)
                canv.setFillColorRGB(rgb_color[0], rgb_color[1], rgb_color[2])
                canv.drawString(0, 0, self.s)
            canv.restoreState()
        else:
            canv.saveState()
            canv.drawString(x, y, self.s)
            canv.restoreState()
        if self.label:
            log.info('Drawing equation-%s' % self.label)
            canv.bookmarkHorizontal('equation-%s' % self.label, 0, height) 
Example #14
Source File: gen.py    From cwg with GNU General Public License v3.0 4 votes vote down vote up
def generate_sheet(makemeahanzi_path, working_dir, title, guide, stroke_order_color):
    if len(title) > MAX_TITLE_LENGTH:
        raise GenException('Title length exceeded (' + str(len(title)) + \
                '/' + str(MAX_TITLE_LENGTH) + ')');

    character_infos = [];
    words = [];

    character_infos = load_data_from_json_file(working_dir, CHARACTERS_FILE, \
                                                object_to_character_info);
    words = load_data_from_json_file(working_dir, WORDS_FILE, Word.fromJSON);
    words = filter_out_words_with_empty_definition(words);

    c = canvas.Canvas(os.path.join(working_dir, SHEET_FILE), PAGE_SIZE);
    pdfmetrics.registerFont(TTFont(FONT_NAME, FONT_NAME + '.ttf'));

    words_with_spanning_translation = get_spanning_translations( \
                                        character_infos, words);

    draw_header(c, title, HEADER_FONT_SIZE, \
            PAGE_SIZE[1]-HEADER_PADDING);
    for i in range(len(character_infos)):
        i_mod = i % CHARACTERS_PER_PAGE;
        page_number = int(i / CHARACTERS_PER_PAGE + 1);
        if i != 0 and i_mod == 0:
            draw_footer(c, FOOTER_FONT_SIZE, y-CHARACTER_ROW_HEIGHT - \
                    GRID_OFFSET/2);
            draw_page_number(c, i / CHARACTERS_PER_PAGE, PAGE_NUMBER_FONT_SIZE);
            draw_words(c, character_infos, words, page_number-1, \
                        words_with_spanning_translation);
            c.showPage();
            draw_header(c, title, HEADER_FONT_SIZE, \
                    PAGE_SIZE[1]-HEADER_PADDING);
        info = character_infos[i];
        create_character_svg(working_dir, info);
        create_radical_svg(makemeahanzi_path, working_dir, info);
        create_stroke_order_svgs(working_dir, info, stroke_order_color);
        convert_svgs_to_pngs(working_dir);
        y = FIRST_CHARACTER_ROW_Y-i_mod*CHARACTER_ROW_HEIGHT;
        draw_character_row(working_dir, c, info, y, guide);
        delete_files(working_dir, '.*\.svg');
        delete_files(working_dir, '.*\.png');
    
    y = PAGE_SIZE[1]-HEADER_PADDING-GRID_OFFSET/2 - \
        (CHARACTERS_PER_PAGE-1)*CHARACTER_ROW_HEIGHT;
    # TODO: extract
    draw_footer(c, FOOTER_FONT_SIZE, y-CHARACTER_ROW_HEIGHT - \
                    GRID_OFFSET/2);
    draw_page_number(c, page_number, PAGE_NUMBER_FONT_SIZE);
    draw_words(c, character_infos, words, page_number, \
            words_with_spanning_translation);
    c.setTitle(title);
    c.showPage();
    c.save();