Identify when a word breaks



  • Hi!

    I'm making some id cards for a project and I want to control the words' horizontal interpolation, so I think I need to identify when a word is about to break and at that moment stop adding interpolation, in the same way when a text jumps to the other line I want to control vertical interpolation so I want to know if there's a way to identify a line jumps.

    Here's the code:

    import os
    import unicodedata
    
    def strip_accents(text):
    
        try:
            text = unicode(text, 'utf-8')
        except NameError: # unicode is a default on python 3 
            pass
    
        text = unicodedata.normalize('NFD', text)\
               .encode('ascii', 'ignore')\
               .decode("utf-8")
    
        return str(text)
    
    class Canvas:
        
        def __init__(self, w, h, o = 0, bleed = 0):
            self.w = w
            self.h = h
            self.o = o
            self.bleed = bleed
            if self.bleed <= 0:
                newPage(self.w, self.h)
            else:
                newPage(self.w + self.bleed * 2, self.h + self.bleed * 2)
                translate(self.bleed, self.bleed)
        
        def color(self, r = 255, g = 255, b = 255, a = 100):
            self.r = r / 255
            self.g = g / 255
            self.b = b / 255
            self.a = a / 100
            return fill(self.r, self.g, self.b, self.a)
        
        def bg_stroke(self, r, g, b, a, sw):
            self.r, self.g, self.b, self.a = color_c(r, g, b, a)
            self.sw = sw
            stroke(self.r, self.g, self.b, self.a)
            strokeWidth(self.sw)
            fill(None)
        
        def grid(self, cols, rows, gutter, mTop, mBottom, mLeft, mRight, view=True):
            if view == True:
                self.cols = cols
                self.rows = rows
                self.gutter = gutter
                self.mTop = mTop - self.gutter
                self.mBottom = mBottom  - self.gutter
                self.mLeft = mLeft - self.gutter
                self.mRight = mRight - self.gutter
                wd = (self.w - self.gutter * (self.cols + 1)) / self.cols - ((self.mRight + self.mLeft) / self.cols)
                hg = (self.h - self.gutter * (self.rows + 1)) / self.rows - ((self.mTop + self.mBottom) / self.rows)
                fill(None)
                strokeWidth(0.25)
                stroke(0, 1, 1)
                for self.col in range(self.cols):
                    for self.row in range(self.rows):
                        x = self.gutter + self.col * (wd + self.gutter)
                        y = self.gutter + self.row * (hg + self.gutter)
                        rect(x + self.mLeft, y + self.mBottom, wd, hg)
        
        def bg_square(self):
            if self.bleed <= 0:
                rect(self.o, self.o, self.w, self.h)
            else:
                rect(self.o - self.bleed, self.o - self.bleed, self.w + self.bleed * 2, self.h + self.bleed * 2)
        
        def bg_image(self, imgPath, px, py, angle, s):
            self.imgPath = imgPath
            self.px = px
            self.py = py
            self.angle = angle
            self.s = s
            srcWidth, srcHeight = imageSize(self.imgPath)
            dstWidth, dstHeight = self.w + s, self.h + s
            factorWidth = dstWidth  / srcWidth
            factorHeight = dstHeight / srcHeight
            with savedState():
                scale(factorWidth, factorHeight)
                rotate(self.angle)
                translate(self.px, self.py)
                image(imgPath, (0, 0))
        
        def crop_marks(self):
            stroke(1)
            strokeWidth(1)
            line((self.o, -8), (self.o, -4))
            line((-8, self.o), (-4, self.o))
            line((self.o + self.w, -8), (self.o + self.w, -4))
            line((8 + self.w, self.o), (4 + self.w, self.o))
            line((self.o, 8 + self.h), (self.o, 4 + self.h))
            line((-8, self.o + self.h), (-4, self.o + self.h))
            line((self.o + self.w, 8 + self.h), (self.o + self.w, 4 + self.h))
            line((8 + self.w, self.o + self.h), (4 + self.w, self.o + self.h))
            stroke(0)
            strokeWidth(0.5)
            line((self.o, -8), (self.o, -4))
            line((-8, self.o), (-4, self.o))
            line((self.o + self.w, -8), (self.o + self.w, -4))
            line((8 + self.w, self.o), (4 + self.w, self.o))
            line((self.o, 8 + self.h), (self.o, 4 + self.h))
            line((-8, self.o + self.h), (-4, self.o + self.h))
            line((self.o + self.w, 8 + self.h), (self.o + self.w, 4 + self.h))
            line((8 + self.w, self.o + self.h), (4 + self.w, self.o + self.h))
                
    #Design
    
    #Margin
    gutter = 0
    mTop = 8
    mBottom = 8
    mLeft = 8
    mRight = 8
    
    #Variable Font
    myVarFont = '/Library/Application Support/Adobe/Fonts/AstripeVariableGX.ttf'
    variations = listFontVariations(myVarFont)
    print(variations)
    #print(listFontGlyphNames())
    axis1 = list(variations.keys())[0]
    minH = variations[axis1]['minValue']
    maxH = variations[axis1]['maxValue']
    axis2 = list(variations.keys())[1]
    
    
    
    minV = variations[axis2]['minValue']
    maxV = variations[axis2]['maxValue']
    fs = 41
    gf = 7
    
    def lenght():
        var = 400
        var += 200
        return var
    
    #Canvas
    page = Canvas(240, 150, 0, 8)
    page.color(255, 255, 255, 100)
    page.bg_square()
    
    #Info
    gafetes = ['Staff', 'All Access', 'Participante', 'Prensa', 'Académico', 'Maestro de Ceremonia', 'Jueces', 'Edecán', 'Sistemas', 'Acompañante', 'Director']    
    
    #Art
    page.bg_image('/Users/eduardo.aire/Documents/Documentos - EATs iMac/A/01_A_PROYECTOS/01_VIGENTES/2020_PIBA/PIBA_2020_FOTOS/29_PIBA_2020_ESTELASTRIPE.psd', -1160, -70, 270, 110)
    t = FormattedString()
    t.font(installFont('/Library/Application Support/Adobe/Fonts/AstripeVariableGX.ttf'))
    t.fontSize(fs)
    t.fill(0)
    t.openTypeFeatures(calt=True)
    t.align('right')
    hyphenation(True)
    t.lineHeight(45)
    t.baselineShift(-15)
    for letter in gafetes[gf].upper():
        t.append(letter, fontVariations={axis1:lenght(), axis2:randint(minV, maxV)})
    textBox(t, (mLeft, mBottom, page.w - mRight - mLeft, page.h - mTop - mBottom))
    
    #Marks, guides and comments
    #fill(0, 0, 0, 0.1)
    #rect(mLeft, mBottom, page.w - mRight - mLeft, page.h - mTop - mBottom)
    page.crop_marks()
    page.grid(6, 3, 0, mTop, mBottom, mLeft, mRight, False)
    
    #Saving
    saveImage('~/Desktop/PIBA_2020_GAFETES_{name}.png'.format(name = strip_accents(gafetes[gf].upper().replace(" ", "_"))), imageResolution = 144)
    

    And here some images of the design.

    PIBA_2020_GAFETES_MAESTRO_DE_CEREMONIA.png PIBA_2020_GAFETES_EDECAN.png

    Thank you!!



  • hello @eduairet,

    here’s a simple example showing word breaks (changing fill color) and line breaks (stroke color):

    Screen Shot 2020-02-13 at 16.44.39.png

    TXT = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
    FONT = 'Impact'
    FONTSIZE = 36
    WIDTH = 800
    
    T = FormattedString(font=FONT, fontSize=FONTSIZE, lineHeight=FONTSIZE*1.2, strokeWidth=2)
    T.stroke(random(), random(), random())
    
    font(FONT)
    fontSize(FONTSIZE)
    
    lineLength = 0
    for word in TXT.split():
        T.fill(random())
        if lineLength + textSize(word)[0] <= WIDTH:
            T += word + ' '
            lineLength += textSize(word + ' ')[0]
        else:
            T.stroke(random(), random(), random())
            T += '\n' + word + ' '
            lineLength = textSize(word + ' ')[0]
    
    text(T, (50, 900))
    

    hope it makes sense! good luck



  • @gferreira Thank you! I've used this in the following application but I noticed that even though I used hyphenation=False the words break in the middle so, I don't need it to break for this exercise but it's something I can't figure out:

    myVarFont = '/Library/Application Support/Adobe/Fonts/AstripeVariableGX.ttf'
    variations = listFontVariations(myVarFont)
    print(variations)
    axis1 = list(variations.keys())[0]
    minH = variations[axis1]['minValue']
    maxH = variations[axis1]['maxValue']
    axis2 = list(variations.keys())[1]
    minV = variations[axis2]['minValue']
    maxV = variations[axis2]['maxValue']
    
    #Words
    def textPage(*words, o=0, size='Tabloid', positive=True, h=True, txt=FormattedString(), myFont=myVarFont, fSize=30, lHeight=23.5):
        def canvas():
            newPage(size)
            if positive is True:
                fill(1)
            if positive is False:
                fill(0)
            rect(o, o, width(), height())
        canvas()
        txt.font( installFont(myFont) )
        txt.fontSize(fSize)
        txt.openTypeFeatures(calt=True)
        txt.lineHeight(lHeight)
        hyphenation(False)
        lineLength = 0
        textLength = (width()*height())/(lHeight)
        #print(textLength)
        
        while txt.size()[0] < textLength:
            for word in words:
                if lineLength % 350 == 0:
                    txt.append('\n' + word, fontVariations={axis1:minH, axis2:minV})
                else:    
                    txt.append(word, fontVariations={axis1:minH, axis2:minV})
                lineLength += textSize(word)[0]
                #print(lineLength)
        textBox(txt, ( o, o, width(), height() ))
        #print(txt.size()[0])
        
         
    textPage('PIBA', '2020', 'LIDERA')
    
    saveImage('~/Desktop/PIBA_2020_CORBATA.pdf')
    

    This is what I need from the image:
    PIBA_2020_CORBATA_2.jpg

    And this is what I don't understand:

    PIBA_2020_CORBATA_2.jpg

    By the way:
    The previous exercise worked this way:

    import os
    
    import unicodedata
    def strip_accents(text):
        try:
            text = unicode(text, 'utf-8')
        except NameError: # unicode is a default on python 3 
            pass
        text = unicodedata.normalize('NFD', text)\
               .encode('ascii', 'ignore')\
               .decode("utf-8")
        return str(text)
    
    class Canvas:
        def __init__(self, w, h, o = 0, bleed = 0):
            self.w = w
            self.h = h
            self.o = o
            self.bleed = bleed
            if self.bleed <= 0:
                newPage(self.w, self.h)
            else:
                newPage(self.w + self.bleed * 2, self.h + self.bleed * 2)
                translate(self.bleed, self.bleed)
        def color(self, r = 255, g = 255, b = 255, a = 100):
            self.r = r / 255
            self.g = g / 255
            self.b = b / 255
            self.a = a / 100
            return fill(self.r, self.g, self.b, self.a)
        def bg_stroke(self, r, g, b, a, sw):
            self.r, self.g, self.b, self.a = color_c(r, g, b, a)
            self.sw = sw
            stroke(self.r, self.g, self.b, self.a)
            strokeWidth(self.sw)
            fill(None)
        def grid(self, cols, rows, gutter, mTop, mBottom, mLeft, mRight, view=True):
            if view == True:
                self.cols = cols
                self.rows = rows
                self.gutter = gutter
                self.mTop = mTop - self.gutter
                self.mBottom = mBottom  - self.gutter
                self.mLeft = mLeft - self.gutter
                self.mRight = mRight - self.gutter
                wd = (self.w - self.gutter * (self.cols + 1)) / self.cols - ((self.mRight + self.mLeft) / self.cols)
                hg = (self.h - self.gutter * (self.rows + 1)) / self.rows - ((self.mTop + self.mBottom) / self.rows)
                fill(None)
                strokeWidth(0.25)
                stroke(0, 1, 1)
                for self.col in range(self.cols):
                    for self.row in range(self.rows):
                        x = self.gutter + self.col * (wd + self.gutter)
                        y = self.gutter + self.row * (hg + self.gutter)
                        rect(x + self.mLeft, y + self.mBottom, wd, hg)
        def bg_square(self):
            if self.bleed <= 0:
                rect(self.o, self.o, self.w, self.h)
            else:
                rect(self.o - self.bleed, self.o - self.bleed, self.w + self.bleed * 2, self.h + self.bleed * 2)
        def bg_image(self, imgPath, px, py, angle, s):
            self.imgPath = imgPath
            self.px = px
            self.py = py
            self.angle = angle
            self.s = s
            srcWidth, srcHeight = imageSize(self.imgPath)
            dstWidth, dstHeight = self.w + s, self.h + s
            factorWidth = dstWidth  / srcWidth
            factorHeight = dstHeight / srcHeight
            with savedState():
                scale(factorWidth, factorHeight)
                rotate(self.angle)
                translate(self.px, self.py)
                image(imgPath, (0, 0))
        def crop_marks(self):
            stroke(1)
            strokeWidth(1)
            line((self.o, -8), (self.o, -4))
            line((-8, self.o), (-4, self.o))
            line((self.o + self.w, -8), (self.o + self.w, -4))
            line((8 + self.w, self.o), (4 + self.w, self.o))
            line((self.o, 8 + self.h), (self.o, 4 + self.h))
            line((-8, self.o + self.h), (-4, self.o + self.h))
            line((self.o + self.w, 8 + self.h), (self.o + self.w, 4 + self.h))
            line((8 + self.w, self.o + self.h), (4 + self.w, self.o + self.h))
            stroke(0)
            strokeWidth(0.5)
            line((self.o, -8), (self.o, -4))
            line((-8, self.o), (-4, self.o))
            line((self.o + self.w, -8), (self.o + self.w, -4))
            line((8 + self.w, self.o), (4 + self.w, self.o))
            line((self.o, 8 + self.h), (self.o, 4 + self.h))
            line((-8, self.o + self.h), (-4, self.o + self.h))
            line((self.o + self.w, 8 + self.h), (self.o + self.w, 4 + self.h))
            line((8 + self.w, self.o + self.h), (4 + self.w, self.o + self.h))
                
    #Design
    
    #Margin
    gutter = 0
    mTop = 8
    mBottom = 8
    mLeft = 8
    mRight = 8
    
    #Variable Font
    myVarFont = '/Library/Application Support/Adobe/Fonts/AstripeVariableGX.ttf'
    variations = listFontVariations(myVarFont)
    print(variations)
    #print(listFontGlyphNames())
    axis1 = list(variations.keys())[0]
    minH = variations[axis1]['minValue']
    maxH = variations[axis1]['maxValue']
    axis2 = list(variations.keys())[1]
    minV = variations[axis2]['minValue']
    maxV = variations[axis2]['maxValue']
    num = 0
    logo = 'PIBA_2020_GAFETES_LOGO.pdf'
    
    #Info
    gafetes_dir = {'Staff': 3, 'All Access': 1, 'Participante': 3, 'Prensa': 1, 'Académico': 3, 'Maestro de Ceremonia': 3, 'Jueces': 1, 'Edecán': 1, 'Sistemas': 1, 'Acompañante': 1, 'Director': 1} 
    
    gafetes = [i for i in gafetes_dir.keys()]
    copias = [i for i in gafetes_dir.values()]
    
    def gafete(gf=0):
        #Frente
        page = Canvas(240, 150, 0, 8)
        page.color(255, 255, 255, 100)
        page.bg_square()
        
        #Text
        var = 400
        minus = 0
        lineHeight = 45
        al = 'right'
        fs = 41
        
        t = FormattedString()
        t.font(installFont(myVarFont))
        t.fontSize(fs)
        t.fill(0)
        t.openTypeFeatures(calt=True)
        t.align(al)
        t.lineHeight(lineHeight)
        t.baselineShift(-15)
        
        for letter in gafetes[gf].upper():
            t.append(letter, fontVariations={axis1:var, axis2:randint(minV, maxV)})
        print(t.size()[0])
        
        while t.size()[0] < page.w - 40 and var < 500:
            var += 10
        print(var)
        
        if t.size()[0] > 300.0:
            lineHeight = 40
            minus = 440.0
            print('minus')
            
        if t.size()[0] < 140.0:
            lineHeight = 69
            fs = 60
            print('minus')
        
        t = FormattedString()
        t.font(installFont(myVarFont))
        t.fontSize(fs)
        t.fill(0)
        t.openTypeFeatures(calt=True)
        t.align(al)
        t.lineHeight(lineHeight)
        t.baselineShift(-15)
        for letter in gafetes[gf].upper():
            t.append(letter, fontVariations={axis1:var, axis2:randint(minV, maxV - minus)})
        textBox(t, (mLeft, mBottom, page.w - mRight - mLeft, page.h - mTop - mBottom))
        
        #Art
        page.bg_image('/Users/eduardo.aire/Documents/Documentos - EATs iMac/A/01_A_PROYECTOS/01_VIGENTES/2020_PIBA/PIBA_2020_FOTOS/29_PIBA_2020_ESTELASTRIPE.psd', -1140, -10, 270, 100)
        
        #Marks, guides and comments 
        #fill(0, 0, 0, 0.1)
        #rect(mLeft, mBottom, page.w - mRight - mLeft, page.h - mTop - mBottom)
        page.crop_marks()
        page.grid(6, 3, 0, mTop, mBottom, mLeft, mRight, False)
        
        #Reverso
        page = Canvas(240, 150, 0, 8)
        page.color(255, 255, 255, 100)
        page.bg_square()   
        
        #Logo
        imgPath = logo
        srcWidth, srcHeight = imageSize(imgPath)
        dstWidth, dstHeight = page.w, page.h
        factorWidth = dstWidth  / srcWidth
        factorHeight = dstHeight / srcHeight
        with savedState():
            scale(1)
            rotate(-90)
            translate(-150, 0)
            image(imgPath, (0,0))
        
        #Marks, guides and comments 
        #fill(0, 0, 0, 0.1)
        #rect(mLeft, mBottom, page.w - mRight - mLeft, page.h - mTop - mBottom)
        page.crop_marks()
        page.grid(6, 3, 0, mTop, mBottom, mLeft, mRight, False)
        
        saveImage('~/Desktop/PIBA_2020_GAFETES_{name}_{number:0>2}.pdf'.format(name = strip_accents(gafetes[gf].upper().replace(" ", "_")), number = str(num)))
        newDrawing()
    
    #gafete(6)
    
    for i in range(len(gafetes)+1):
         num=1
         for j in range(copias[i - 1]):
             gafete(i - 1)
             num += 1
    

    PIBA_2020_GAFETES_ACADEMICO_01_1.jpg PIBA_2020_GAFETES_ACADEMICO_02_1.jpg PIBA_2020_GAFETES_ACADEMICO_03_1.jpg

    PIBA_2020_GAFETES_STAFF_01_1.jpg PIBA_2020_GAFETES_STAFF_03_1.jpg PIBA_2020_GAFETES_STAFF_02_1.jpg


Log in to reply