示例#1
0
def showAll():
    """Shows all fonts that are shipped with PageBot."""
    context = getContext()
    doc = Document(w=W, h=H, originTop=False, autoPages=1, context=context)
    page = doc[1]
    page.padding = P
    
    c1 = (Left2Left(), Fit2Right(), Float2Top()) # Group condition
    c2 = (Left2Left(), Float2Top()) # Title condition    
    c3 = (Right2Right(), Float2Top()) # Speciment condition

    families = getFamilyPaths()
    fam = findFamily('Roboto')
    print(fam)
    fam = getFamily('Bungee')
    print(fam)

    fam = getFamily('BungeeOutline')
    print(fam)

    fam = getFamily('Roboto')

    #verboseFam(fam)
    fam = getFamily('RobotoCondensed')
    verboseFam(fam)

    fam = getFamily('PageBot')
    print(fam)

    for s in fam.getStyles():
        print(' - %s' % s)

    #print(families)
    print('Number of families found: %d' % len(families))
    fontPaths = getFontPaths()
    print('Number of fonts found: %d' % len(fontPaths))
    tfp = getTestFontsPath()
    pbFonts = getPageBotFontPaths()
    print('Number of fonts shipped with PageBot: %d' % len(pbFonts))
    #print(sorted(pbFonts.keys()))
    font = findFont('Roboto-Black')
    print('The Font object from the pagebot.fonttoolbox.objects module: %s' % font)
    print('It has %d glyphs.' % len(font))
    i = 0

    for pbFont in sorted(pbFonts.keys()):
        if 'Bungee' in pbFont or 'PageBot' in pbFont: # Filter some of the PageBot fonts.
            f = findFont(pbFont)
            if f is not None:
                i += 1
                g = newGroup(parent=page, conditions=c1, padding=7, borderTop=1, strokeWidth=0)
                newText('%s\n' % pbFont, parent=g, conditions=c2, fontSize=16, strokeWidth=0)
                newText('ABCDEabcde012345', parent=g, conditions=c3, font=f, fontSize=pt(44), strokeWidth=0)
        if i > 10:
            page = page.next
            page.padding = P
            i = 0
                
    doc.solve()
    doc.export('_export/Fonts.pdf')
def fit():
    varFont = findFont('RobotoDelta-VF')
    print(varFont.axes)
    condensedFont = getVarFontInstance(varFont, dict(wdth=75, YTUC=528))
    wideFont = getVarFontInstance(varFont, dict(wdth=125, YTUC=528))
    boldFont = getVarFontInstance(varFont, dict(wght=900, GRAD=1))

    W, H = 500, 500
    PADDING = 56
    COL = 40
    
    doc = Document(w=W, h=H, originTop=False)
    view = doc.view
    context = view.context

    page = doc[1] # Get page on pageNumber, first in row (this is only one now).
    page.padding = PADDING

    s = 'a'

    fontSize = 32

    for ix in range(10):
        for iy in range(10):

            instance = getVarFontInstance(varFont, dict(wdth=75, YTUC=528))
                
            style = dict(font=instance, fontSize=fontSize, leading=fontSize)
            bs = context.newString(s, style=style)
            tw, th = bs.size
            newText(bs, x=page.pl+ix*COL, y=page.pb+iy*COL, w=COL, h=COL, parent=page)

    doc.export(EXPORT_PATH)
示例#3
0
def makeDocument():
    # Creates the publication/document that holds the pages.
    doc = Document(w=W, h=H, originTop=False, autoPages=1)

    # Gets page by pageNumber, first in row (at this point there is only one in
    # this row).
    page = doc[1]
    page.padding = PADDING
    page.showPadding = True

    conditions = [Right2Right(), Float2Top(), Float2Left()]
    # TODO: Solve this bug, does not mirror.
    conditions = (Left2Left(), Float2Top(), Float2Right())
    numberOfSquares = 88
    ratio = 1 / numberOfSquares

    for n in range(numberOfSquares):
        newRect(w=RW,
                h=RH,
                parent=page,
                fill=color(1 - n * ratio, 0, 0.5),
                conditions=conditions,
                margin=0)

    # Recursively solve the conditions in all page child elements..
    # If there are failing conditions, then the status
    # is returned in the Score instance.
    score = doc.solve()
    # Export to various export formats
    for exportPath in EXPORT_PATHS:
        doc.export(exportPath)
