Ejemplo n.º 1
0
def getFontByName(name):
    """
    >>> getFontByName('PageBot')
    """
    return findFont(name)
Ejemplo n.º 2
0
# -----------------------------------------------------------------------------
#
#     testFontMetrics.py
#
import sys
from pagebot.contexts.platform import getContext

context = getContext()
if not context.isDrawBot:
    print('Example only runs on DrawBot.')
    sys.exit()

from pagebot.fonttoolbox.fontpaths import getTestFontsPath
from pagebot.fonttoolbox.objects.font import findFont

f = findFont('Amstelvar-Roman-VF')
print(
    'Family %s, style %s, em %d, ascender %d, descender: %d, capHeight %d, xHeight %d'
    % (f.info.familyName, f.info.styleName, f.info.unitsPerEm, f.info.ascender,
       f.info.descender, f.info.capHeight, f.info.xHeight))

spacer = context.newString('-----\n ',
                           style=dict(lineHeight=1, font=f.path, fontSize=12))

# Create DrawBotString, inheriting from BabelString, based on view type.
bs = context.newString('Hlxg',
                       style=dict(font=f.path,
                                  textFill=(1, 0, 0),
                                  fontSize=300,
                                  leading=320,
                                  baselineShift=200))
Ejemplo n.º 3
0
    def newString(cls,
                  s,
                  context,
                  e=None,
                  style=None,
                  w=None,
                  h=None,
                  pixelFit=True):
        """Answers a InDesignString instance from valid attributes in *style*.
        Set all values after testing their existence, so they can inherit from
        previous style formats. If target width *w* or height *h* is defined,
        then *fontSize* is scaled to make the string fit *w* or *h*.

        >>> from pagebot.toolbox.units import pt
        >>> from pagebot.contexts.indesigncontext import InDesignContext
        >>> context = InDesignContext()
        >>> bs = InDesignString.newString('AAA', context, style=dict(fontSize=pt(30)))
        >>> #bs.s.lines()
        >>> #'indesign.text.text' in str(bs)
        True
        """
        if style is None:
            style = {}

        sUpperCase = css('uppercase', e, style)
        sLowercase = css('lowercase', e, style)
        sCapitalized = css('capitalized', e, style)

        if sUpperCase:
            s = s.upper()
        elif sLowercase:
            s = s.lower()
        elif sCapitalized:
            s = s.capitalize()

        # Since Indesign does not do font GSUB feature compile, we'll make the transformed string here,
        # using Tal's https://github.com/typesupply/compositor
        # This needs to be installed, in case PageBot is running outside of DrawBot.

        font = style.get('font')
        if font is not None and not isinstance(font, str):
            font = font.path
        if font is None or not os.path.exists(font):
            font = DEFAULT_FONT_PATH
        fontSize = style.get('fontSize', DEFAULT_FONT_SIZE)
        assert isUnit(fontSize), (
            '%s.newString: FontSize %s must be of type Unit' %
            (cls.__name__, fontSize))
        leading = style.get('leading', DEFAULT_LEADING)
        assert isUnit(leading), (
            '%s.newString: Leading %s must be of type Unit' %
            (cls.__name__, leading))
        inDesignFont = findFont(font)
        #strike = context.b.strike(indesignFont)
        #strike.size(fontSize.pt, leading.pt, units='pt')
        #if w is not None:
        #    strike.width = w
        #s = strike.text(s)
        s = ''
        return cls(s, context=context,
                   style=style)  # Make real Indesign flavor BabelString here.
Ejemplo n.º 4
0
from pagebot.document import Document
from pagebot.fonttoolbox.objects.font import findFont
from pagebot.elements import newTextBox

W = 652
H = 850
W = pt(W)
H = pt(H)

#f = Color(0, 0, 0)
s = Color(1, 0, 0)

drawBotContext = getContext('DrawBot')
flatContext = getContext('Flat')
boldFontName = 'PageBot-Bold'
boldFont = findFont(boldFontName)
regularFontName = 'Roboto-Regular'
regularFont = findFont(regularFontName)
LINE = 12
TEXTSIZE = 12
HEADSIZE = 14

def loadJSON(context):
    doc = Document(w=W, h=H, originTop=False, context=context)
    view = doc.getView()
    view.showPadding = True
    view.showDimensions = True
    view.showOrigin = True

    page = doc[1]
    page.solve()
Ejemplo n.º 5
0
 def _get_font(self):
     if self._font is None:
         self._font = findFont(self.fontName)
     return self._font
Ejemplo n.º 6
0
# -----------------------------------------------------------------------------
#
#     AlterGlyphCoordinates.py
#
#     This script is using getContext(), so it should be able to run it with flatContext.
#

import pagebot
from pagebot import getContext
from pagebot.fonttoolbox.objects.font import findFont
from pagebot.toolbox.units import pt
from pprint import pprint