示例#4
0
def makeAnimation(font, w, h, c, magnifySizeFactor):
    # 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.

    # 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)
    # Sample text to show in the animation
    sample = 'Optical size'  #font.info.familyName #'Decovar'

    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

            phisin = sin(
                radians(axisFrameIndex / axisFrames * 360 +
                        3 / 4 * 360)) * 0.5 + 0.5
            fontSize = phisin * (maxValue - minValue) + minValue

            # Variable Font location for this frame sample
            variableLocation = {axisTag: fontSize}
            # Overall style for the frame
            style = dict(leading=em(1.4),
                         fontSize=fontSize * fontSizeFactor,
                         xTextAlign=RIGHT,
                         textFill=color(1),
                         stroke=None,
                         fill=blackColor,
                         variableLocation=variableLocation)

            af = AnimatedBannerFrame(sample,
                                     font,
                                     frameCnt,
                                     frameIndex,
                                     parent=page,
                                     style=style,
                                     w=page.w,
                                     h=page.h,
                                     context=c)
            af.magnifySizeFactor = magnifySizeFactor
            frameIndex += 1  # Prepare for the next frame

    doc.solve()
    doc.export('images/%s_OpticalSize.gif' % font.info.familyName)
示例#5
0
def fit():
    varFont = findFont('RobotoDelta-VF')
    print(varFont.axes)
    condensedFont = getVarFontInstance(varFont, dict(wdth=75, YTUC=528))
    wideFont = getVarFontInstance(varFont, dict(wdth=125, YTUC=528))
    boldFont = getVarFontInstance(varFont, dict(wght=900, GRAD=1))

    W, H = 500, 400
    PADDING = 8

    doc = Document(w=W, h=H, originTop=False)
    view = doc.view
    context = view.context

    page = doc[1] # Get page on pageNumber, first in row (this is only one now).
    page.padding = PADDING

    s = 'Variable'

    labelStyle = dict(font=varFont.path, fontSize=8, textFill=(1, 0, 0),
        leading=8)

    conditions1 = [Left2Left(), Top2Top()]
    conditions2 = [Left2Left(), Float2Top()]
    
    fontSize = 80
    style = dict(font=varFont.path, fontSize=fontSize, leading=fontSize)
    bs = context.newString(s, style=style)
    tw, th = bs.size
    newText(bs, w=W-2*PADDING, h=th*1.2, parent=page,
        conditions=conditions1)
    labelS = context.newString('Original var-font %0.2fpt' % (bs.fontSize), style=labelStyle)
    newText(labelS, parent=page,
        conditions=conditions2)

    style = dict(font=condensedFont.path, fontSize=fontSize, leading=fontSize)
    bs = context.newString(s, style=style)
    tw, th = bs.size
    newText(bs, w=W-2*PADDING, h=th*1.2, parent=page, conditions=conditions2)
    labelS = context.newString('Wide %0.2fpt %s' % (bs.fontSize, wideFont.info.location), style=labelStyle)
    newText(labelS, parent=page, conditions=conditions2)

    style = dict(font=wideFont.path, fontSize=fontSize, leading=fontSize)
    bs = context.newString(s, style=style)
    tw, th = bs.size
    newText(bs, w=W-2*PADDING, h=th*1.2, parent=page, conditions=conditions2)
    labelS = context.newString('Wide %0.2fpt %s' % (bs.fontSize, wideFont.info.location), style=labelStyle)
    newText(labelS, parent=page, conditions=conditions2)

    style = dict(font=boldFont.path, fontSize=fontSize, leading=fontSize)
    bs = context.newString(s, style=style)
    tw, th = bs.size
    newText(bs, w=W-2*PADDING, h=th*1.2, parent=page, 
        conditions=conditions2)
    labelS = context.newString('Bold %0.2fpt %s' % (bs.fontSize, boldFont.info.location), style=labelStyle)
    newText(labelS, parent=page, conditions=conditions2)
    
    page.solve()
    doc.export(EXPORT_PATH)
示例#6
0
def main():
    #print _drawBotDrawingTool._tempInstalledFonts
    template = Template(w=W, h=H, padding=PADDING)

    doc = Document(title="sample", w=W, h=H, autoPages=1, originTop=False,
        pageTemplate=template, startPage=1)
    view = doc.getView()
    view.padding = 40

    page1 = doc[0]

    for ypos, ytch in enumerate(range(200, 800+1, 200)):
        for xpos, xtch in enumerate(range(200, 800+1, 200)):
            f = getVariableFont(FONT_PATH, location=dict(xtch=xtch, ytch=ytch))
            newText("我H", point=(70*xpos, 750-40*ypos), parent=page1, name="", font=f.installedName, fontSize=40)
    doc.solve()
    doc.export(EXPORT_PATH)
示例#7
0
def run():
    doc = Document(w=W, h=H)
    page = doc[1]
    c = newRect(parent=page,
                name='myContainerElement',
                x=100,
                y=100,
                w=page.w / 2,
                h=page.h / 2,
                fill=(1, 0, 0))

    print('Container we made:' + str(c))
    print('No elements yet:' +
          str(c.elements))  # Currently no elements in the container
    child1 = newRect(parent=c, name='Child1',
                     fill=(1, 1, 0))  # Make child containers with unique Id
    child2 = newRect(parent=c, name='Child2', fill=(1, 0, 1))
    # Get unique element eIds
    eId1 = child1.eId
    eId2 = child2.eId
    print('-- Now the container got 2 named child containers.')
    print('Elements:' +
          str(c.elements))  # Currently no elements in the container
    print('-- None of the children are placed on default position (0, 0, 0)')
    for e in c.elements:
        print(e.name, e.x, e.y, e.z)
    print(
        '-- Place the Child1 element on a fixed position (x,y), z is undefined/untouched'
    )
    child1.x = 20
    child1.y = 30
    child1.z = 100
    print(child1)
    print(
        '-- Place the same Child2 element on another fixed position (x,y,z), a point tuple.'
    )
    child2.point = (120, 30, 20)
    print(child2)
    print(
        '-- The container behaves as a dictionary of child elements with e.eId as key.'
    )
    print(c[eId1])
    print(c[eId2])

    doc.export('_export/UseContainerElements.pdf')
示例#8
0
def fit():
    varFont = findFont('RobotoDelta-VF')
    print(varFont.axes)
    wideFont = getVarFontInstance(varFont, dict(wdth=125, YTUC=528))
    boldFont = getVarFontInstance(varFont, dict(wght=900, GRAD=1))

    W, H = 500, 350
    PADDING = 20

    doc = Document(w=W, h=H, originTop=False)
    view = doc.view
    context = view.context

    page = doc[
        1]  # Get page on pageNumber, first in row (this is only one now).
    page.padding = PADDING

    s = 'ABCDEF'

    labelStyle = dict(font=varFont.path, fontSize=8, textFill=(1, 0, 0))

    style = dict(font=varFont.path, fontSize=10)
    bs = context.newString(s, style=style, w=W - 2 * PADDING)
    newText(bs, x=20, y=180, w=W - 2 * PADDING, h=H, parent=page)
    labelS = context.newString('Original var-font %0.2fpt' % (bs.fontSize),
                               style=labelStyle)
    newText(labelS, x=20, y=220, parent=page)

    style = dict(font=wideFont.path, fontSize=10)
    bs = context.newString(s, style=style, w=W - 2 * PADDING)
    newText(bs, x=20, y=100, w=W - 2 * PADDING, h=H, parent=page)
    labelS = context.newString('Wide %0.2fpt %s' %
                               (bs.fontSize, wideFont.info.location),
                               style=labelStyle)
    newText(labelS, x=20, y=130, parent=page)

    style = dict(font=boldFont.path, fontSize=10)
    bs = context.newString(s, style=style, w=W - 2 * PADDING)
    newText(bs, x=20, y=-30, w=W - 2 * PADDING, h=H, parent=page)
    labelS = context.newString('Bold %0.2fpt %s' %
                               (bs.fontSize, boldFont.info.location),
                               style=labelStyle)
    newText(labelS, x=20, y=10, parent=page)

    doc.export(EXPORT_PATH)
示例#9
0
def makeBanner(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 = ['wdth']
    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.

    # 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)
    # Sample text to show in the animation
    sample = 'Fitting' 

    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))
示例#10
0
def makeDocument():
    # Creates the publication/document that holds the pages.
    doc = Document(w=W, h=H, originTop=False, autoPages=1)
    doc.view.padding = 0  # Don't show cropmarks in this example.
    doc.view.showPadding = True

    # Gets page by pageNumber, first in row (at this point there is only one in
    # this row).
    page = doc[1]
    page.padding = 30

    conditions = [Right2Right(), Float2Top(), Float2Left()]
    # TODO: Solve this bug, does not mirror.
    #conditions = [Left2Left(), Float2Top(), Float2Right()]

    for n in range(32):
        newRect(w=40,
                h=42,
                mr=4,
                mt=4,
                parent=page,
                fill=color(random() * 0.5 + 0.5, 0, 0.5),
                conditions=conditions)

    # Recursively solve the conditions in all pages.
    # If there are failing conditions, then the status
    # is returned in the Score instance.
    score = doc.solve()
    if score.fails:
        print(score.fails)

    doc.export(EXPORT_PATH_SVG)
    doc.export(EXPORT_PATH_JPG)
    doc.export(EXPORT_PATH_PNG)
    doc.export(EXPORT_PATH_PDF)

    print('Done making document %s' % doc)