context = getContext()
EXPORT_PATH = '_export/AlteredGlyphWithPoints.pdf'
f = findFont('Amstelvar-Roman-VF') # Get PageBot Font instance of Variable font.

W = H = 1000

# Scale em of 2048 back to page size.
s = 0.5

# Offset of drawing origin.
context.translate(pt(100), pt(100))

# Open the font and get the glyph.
g = f['H']

# These are the points we have in the H:
print('List of APoints of the glyph:')
pprint(g.points)
TEMPLATE_PATH = '_local/2018-09-04_De_Volkskrant_-_04-09-2018.pdf'
#TEMPLATE_PAGE = '_local/2018-09-14_De_Volkskrant_-_14-09-2018.pdf'
PAGE_COUNT = 2  #context.numberOfImages(TEMPLATE_PATH)

# =============================================================================
#    Text content
#    For this example defined as strings. Should from from MarkDown file instead.
# .............................................................................

TITLE = 'The Variable Globe'

# =============================================================================
#    Fonts and Variable instances.
# .............................................................................

bodyFont = findFont('RobotoDelta-VF')
#print(bodyFont.axes) # Uncomment to see axes and values for this VF
location = dict(wght=700)
boldFont = bodyFont.getInstance(location)
headFont = findFont('AmstelvarAlpha-VF')
#print(headFont.axes) # Uncomment to see axes and values for this VF
# Create bold/title font as Variable location
kerning = {('V', 'a'): -100}
location = dict(wght=700, XTRA=350)
headBoldFont = headFont.getInstance(location, kerning=kerning)
location = dict(wght=650, XTRA=260)
headBoldCFont = titleFont = headFont.getInstance(location, kerning=kerning)

if 0:
    # Print the available axis names with the (min, default, max) values.
    print('Variable axes for bodyFont: ', bodyFont.axes)
Ejemplo n.º 8
0
from pagebot.fonttoolbox.objects.font import findFont, Font
from pagebot.toolbox.units import pt, upt
from pagebot.toolbox.color import noColor, color
from pagebot.contributions.filibuster.blurb import Blurb
from pagebot.constants import *
from pagebot.style import getRootStyle
from pagebot.contexts.base.babelstring import getFontPath

# TODO: move to basics when finished.

H, W = A3
W = pt(W)
H = pt(H)
M = 50

robotoRegular = findFont('Roboto-Regular')
pageBotBold = findFont('PageBot-Bold')
pageBotRegular = findFont('PageBot-Regular')
robotoBold = findFont('Roboto-Bold')
bungeeRegular = findFont('Bungee-Regular')
bungeeHairline = findFont('Bungee-HairlineRegular')
bungeeOutline = findFont('Bungee-OutlineRegular')


def drawBaselines(x0, y0, w, baselines, s, page):
    fontPath = getFontPath(s.style)
    font = Font(fontPath)
    infoLine = 1
    baseH0 = 0
    upem = font.getUpem()
    fontSize = s.style.get('fontSize')
Ejemplo n.º 9
0
#     Licensed under MIT conditions
#
#     Supporting DrawBot, www.drawbot.com
#     Supporting Flat, xxyxyz.org/flat
# -----------------------------------------------------------------------------
#
#     UseGlyphAnalyzer.py
#
#     Implements a PageBot font classes to get info from a TTFont.
#     Show the values that the GlyphAnalyzer get derive from font and glyph outline.
#   
from pagebot.fonttoolbox.objects.font import findFont
from pagebot import getContext

GLYPH_NAME = 'B'

context = getContext()
font = findFont('Georgia')
print(font.analyzer) 
print(font.analyzer.name) 
glyph = font[GLYPH_NAME]
ga = glyph.analyzer
print(ga)
print('Glyph horizontals width:', ga.width, ga.glyph.width, glyph.width)
print('Glyph bounding box:', ga.boundingBox)
# X position of vertical lines also includes sides of serifs.
print('x-position of verticals:', sorted(ga.verticals.keys()))
# Y position of horizontal lines
print('y-position of horizontals:', sorted(ga.horizontals.keys()))

Ejemplo n.º 10
0
context = getContext()

X0 = 100
Y0 = 100
WIDTH = 1600
HEIGHT = 1400
HBOX = 34
WBOX = 170
GAP = 20
HGAP = 60
P = 15
TEXTSIZE = pt(12)
OFFSET = 9

titleFont = findFont('BungeeInline-Regular')
font = findFont('Roboto-Regular')
boldFont = findFont('BungeeOutline-Regular')


def drawClassHierarchy(obj, colorRange, i):

    previous = None
    y = Y0
    x = X0

    for c in list(obj.__mro__)[::-1]:
        current = c.__name__
        #if current == 'object':
        #    continue