示例#11
0
        page = doc[frameIndex]  # Get the current frame-page

        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=240,
                     textFill=(0, 0, 0),
                     fill=.8,
                     location=location)

        print(style)

        af = AnimatedBannerFrame(sample,
                                 font,
                                 frameCnt,
                                 frameIndex,
                                 parent=page,
                                 style=style,
                                 w=page.w,
                                 h=page.h,
                                 context=c)
        frameIndex += 1  # Prepare for the next frame

doc.solve()
doc.export('_export/%s_%s.gif' % (font.info.familyName, sample))
示例#12
0
def loadJSON(context):
    doc = Document(w=W, h=H, originTop=False, context=context)
    #doc = Document(w=W, h=H, originTop=True, context=context)
    view = doc.getView()
    view.showPadding = True
    view.showDimensions = True
    view.showOrigin = True

    page = doc[1]

    base = os.path.abspath(__file__)
    d = os.path.dirname(base)
    src = '/jsondata/AMXP--119s014.json'
    p = d + src
    f = open(p, 'r')
    jsondata = f.read()
    jsondict = json2Dict(jsondata)
    content = jsondict['content']
    src = ''

    for k, v in content.items():
        src = 'jsondata/' + v['assets'][0]['src']
        break

    for k, v in content.items():
        src = 'jsondata/' + v['assets'][0]['src']
        break

    title = ''
    addedvalue = ''
    description = ''
    location = ''
    prices = ''
    facilities = ''

    for lang in jsondict['translations']:
        for _, o in jsondict['translations'][lang]['objects'].items():
            for k, v in o.items():
                if k == 'name':
                    title = v
                elif k == 'desc':
                    description = v
                elif k == 'location':
                    location = v
                elif k == 'facilites':
                    facilities = v
                elif k == 'added-values':
                    addedvalue = v
                elif k == 'prices':
                    prices = v

        addTitle(page, context, title)
        addDescription(page, context, description)
        addImage(page, context, src)
        """
        # dh is added offset from top page edge.
        dh = drawDescription(context, description, dh)
        dh = drawLocation(context, location, dh)
        """

        # Just testing first language for now.
        break

    page.solve()
    path = '_export/doc-%s.pdf' % doc.context.name
    doc.export(path)
示例#13
0
    y=20,
    w=page.pw / 2 - page.gw,
    mr=page.gw,
    fill=0,
    fontSize=fontSize,
    conditions=[Left2Left(),
                Float2Top(),
                Fit2Bottom(),
                Overflow2Next()],
    nextElement=cId2)
#print ce1.isOverflow()

newTextBox('',
           name=cId2,
           parent=page,
           ml=page.gw,
           x=20,
           y=20,
           fill=0,
           fontSize=fontSize,
           w=page.pw / 2 - page.gw,
           conditions=[Float2Right(),
                       Float2Top(),
                       Float2Left(),
                       Fit2Bottom()])
#print he.x, he.y
print page.solve()
#print he.x, he.y

doc.export('_export/TextAssignment.pdf')
# Red frame to show position and dimensions of the text box element.
# Default behavior of the textbox is to align the text at "top of the em-square".
c1 = newTextBox(t,
                parent=page,
                w=500,
                stroke=(1, 0, 0),
                yAlign=TOP,
                showOrigin=True,
                showBaselineGrid=False,
                conditions=[Left2Left(),
                            Top2Top(),
                            Fit2Height(),
                            Fit2Width()])
# Solve the page/element conditions, so the text box as it's position and size.
doc.solve()

# Get the position of the first baseline of the text.
firstLine = c1.textLines[0]
#print(sorted(c1.baselines))
#print(firstLine, firstLine.y)
#print(firstLine[0].fontMatrix)
#newLine(x=0, y=firstLine.y, w=page.pl, h=0, stroke=(1, 0, 0), strokeWidth=1, parent=page)
#newLine(x=c1.x, y=c1.h-firstLine.y-firstLine.xHeight, w=c1.w, h=0, stroke=(1, 0, 0), strokeWidth=1, parent=page)
#newLine(x=c1.x, y=c1.h-firstLine.y-firstLine.capHeight, w=c1.w, h=0, stroke=(1, 0, 0), strokeWidth=1, parent=page)
# FIX: Something with the ascender position? Or is it showing the max-value for all glyphs?
#newLine(x=c1.x, y=c1.h-firstLine.y-firstLine.ascender, w=c1.w, h=0, stroke=(1, 0, 0), strokeWidth=1, parent=page)
#newLine(x=c1.x, y=c1.h-firstLine.y-firstLine.descender, w=c1.w, h=0, stroke=(1, 0, 0), strokeWidth=1, parent=page)