Ejemplo n.º 11
0
from pagebot.style import RIGHT
from pagebot.document import Document
from pagebot.typesetter import Typesetter
from pagebot.composer import Composer
from pagebot.elements import *
from pagebot.conditions import *

W, H = 1920, 1080

MD_PATH = u"WhatIsPageBot.md"
PADDING = 50
M = 310
T = 64
G = P = 24
FONT_NAME = 'MomentumSans-VF'
font = findFont(FONT_NAME)
fontPath = 'MomentumSans-TextMedium'

LOGO = 'TYPE NETWORK'
TITLE = 'What is PageBot? | April 2nd, 2018'

BG1 = 0.1
BG2 = BG3 = (1, 1, 1, 0.15)

CONTENT = [
    dict(head="""What is PageBot?""",
         image=((W - M, None), 'images/PageBotPage.png')),
    dict(
        head="""What is PageBot?""",
        content=
        "PageBot is a Python libary to script the creation of any type of publication in any design from any type of source, and save it to any format.\n\nMIT Open Source since July 2017."
Ejemplo n.º 12
0
PADDING = PT, PR, PB, PL = pt(40, 30, 30, 50)
G = pt(12)
COLUMNS = 4
CW = (W - PL - PR - G) / COLUMNS - G
CW2 = CW + G + CW
CW3 = CW2 + G + CW
CW4 = CW3 + G + CW

GH = pt(1)
COLUMNS = 4
RH = ()
GRID_X = ((CW, G), (CW, G), (CW, G), (CW, 0))

context = getContext()

fontRegular = findFont('Upgrade-Regular')
fontBold = findFont('Upgrade-Bold')

coverTitleStyle = dict(font=fontBold,
                       textFill=color(1, 0, 0),
                       fontSize=pt(100))

# Let the Magazine create a Finder instance, where to find resources, such as images.
m = Magazine(RESOURCES_PATH,
             size=(W, H),
             padding=PADDING,
             originTop=False,
             gridX=GRID_X,
             gridY=GRID_X,
             context=context)
Ejemplo n.º 13
0
#     TextBoxSideConditions2.py
#
#     Position fixed size textbox elements by their page side with conditions
#
# Document is the main instance holding all information about
# the document togethers (pages, styles, etc.)
from pagebot.document import Document
from pagebot.elements import newTextBox
from pagebot.toolbox.units import p, pt
from pagebot.toolbox.color import color, whiteColor
from pagebot.conditions import *
from pagebot.constants import *
from pagebot.fonttoolbox.objects.font import findFont

W = H = pt(500)
font = findFont('PageBot Regular')

doc = Document(w=W, h=H, originTop=False)
t = doc.context.newString('TEXT',
                          style=dict(font=font,
                                     fontSize=36,
                                     textFill=whiteColor,
                                     xTextAlign=CENTER))
PADDING = t.size[0]

page = doc[1]  # Get the single page from te document.
page.padding = PADDING

page.showPadding = True

newTextBox(t,
Ejemplo n.º 14
0
#
#     Supporting DrawBot, www.drawbot.com
# -----------------------------------------------------------------------------
#
#     testVariableTTFont.py
#
from pagebot.contexts.platform import getContext
from pagebot.document import Document
from pagebot.style import A4
from pagebot.fonttoolbox.objects.font import findFont
from pagebot.elements import newText
from pagebot.fonttoolbox.variablefontbuilder import getVarFontInstance

context = getContext()

f = findFont('Skia')

wghtMin, wghtDef, wghtMax = f.axes['wght']
wdthMin, wdthDef, wdthMax = f.axes['wdth']

#wghtMin, wghtDef, wghtMax = (-1, 0, 1)
#wdthMin, wdthDef, wdthMax = (-1, 0, 1)

print('wght %s %s %s' % (wghtMin, wghtDef, wghtMax))
print('wdth %s %s %s' % (wdthMin, wdthDef, wdthMax))


NORMAL = getVarFontInstance(f, dict(wght=wghtDef, wdth=wdthDef), styleName='Normal', normalize=False)
LIGHT = getVarFontInstance(f, dict(wght=wghtMin, wdth=wdthDef), styleName='Light', normalize=False)
BOLD = getVarFontInstance(f, dict(wght=wghtMax, wdth=wdthDef), styleName='Bold', normalize=False)
COND = getVarFontInstance(f, dict(wght=wghtDef, wdth=wdthMin), styleName='Cond', normalize=False)
Ejemplo n.º 15
0
from pagebot.toolbox.units import em

# For clarity, most of the MakeABookCover.py example document is setup
# as a sequential excecution of Python functions. For complex documents
# this is not the best method. More functions and classes will be used in the
# real templates, which are available from the PageBotTemplates repository.

W, H = B4
W -= 48  # Make a bit more narrow format.

BLEED = 8

# Export in folder that does not commit to Git. Force to export PDF.
EXPORT_PATH = '_export/AVarCover.pdf'

varFont = findFont('RobotoDelta-VF')
fontRegular = getVarFontInstance(varFont, dict(wdth=75))
#print(varFont.axes)
fontBold = varFont  #family.findFont('Bold')
fontItalic = varFont  #family.findFont('Italic')
ampersandFont = findFont('Georgia')


def makeDocument():
    """Demo random book cover generator."""

    # Create new document with (w,h) and fixed amount of pages.
    # Make number of pages with default document size.
    # Initially make all pages default with template
    # One page, just the cover.
    doc = Document(w=W,
Ejemplo n.º 16
0
from pagebot.typesetter import Typesetter
from pagebot.themes import ThemeClasses, BaseTheme, DEFAULT_THEME_CLASS
from pagebot.fonttoolbox.objects.font import findFont
from pagebot.conditions import *
from pagebot.document import Document
from pagebot.toolbox.units import inch, pt
from pagebot.toolbox.color import color
from pagebotcocoa.apps.baseapp import BaseApp
from pagebotcocoa.contexts.drawbot.drawbotcontext import DrawBotContext
from drawBot.ui.drawView import DrawView

ADD_MENU = True

context = DrawBotContext()

fontRegular = findFont('PageBot-Regular')
fontBold = findFont('PageBot-Bold')

redColor = color('red')
headStyle = dict(font=fontRegular, fontSize=pt(4))

MD_SAMPLE_PATH = getResourcesPath() + '/texts/SAMPLE.md'
UNTITLED_PUBLICATION = 'Untitled Publication #%d'

MENUS = (
    ('File', 100, 'fileMenu', (
        ('New publication', 'newPublication'),
        ('New page', 'newPage'),
        ('Open...', 'openPublication'),
        ('Close', 'closePublication'),
        ('Save', 'savePublication'),
Ejemplo n.º 17
0
def testFlatContext():
    context = getContext('Flat')

    # PageBot implementation, to be used for strings and styles.
    pagebotFont = findFont(FONTNAME)
    pagebotFill = color((180.0 / 255, 0, 125.0 / 255))
    pagebotStroke = color(100.0 / 255, 180.0 / 255, 0)

    # Native flat implementation of fonts and colors.
    flatFont = font.open(pagebotFont.path)
    flatFill = rgb(180, 0, 125)
    flatStroke = rgb(100, 180, 0)

    # Stroke width is the same.
    strokeWidth = 1

    ''' Creates a document. '''

    # Creating a Flat document.
    flatDoc = document(WIDTH, HEIGHT, 'pt')
    flatPage = flatDoc.addpage()

    # Pagebot equivalent.
    context.newDrawing(WIDTH, HEIGHT)
    pbPage = context.newPage()
    print(pbPage)

    ''' Draws a figure. '''

    # Flat.
    #figure = shape().fill(flatFill).stroke(flatStroke).width(strokeWidth)
    #r = figure.rectangle(50, 50, 20, 20)
    #p.place(r)

    # Pagebot.
    #context.fill(pagebotFill)
    #context.stroke(pagebotStroke)
    #context.strokeWidth(strokeWidth)
    #context.rect(50, 50, 20, 20)

    #print(p.items[0].item.style.width)
    #print(context.pages[0].items[0].item.style.width)

    #s = context.pages[0].items[0]

    #print(s.item.style.fill)
    #print(s.item.style.stroke)
    #print(s.item.style.join)
    #print(s.item.style.limit)

    ''' Draws text. '''

    msg = 'Hello world!'

    # Flat.

    header = strike(flatFont).color(flatStroke).size(FONTSIZE, LEADING, units='pt')
    t = header.text(msg)
    placedText = flatPage.place(t).frame(100, 100, 380, 80)

    # Pagebot.
    style = dict(font=pagebotFont, fontSize=FONTSIZE, textFill=pagebotStroke,
            leading=LEADING)
    bs = context.newString(msg, style=style)
    context.text('bla', (50, 100)) # TODO: also for native flat.
    context.text(bs, (100, 100))


    #print(headline.style.size)
    #print(headline.style.leading)
    #print(headline.style.color.r)
    #print(headline.style.color.g)

    # Now for conditions and elements.
    c = (Left2Left(), Fit2Right(), Float2Top())
    style = dict(fontSize=14, font=pagebotFont)
    msg = 'Testing textBox'
    print(msg)
    bs = context.newString(msg, style=style)
    print(type(bs))

    newTextBox(bs, font=pagebotFont, parent=pbPage, conditions=c, fill=0.9,
            margin=4)
    #print(p.items)

    ''' Exports file. '''

    im = flatPage.image(kind='rgb')


    # TODO:
    #imagePath = getResourcesPath() + '/images/peppertom_lowres_398x530.png'
    #size = context.imageSize(imagePath)
    #print(size)

    if not os.path.exists('_export'):
        os.mkdir('_export')

    #print('Exporting native')
    flatDoc.pdf('_export/native-flat.pdf')
    #im.png('_export/native-flat.png')
    #im.jpeg('_export/native-flat.jpg')
    #p.svg('_export/native-flat.svg')
    #print(context.doc)

    context.saveDrawing('_export/pagebot-flat.pdf')
Ejemplo n.º 18
0
from pagebot.elements import *
from pagebot.fonttoolbox.objects.font import findFont
from pagebot.toolbox.units import inch, em, pt
from pagebot.toolbox.color import color
from pagebot.constants import LEFT, RIGHT
from pagebot.conditions import *

from metrics import *

SHOW_TEMPLATE = True

TEMPLATE_PDF = '../../../Design_TYPE-3/Noordzij_Layout-02_rb_TYPE-3.pdf'
TEMPLATE_PDF = '../Dropbox/Production_TYPE-3/2_Layouts__TYPE-3/People_Layout-01_rb_TYPE-3.pdf'
TEMPLATE_PDF = '/Users/petr/Dropbox/Production_TYPE-3/2_Layouts__TYPE-3/People_Layout-01_rb_TYPE-3.pdf'

titleBold = findFont('Upgrade-Bold')
titleSemibold = findFont('Upgrade-Semibold')
titleRegular = findFont('Upgrade-Regular')
titleFont = findFont('Upgrade-Thin')
bookFont = findFont('Upgrade-Book')

headline = findFont('Upgrade-Medium')
headline2 = findFont('Upgrade-Regular')
headlineItalic = findFont('Upgrade-Italic')
bodyText = findFont('Proforma-Book')
bosyTextBold = findFont('Proforma-Semibold')
bodyTextItalic = findFont('Proforma-BookItalic')

headline = findFont('PageBot-Light')

styles = dict(
Ejemplo n.º 19
0
f = Color(1, 0, 0)
wbox = 300
hbox = 400

blurb = Blurb()
context = getContext('DrawBot')
context.newDrawing()
context.newPage(W, H)
x = 0
y = 0
context.text('(%s, %s)' % (x, y), (x, y))
x = W / 2
y = H - hbox
context.text('(%s, %s)' % (x, y), (x, y))
b = blurb.getBlurb('stylewars_documentary')[:200]
font = findFont('Bungee-Regular')
style = dict(font=font, fontSize=pt(18), textFill=color(0.5, 1, 0))
bs = context.newString(b, style=style)
lines = bs.getTextLines(w=wbox, h=hbox)
attrString = bs.s.getNSObject()
setter = CTFramesetterCreateWithAttributedString(attrString)
path = CGPathCreateMutable()
CGPathAddRect(path, None, CGRectMake(0, 0, wbox, hbox))
ctBox = CTFramesetterCreateFrame(setter, (0, 0), path, None)
ctLines = CTFrameGetLines(ctBox)
origins = CTFrameGetLineOrigins(ctBox, (0, len(ctLines)), None)
context.fill(None)
context.stroke(f)
context.rect(PADDING, H, wbox, -hbox)
context.fill(f)
Ejemplo n.º 20
0
            bs = c.newString(self.sampleText, style=style)
            tw, th = bs.textSize()
            c.text(bs, (self.w/2 - tw/2, self.h/2-th/8)) # /8 vert
            
            style['fontSize'] = style['location']['opsz'] * 4
            style['font'] = instance
            bs = c.newString('%s %dpt' % (self.sampleText, style['fontSize']), style=style)
            tw, th = bs.textSize()
            c.text(bs, (self.w/2 - tw/2, self.h/4-th/8)) 
     
c = DrawBotContext()
W, H = 2040, 1020 # Type Network banners

# Claire: for now, add your Fit-Variable_1.ttf to your /Library/Fonts and it can be found.
#Gimlet_Italics-VF.ttf
#Gimlet_Romans-VF.ttf
font = findFont('AlliumMediumVARGX_hyphen')
print(font)
# Fit axes to select from: here we are showing the optical size.
# Define tag list for axes to be part of the animation as sequence
sequenceAxes = ['opsz']
sequenceLength = 3 # Seconds per sequence
sequences = len(sequenceAxes) # Amount of sequences, one per axis
duration = sequenceLength * len(sequenceAxes) # Total duration of the animation in seconds
framesPerSecond = 12
frameCnt = duration * framesPerSecond # Total number of frames
axisFrames = sequenceLength * framesPerSecond # Number of frames per axis sequence.

# Create a new doc, with the right amount of frames/pages.
doc = Document(w=W, h=H, originTop=False, frameDuration=1.0/framesPerSecond, 
    autoPages=frameCnt, context=c)
Ejemplo n.º 21
0
        x = x1 - R / 2 + R / 8
        y = self.h / 2 - R / 2
        c.oval(x, y, R, R)
        c.line((x - L / 2 + 2, y + R / 2), (x - R + 2 * L, y + R / 2))

        # Large "Opt" on the left
        style['fontSize'] = self.vfFont.axes['opsz'][2] * magnifySizeFactor
        bs = c.newString(self.sampleText[:3], style=style)
        tw2, th2 = bs.size
        x2, y2 = self.w / 2 - tw2, self.h / 2 - th2 / 5
        c.text(bs, (x2, y2))  # Make tekst right aligned


c = DrawBotContext()
W, H = 2040, 1020  # Type Network banners
font = findFont('AmstelvarAlpha-VF')
# Amstelvar axes to select from: here we are showing the optical size.
# Define tag list for axes to be part of the animation as sequence
sequenceAxes = ['opsz']
sequenceLength = 3  # Seconds per sequence
sequences = len(sequenceAxes)  # Amount of sequences, one per axis
duration = sequenceLength * len(
    sequenceAxes)  # Total duration of the animation in seconds
framesPerSecond = 10
frameCnt = duration * framesPerSecond  # Total number of frames
axisFrames = sequenceLength * framesPerSecond  # Number of frames per axis sequence.

fontSizeFactor = 3  # Enlarge the [opsz] font size by this factor.
magnifySizeFactor = 8  # Enlarge magnified word by this factor, compared to the max value of [opsz]

# Create a new doc, with the right amount of frames/pages.
Ejemplo n.º 22
0
        c.text(bs, (self.w / 2 - tw / 2, self.h / 3 + 20))

        # Now make instance and draw over regular and add to new copy of the style
        style = self.style.copy()
        instance = self.f.getInstance(self.style['location'])
        style['font'] = instance.path
        #print(self.frameIndex, style['font'])
        #style['fontSize'] = self.h/3
        bs = c.newString(self.sampleText, style=style)
        tw, th = bs.size
        c.text(bs, (self.w / 2 - tw / 2, self.h / 3 + 20))


c = DrawBotContext()
w, h = 2040, 1020  # Type Network banners
font = findFont('DecovarAlpha-VF')
# Decovar axes to select from
# 'BLDA' Inline
# 'TRMG' Serif terminals
# 'BLDB' Turning flourishes
# 'SKLA' Blocked inside
# 'SKLD' Striped stems
# 'TRMA' Rounded
# 'SKLB' Turning round flourishes
# 'TRMC' Round terminal serifs
# 'TRMB' Sharp terminal serifs
# 'TRME' Split sharp terminal serifs
# 'TRMD' Angled terminals
# 'WMX2' Contrast width black
# 'TRMF' Plus terminals
# 'TRMK' Rectangle inside terminal
Ejemplo n.º 23
0
            if the axis exists.

            """
        ox, oy, _ = origin
        c = self.context
        # Now make fitting text instance
        bs = c.fitString(self.sampleText, style=self.style, w=self.w, h=self.h)
        tx, ty, _, _ = bs.bounds()
        c.text(bs, (ox - tx, oy - ty))


c = DrawBotContext()
W, H = 2040, 1020  # Type Network banners
M = 30
# Claire: for now, add your Fit-Variable_1.ttf to your /Library/Fonts and it can be found.
font = findFont('Fit-Variable_1')
# Fit axes to select from: here we are showing the optical size.
# Define tag list for axes to be part of the animation as sequence
sequenceAxes = ['wdth']
sequenceLength = 3  # Seconds per sequence
sequences = 4  # Amount of sequences in choreography
duration = sequenceLength * sequences  # Total duration of the animation in seconds
framesPerSecond = 10  # 2 for testing
frameCnt = duration * framesPerSecond  # Total number of frames
axisFrames = sequenceLength * framesPerSecond  # Number of frames per axis sequence.

# Create a new doc, with the right amount of frames/pages.
doc = Document(w=W,
               h=H,
               originTop=False,
               frameDuration=1.0 / framesPerSecond,
Ejemplo n.º 24
0
        # Now make instance and draw over regular and add
        # to new copy of the style

        style = self.style.copy()
        instance = self.f.getInstance(self.style['location'])
        style['font'] = instance.path
        #print(self.frameIndex, style['font'])
        #style['fontSize'] = self.h/3
        bs = c.newString(self.sampleText, style=style)
        tw, th = bs.size
        c.text(bs, (self.w / 2 - tw / 2, self.h / 3 + 20))


c = DrawBotContext()
w, h = 2040, 1020  # Type Network banners
font = findFont('RobotoDelta-VF')
print(font.axes)
# Roboto axes to select from
# wdth - overall width
# wght - overall weight
# opsz - optical size
# YOPQ
# YTRA
# YTAS - ascender
# YTDE - descender
# YTDD
# YTUC - capitals
# YTLC - xHeight
# XTRA - change width, keep stems the same
# YTAD
# XOPQ - change stems, keep counters the same
Ejemplo n.º 25
0
#
#     Implements a PageBot font classes to get info from a TTFont.
#     Show drawing of outline points and intersection beam with flattened path
#
from random import random

from pagebot.fonttoolbox.objects.font import findFont
from pagebot import getContext
from pagebot.toolbox.color import color, noColor, blackColor

c = getContext()

c.newPage(2000, 550)
c.scale(0.5)

font = findFont('PageBot-Bold')
print(font.analyzer)
print(font.analyzer.name)


def drawGlyph(px, py, glyph):
    ga = glyph.analyzer
    # Three ways to access the glyph metrics
    #print('Glyph width:', ga.width, ga.glyph.width, glyph.width)
    #print('Glyph bounding box:', ga.boundingBox)
    # X position of vertical lines also includes sides of serifs.
    #verticals = sorted(ga.verticals.keys())
    #print('x-position of detected verticals:', verticals)
    # Y position of horizontal lines
    #horizontals = sorted(ga.horizontals.keys())
    #print('y-position of deteted horizontals:', horizontals)
Ejemplo n.º 26
0
from pagebot.conditions import *
from pagebot.fonttoolbox.objects.font import findFont
from pagebot.contexts.strings.babelstring import BabelString
from pagebot.contexts.strings.drawbotstring import DrawBotString
from pagebot.contexts.strings.flatstring import FlatString
from pagebot.toolbox.units import pt
from pagebot.toolbox.color import noColor, color
from pagebot.contributions.filibuster.blurb import Blurb
from pagebot.constants import *
W, H = A5
H = pt(H)
W = pt(W)
M = 100
s = 36

roboto = findFont('Roboto-Regular')
robotoBold = findFont('Roboto-Bold')
bungee = findFont('BungeeHairline-Regular')

blurb = Blurb()
txt = blurb.getBlurb('news_headline', noTags=True)

testContexts = (
    (DrawBotContext(), '_export/testDrawBotString.pdf'),
    #(FlatContext(), '_export/testFlatString.pdf'),
    #(InDesignContext(), '_export/testInDesignString.pdf'),
    #(HtmlContext(), '_export/testHtmlString.pdf'),
    #(InDesignContext(), '_export/testInDesignString.pdf'),
    #(IdmlContext(), '_export/testIdmlString.pdf')
)
Ejemplo n.º 27
0
    frameIndex = 1 # Same as page index in the document
    for axisTag in sequenceAxes:

        minValue, defaultValue, maxValue = font.axes[axisTag]
        for axisFrameIndex in range(axisFrames):
            page = doc[frameIndex] # Get the current frame-page
            page.w = W

            axisRange = maxValue - minValue
            phisin = sin(radians(axisFrameIndex/axisFrames * 360+3/4*360))*0.5+0.5
        
            # Variable Font location for this frame sample
            location = {axisTag: phisin*axisRange+minValue}
            # Overall style for the frame
            style = dict(leading=em(1.4), fontSize=H-40, xTextAlign=RIGHT, textFill=whiteColor, 
                fill=blackColor, location=location)
        
            af = AnimatedBannerFrame(sample, font, frameCnt, frameIndex, parent=page, style=style, 
                w=page.pw, h=page.ph, context=c)
            frameIndex += 1 # Prepare for the next frame

    doc.solve()
    doc.export('_export/%s_%s.gif' % (font.info.familyName, sample))

font = findFont('Gimlet_Italics-VF')
if font is None:
    print('Gimlet_Italics-VF not found.')
else:
    makeBanner(font)

Ejemplo n.º 28
0
    def drawAnimatedFrame(self, view, origin, **kwargs):
        """Draw the content of the element, responding to size, styles, font
        and content.  Create 2 columns for the self.fontSizes ranges that show
        the text with and without [opsz] if the axis exists."""
        wdthMin, wdthDefault, wdthMax = self.f.axes['wdth']
        wghtMin, wghtDefault, wghtMax = self.f.axes['wght']

        ox, oy, _ = origin
        c = self.context
        style = self.style.copy()
        #location = getScaledLocation(self.f, dict(wght=self.frameIndex/self.frames))
        #instance = getInstance(self.f, location)
        phisin = sin(radians(self.frameIndex / self.frames * 360))
        phicos = cos(radians(self.frameIndex / self.frames * 360))

        style['textFill'] = color(1 - phicos * 0.3 + 0.5)
        # TODO: Not the right instance-weight is shown in export.
        wdthRange = wdthMax - wdthMin
        wghtRange = wghtMax - wghtMin
        location = dict(wdth=phisin * wdthRange / 2 + wdthRange / 2 + wdthMin,
                        wght=phisin * wghtRange / 2 + wghtRange / 2 + wghtMin)
        instance = self.f.getInstance(location)  #instance.path
        style['font'] = instance.path
        #style['fontSize'] = self.h/3
        bs = c.newString(self.sampleText, style=style)
        tw, th = bs.textSize
        c.text(bs, (self.w / 2 - tw / 2, self.h / 2))
        glyph = instance['ampersand']
        c.save()
        c.stroke(color(0), pt(0.25))
        gray = phisin * 0.3 + 0.5
        c.fill(color(gray, gray, 1 - gray, 0.6))
        s = 0.4
        c.scale(s)
        c.drawPath(c.getGlyphPath(glyph),
                   ((ox + self.pl) / s, (oy + self.ph / 4) / s))
        c.restore()

        # FIXME: should get local path using findFont(), but axis seem to be specific to
        # Bitcount.
        #path = "/Users/petr/Desktop/TYPETR-git/TYPETR-Bitcount-Var/variable_ttf/BitcountTest_DoubleCircleSquare4-VF.ttf"
        #f = Font(path)
        f = findFont('RobotoDelta-VF')

        if 'SHPE' in f.axes:
            SHPEMin, SHPEDefault, SHPEMax = f.axes['SHPE']
            SHPERange = SHPEMax - SHPEMin
            wghtMin, wghtDefault, wghtMax = self.f.axes['wght']
            wghtRange = wghtMax - wghtMin
            location = dict(
                SHPE=phisin * SHPERange / 2 + SHPERange / 2 + SHPEMin,
                wght=phicos * wghtRange / 2 + wghtRange / 2 + wghtMin)
            instance = f.getInstance(location)  #instance.path
            glyph = instance['A']
        """
        path = "/Users/petr/Desktop/TYPETR-git/TYPETR-Bitcount-Var/variable_ttf/BitcountTest_DoubleCircleSquare2-VF.ttf"
        f = Font(path)
        SHPEMin, SHPEDefault, SHPEMax = f.axes['SHPE']
        SHPERange = SHPEMax - SHPEMin
        wghtMin, wghtDefault, wghtMax = self.f.axes['wght']
        wghtRange = wghtMax - wghtMin
        location = dict(SHPE=phisin*SHPERange/2+SHPERange/2+SHPEMin, wght=phicos*wghtRange/2+wghtRange/2+wghtMin)
        instance = f.getInstance(location)#instance.path
        glyph = instance['A']
        """
        c.save()
        c.stroke(color(1, 0, 0), pt(0.25))
        gray = phisin * 0.3 + 0.7
        c.fill(color(gray, gray, gray, 0.8))
        s = 1
        c.scale(s)
        c.drawPath(c.getGlyphPath(glyph),
                   ((ox + self.w / 2 + self.pl) / s, (oy + self.ph / 4) / s))
        c.restore()
Ejemplo n.º 29
0
#
#     Implements a PageBot font classes to get info from a TTFont.
#     Show drawing of outline points and intersection beam with flattened path
#
from pagebot.fonttoolbox.objects.font import findFont
from pagebot.contexts.platform import getContext
from pagebot.toolbox.color import color, noColor, blackColor

GLYPH_NAME = 'B'  # 'ampersand'

c = getContext()

c.newPage(1000, 1000)
c.scale(0.5)

font = findFont('Roboto-Regular')
print(font.analyzer)
print(font.analyzer.name)
glyph = font[GLYPH_NAME]
ga = glyph.analyzer
# Three ways to access the glyph metrics
print('Glyph width:', ga.width, ga.glyph.width, glyph.width)
print('Glyph bounding box:', ga.boundingBox)
# X position of vertical lines also includes sides of serifs.
verticals = sorted(ga.verticals.keys())
print('x-position of detected verticals:', verticals)
# Y position of horizontal lines
horizontals = sorted(ga.horizontals.keys())
print('y-position of deteted horizontals:', horizontals)

c.stroke(blackColor, 1)
Ejemplo n.º 30
0
    style = dict(font=font, fontSize=H2_FONTSIZE, leading=H2_FONTSIZE * 1.4)
    bs = context.newString(blurbHeadline + '\n', style=style)

    style = dict(font=font, fontSize=P_FONTSIZE, leading=P_FONTSIZE * 1.4)
    bs += context.newString(blurbArticle, style=style)
    newTextBox(bs,
               h=page.ph,
               w=page.pw / 2 - pt(12),
               conditions=[Right2Right(), Top2Top()],
               parent=page)


# ------------------------------------

page = None
FONTS = (
    'Roboto-Regular',
    'Roboto-Bold',
)
for fontName in FONTS:
    if page is None:
        page = doc[1]
    else:
        page = page.next
    font = findFont(fontName)
    buildPage(page, font)
    page.solve()

doc.export('_export/OurTypeSpeciment.pdf')