# Export the document to this PDF file.
doc.export('_export/SingleColumnYPositions.pdf')
示例#15
0
# Example baseline position, showing that start can be different from page side
# or top of text box.
BASELINE = pt(15)
BASELINE_START = 3.5 * BASELINE
PADDING = 5 * BASELINE  # Page padding related to baseline in this example.

doc = Document(
    size=B5,
    padding=PADDING,
    originTop=True,
    autoPages=3,  # Create multiple pages, to show the page number/total pages.
    baselineGrid=BASELINE,
    baselineGridStart=BASELINE_START)

view = doc.view  # Get the current view of this document. Defaulse it PageView.
view.padding = inch(
    0.5)  # Define padding of the view, so there is space for crop marks
view.showBaselineGrid = [BASE_LINE_BG,
                         BASE_INDEX_LEFT]  # Set to True to show baseline index
#view.showBaselineGrid = [BASE_LINE_BG, BASE_Y_LEFT] # Use this line to show vertical positions
view.showPadding = True  # Show the padding of the page. The size is then (page.pw, page.ph)
view.showCropMarks = True
view.showRegistrationMarks = True
view.showNameInfo = True  # Show document/name/date info in view padding area.
view.showFrame = True  # Show frame of the page size.

# The page has no child elements, just showing the metrics of the padding and baseline.

# Export the document showing the baselines of the page as horizontal lines and the padding.
doc.export('_export/PageBaselines.pdf')
示例#16
0
# Rotate the whole by selecting the value and then cmd-drag to alter the value
# The elements rotate independently. Note that the image is rotating in the
# reversed direction, so it stays upright in the clipping rectangle.
a = degrees(100)

im.angle = a
im.fill = (0, 0, 0.7 + random() * 0.3)
imd = im.imageData
imd.x = 366
imd.y = 150
imd.w = 300
imd.h = 400
imd.rx = 50
imd.ry = 60
imd.angle = -a

bs = context.newString('Rotating images', style=dict(fontSize=32, textFill=1))
tb = newTextBox(bs,
                w=400,
                parent=im,
                conditions=(Center2Center(), Middle2Middle()),
                angle=-a,
                fill=noColor)
# Solve the page/element conditions
doc.solve()

im.rx = im.w / 2
im.ry = im.h / 2
# Export the document to this PDF file.
doc.export('_export/ImageClipping.pdf')
示例#17
0
        w=w,
        h=w,
        fill=color('yellow'),
        conditions=[Left2Left(), Top2Top()])
newRect(parent=page,
        w=w,
        h=w,
        fill=color('purple'),
        conditions=[Bottom2Bottom(), Right2Right()])
newRect(parent=page,
        w=w,
        h=w,
        fill=color('violet'),
        conditions=[Middle2Middle(), Right2Right()])
newRect(parent=page,
        w=w,
        h=w,
        fill=color('cyan'),
        conditions=[Center2Center(), Bottom2Bottom()])
newRect(parent=page,
        w=w,
        h=w,
        fill=color('black'),
        conditions=[Center2Center(), Middle2Middle()])

page.solve()

# Export in _export folder that does not commit in Git. Force to export PDF.
EXPORT_PATH = '_export/ElementConditions.pdf'
doc.export(EXPORT_PATH)
    y=page.h / 2,
    name='c1',
    parent=page,
    nextElementName='c2',
    yAlign=BASE_TOP,
    showOrigin=True,
    showBaselines=(BASE_LINE, BASE_INDEX_LEFT,
                   BASE_Y_RIGHT),  # Overwrite view setting.
    conditions=[Left2Left(), Overflow2Next()])
# Text without initial content, will be filled by overflow of c1.
# Not showing the [+] marker, as the overflow text fits in the second column.
c2 = newTextBox(
    w=CW,
    h=CH,
    y=page.h / 2,
    name='c2',
    parent=page,
    yAlign=BASE_BOTTOM,
    showOrigin=True,
    showBaselines=(BASE_LINE, BASE_INDEX_LEFT,
                   BASE_Y_RIGHT),  # Overwrite view setting.
    conditions=[Right2Right()])

newLine(x=page.pl, y=page.h / 2, w=page.pw, h=0, parent=page, stroke=(1, 0, 0))

# Solve the page/element conditions
doc.solve()

# Export the document to this PDF file.
doc.export('_export/TextBoxBaselinePlacing.pdf')
示例#19
0
BASELINE = pt(15)
BASELINE_START = 3.5 * BASELINE
PADDING = 5 * BASELINE  # Page padding related to baseline in this example.

doc = Document(
    size=B5,
    padding=PADDING,
    originTop=True,
    autoPages=3,  # Create multiple pages, to show the page number/total pages.
    baselineGrid=BASELINE,
    baselineGridStart=BASELINE_START)

view = doc.view  # Get the current view of this document. Defaulse it PageView.
view.padding = inch(
    0.5)  # Define padding of the view, so there is space for crop marks
view.showBaselines = [BASE_LINE_BG,
                      BASE_INDEX_LEFT]  # Set to True to show baseline index
#view.showBaselines = [BASE_LINE_BG, BASE_Y_LEFT] # Use this line to show vertical positions
view.showPadding = True  # Show the padding of the page. The size is then (page.pw, page.ph)
view.showCropMarks = True
view.showRegistrationMarks = True
view.showColorBars = (ECI_GrayConL, COLORBAR_LEFT
                      )  #, COLORBAR_RIGHT) <-- Not right position
view.showNameInfo = True  # Show document/name/date info in view padding area.
view.showFrame = True  # Show frame of the page size.

# The page has no child elements, just showing the metrics of the padding and baseline.

# Export the document showing the baselines of the page as horizontal lines and the padding.
doc.export('_export/PageColorBars.pdf')
示例#20
0
               fill=noColor,
               conditions=(Center2Center(), Middle2Middle()))

if 1:
    # Make image box as child element of the page and set its layout conditions.
    im = Image(imagePath,
               h=IH,
               w=IH,
               fill=(1, 0, 1, 0.5),
               parent=page,
               conditions=[Right2Right(),
                           Float2Top(),
                           Float2Left()],
               mr=G,
               mb=G)
    bs = context.newString('3',
                           style=dict(fontSize=14,
                                      textFill=0,
                                      xTextAlign=CENTER))
    newTextBox(bs,
               parent=im,
               w=IH,
               fill=noColor,
               conditions=(Center2Center(), Middle2Middle()))

# Solve the page/element conditions
doc.solve()

# Export the document to this PDF file.
doc.export('_export/RotatingText.pdf')
示例#21
0
# Show the usable space (=page.padding) of the page, which the same as the box after fitting
view.showPadding = True
view.showOrigin = False
view.showTextOverflowMarker = False
# Get the first (and only automatic created) page of the document
page = doc[1]

# Create a number of paths that can be drawn in a grid showing multiple functions.
# Create a new BezierPath as separate entity to talk to.
path = PageBotPath(context, style=dict(fill=color(rgb='yellow'), stroke=color(rgb='red'), strokeWidth=pt(0.5)))
path.text('B', style=dict(font=font.path, fontSize=400))
path = path.removeOverlap()

e = Paths(path, parent=page, mr=G, mb=G, fill=0.9, h=CW, conditions=[Right2Right(), Float2Top(), Float2Left()])
#e.xy = page.pl, page.pb

path = PageBotPath(context, style=dict(fill=noColor, stroke=color(0.5), strokewidth=0.5))
path.rect(0, 0, CW-G, CW-G)
path.rect(G, G, CW-G, CW-G)
path.rect(G/2, G, CW-G, CW-G)
path.rect(G, G/2, CW-G, CW-G)
path = path.removeOverlap()
e = Paths(path, parent=page, mr=G, mb=G, h=CW, conditions=[Right2Right(), Float2Top(), Float2Left()])
#e.xy = page.pl, page.pb

# Solve the page/element conditions
doc.solve()
# Export the document to this PDF file.
doc.export('_export/PageBotPaths.pdf')

示例#22
0
# Get page by pageNumber, first in row (there is only one now in this row).
page = doc[0]
page.padding = 30

conditions = [Right2Right(), Float2Top(), Float2Left()]
# TODO: Solve this bug, does not mirror.
#conditions = [Left2Left(), Float2Top(), Float2Right()]

for n in range(32):
    newRect(w=40,
            h=42,
            mr=4,
            mt=4,
            parent=page,
            fill=(random() * 0.5 + 0.5, 0, 0.5),
            conditions=conditions)

# Recursively solve the conditions in all pages.
# If there are failing conditions, then the status
# is returned in the Score instance.
score = doc.solve()
if score.fails:
    print(score.fails)

doc.export(EXPORT_PATH_SVG)
doc.export(EXPORT_PATH_JPG)
doc.export(EXPORT_PATH_PNG)
doc.export(EXPORT_PATH_PDF)

print('Done')
示例#23
0
    page.showBaselineGrid = [BASE_LINE]
    page.baselineColor = color(0, 1, 0)




style = dict(font=font, fontSize=pt(18), leading=18, textFill=0, fill=(1, 0, 0), xTextAlign=LEFT)

bs = c.newString('Aaaa\nBbbb\nCccc\nDddd', style=style)
tb = newTextBox(bs, parent=page, padding=G, fill=(1, 1, 0), w=page.pw, h=page.ph, 
    baselineWidth=pt(3), 
    baselineColor=color(1, 0, 0), 
    conditions=[Left2Left(), Baseline2Grid(index=2)])
tb.showBaselineGrid = True
tb.baselineGrid=pt(28)

"""

doc.solve()

#baselineDown2Grid(tb1, index=14) # Rounding in "down" direction
#baselineUp2Grid(tb1, index=14) # Rounding in "up" direction

#tyledBaselineDown2Grid(tb1, dict(textFill=color(0, 1, 0)), 0)
#styledBaselineDown2Grid(tb1, dict(fontSize=9), 0)
#styledBaselineDown2Grid(tb1, bStyle, 0)
#tb1.styledBaselineDown2Grid(pStyle, 3)
#tb1.capHeightDown2Grid(0)

doc.export('_export/TextBaselines.pdf')
示例#24
0
#     Copyright (c) 2016+ Buro Petr van Blokland + Claudia Mens
#     www.pagebot.io
#
#     P A G E B O T
#
#     Licensed under MIT conditions
#
#     Supporting DrawBot, www.drawbot.com
#     Supporting Flat, xxyxyz.org/flat
# -----------------------------------------------------------------------------
#
#    04_RTDExample.py
#

from pagebot.document import Document
from pagebot.elements import newRect
from pagebot.conditions import Center2Center, Middle2Middle
from pagebot.toolbox.units import pt
from pagebot.toolbox.color import color

W, H = pt(300, 200)  # Get size units
doc = Document(w=W, h=H, originTop=False)
page = doc[1]
newRect(parent=page,
        fill=color('red'),
        size=pt(240, 140),
        showDimensions=True,
        conditions=[Center2Center(), Middle2Middle()])
page.solve()
doc.export('_export/RedSquare.png')
示例#25
0
    # Create the Composer instance that will interpret the galley.
    composer = Composer(doc)

    # Create the global targets dictionary with objects that can be used during
    # interpretation of the markdown elements on the galley. The composer instance
    # will run sequentially through the elements, executing the code blocks.
    # This may cause the shifting of target for the text elements to another block
    # or another page.
    targets = dict(doc=doc,
                   page=page1,
                   box=page1.select('Box'),
                   composer=composer,
                   styles=styles,
                   context=doc.context)
    composer.compose(galley, targets=targets)

    # Now the targets dictionary is filled with results that were created during
    # execution of the code blocks, such as possible errors and warnings.
    # Also it contains the latest “box”
    print('Keys in target results:', targets.keys())
    print('Errors:', targets['errors'])
    print('Number of verbose feedback entries:', len(targets['verbose']))
    print('Values created in the code block: aa=%s, bb=%s, cc=%s' %
          (targets['aa'], targets['bb'], targets['cc']))

    doc.solve()

# Save the created document as (2 page) PDF.
pdfDoc.export('_export/ContextBehavior.pdf')
htmlDoc.export('_export/ContextBehaviorSite')
               name='main12',
               h=1200,
               w=CW1,
               parent=main1,
               fill=0.95,
               conditions=(Right2Right(), Float2Top()))
'''
if 1:
    # Main article as group of 3 text boxes
    main2 = newRect(parent=page, w=CW4, mt=G, fill=0.8, conditions=(Left2Left(), Float2Top()))

    bs = context.newString('Headline main 2', style=headline1Style)
    tw, th = bs.size
    newTextBox(bs, name='head2', parent=main2, conditions=(Left2Left(), Fit2Width(), Float2Top()))

    bs = context.newString('Aaaa ' * 120, style=mainStyle)
    newTextBox(bs, name='main21', h=400, w=CW2, parent=main2, fill=0.8, mt=3*G,
        conditions=(Left2Left(), Float2Top()))
    bs = context.newString('Aaaa ' * 120, style=mainStyle)
    newTextBox(bs, name='main22', h=400, w=CW2, parent=main2, fill=0.8, mt=3*G, 
        conditions=(Right2Right(), Float2Top()))

'''
doc.solve()  # Drill down to solve all elements conditions.

# =============================================================================
#    Export to PDF or other file formats
# .............................................................................

doc.export('_export/TheVariableGlobe.pdf')
示例#27
0
# In multipage documents this also can be done in the document, so pages inherit.
page.padding = PAD, PAD, 2 * PAD, PAD
# Create rectangles. Default position and size is (0, 0, 100, 100). The conditions define the layout.
newRect(fill=color(1, 0, 0),
        parent=page,
        h=pt(62),
        conditions=(Left2Left(), Float2Top(), Fit2Right()))
newRect(fill=color(1, 0, 1),
        parent=page,
        conditions=(Left2LeftSide(), Float2Top()))
newRect(fill=color(spot=300),
        parent=page,
        conditions=(Right2Right(), Float2Top(), Float2Left(), Fit2Right()))

# Add a floating text box.
newTextBox('BB',
           parent=page,
           x=100,
           y=150,
           w=300,
           h=400,
           fill=color(spot=400),
           fontSize=p(8),
           font='Verdana',
           textFill=color(spot=120))

# Solve the conditions of the layout in defined order.
doc.solve()
# Export to PDF.
doc.export('_export/SimpleDocument.pdf')
        page.w = W

        phisin = sin(radians(axisFrameIndex / axisFrames * 360 +
                             3 / 4 * 360)) * 0.5 + 0.5
        fontSize = phisin * (maxValue - minValue) + minValue

        # Variable Font location for this frame sample
        variableLocation = {axisTag: fontSize}
        # Overall style for the frame
        style = dict(leading=em(1.4),
                     fontSize=fontSize * fontSizeFactor,
                     xTextAlign=RIGHT,
                     textFill=color(1),
                     stroke=None,
                     fill=blackColor,
                     variableLocation=variableLocation)

        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_OpticalSize.gif' % font.info.familyName)
示例#29
0
context = getContext()
print(context)

W = H = 1000  # Document size
PADDING = 100  # Page padding on all sides. Select value and cmd-drag to change interactive.

font = findFont('PageBot-Bold')
#print(font)

style = dict(font=font, fontSize=24, leading=em(1.4), textFill=0.3)
# Make long text to force box overflow
t = context.newString(text, style=style)
# Create a new document with 1 page. Set overall size and padding.
doc = Document(w=W, h=H, padding=PADDING, context=context, originTop=False)
# Get the default page view of the document and set viewing parameters
view = doc.view
# Show the usable space (=page.padding) of the page, which the same as the box after fitting
view.showPadding = True
view.showOrigin = True
view.showTextOverflowMarker = True
# Get the first (and only automatic created) page of the document
page = doc[1]
# Make text box as child element of the page and set its layout conditions
# to fit the padding of the page.
# Text overflows the edge of the text box, but currently we cannot see that.
tb = newTextBox(t, parent=page, yAlign=TOP, showFrame=True, conditions=[Fit()])
# Solve the page/element conditions
doc.solve()
# Export the document to this PDF file.
doc.export('_export/SingleColumn.pdf')
示例#30
0
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()

    path = '_export/doc-%s.pdf' % doc.context.name
    doc.export(path)


    base = os.path.abspath(__file__)
    d = os.path.dirname(base)
    src = '/jsondata/AMXP--119s014.json'
    p = d + src
    f = open(p, 'r')
    jsondata = f.read()
    jsondict = json2Dict(jsondata)
    content = jsondict['content']

    #context.newDrawing()
    #context.newPage(w=W, h=H)
    src = ''

    for k, v in content.items():
        src = 'jsondata/' + v['assets'][0]['src']
        break

    #context.image(src, p=pt(0, 0), w=pt(200), h=pt(300))
    #context.fill(None)
    #context.stroke(s)

    title = ''
    addedvalue = ''
    description = ''
    location = ''
    prices = ''
    facilities = ''

    for lang in jsondict['translations']:
        for _, o in jsondict['translations'][lang]['objects'].items():
            for k, v in o.items():
                if k == 'name':
                    title = v
                elif k == 'desc':
                    description = v
                elif k == 'location':
                    location = v
                elif k == 'facilites':
                    facilities = v
                elif k == 'added-values':
                    addedvalue = v
                elif k == 'prices':
                    prices = v

        """
        # dh is added offset from top page edge.
        dh = drawTitle(context, title, 0)
        dh = drawDescription(context, description, dh)
        dh = drawLocation(context, location, dh)
        """

        #path = '_export/%s-%s-%s.pdf' % ('JSON', context.name, lang)
        #context.saveImage(path)
        #print('Saved %s' % path)

        # Just testing first language.
        break
    '''