def __init__(self): # Holds current open Bézier path. self._path = None self._fill = blackColor self._stroke = noColor self._strokeWidth = 0 self._textFill = blackColor self._textStroke = noColor self._textStrokeWidth = 0 self._font = DEFAULT_FONT_PATH self._fontSize = DEFAULT_FONT_SIZE self._frameDuration = 0 # Origin set by self.translate() self._ox = pt(0) self._oy = pt(0) self._rotationCenter = (0, 0) self._rotate = 0 self._hyphenation = True self._language = DEFAULT_LANGUAGE self._openTypeFeatures = None # FIXME: what type? # Stack of graphic states. self._gState = [] self.doc = None self.pages = [] self.page = None self.style = None self.units = Pt.UNIT
def useBabelStrings(): for contextId, context in ( ('DrawBot', DrawBotContext()), ('Flat', FlatContext())): W, H = pt(1000, 300) M = pt(100) EXPORT_PATH = '_export/UseBabelStrings-%s.pdf' % contextId # Create a page and set y on top margin. context.newPage(W, H) y = H - M cs = context.newString('Context: %s' % contextId, style={'textFill': color(0, 0, 1), 'fontSize': 36}) context.text(cs, (100, y)) y -= 20 # Create formatted string, with default settings of font, fontSize and textFill color bs = context.newString('This is a formatted BabelString') print(bs.__class__.__name__) context.text(bs, (100, y)) # FIXME: solve for Flat. # Add string with formatting style dict bs += context.newString('\nAdd an other string with color/size format', style=dict(textFill=color(1, 0, 0), fontSize=20, leading=em(1.4))) print(bs) y -= 50 context.text(bs, (100, y)) context.saveImage(EXPORT_PATH)
def oneColumnPage(fontStyle, textString, PageDescription, pageNumber): astring = context.newString(textString, style=dict(font=fontStyle, xTextAlign=CENTER, fontSize=fontSizeH1, leading=pt(163))) page.padding = pagePaddings padd = pt(100) PW2 = W - 2 * padd newTextBox(astring, pt=pt(130), w=PW2, h=H, hyphenation=False, parent=page, conditions=(Center2Center(), Middle2Middle())) newTextBox(PageDescription, style=subtitle, w=PW, hyphenation=False, h=PH, parent=page, columnAlignY=TOP, conditions=(Left2Left(), Top2Top())) newTextBox(pageNumber, style=subtitle, xTextAlign=RIGHT, w=50, h=PH, parent=page, columnAlignY=TOP, conditions=(Right2Right(), Top2Top())) #newTextBox('144pt', style=subtitle, xTextAlign=CENTER, w=200, h=50, parent=page, columnAlignY = TOP, conditions=(Center2Center(), Top2Top())) doc.solve()
def textSize(self, bs, w=None, h=None): """Answer the size tuple (w, h) of the current text. Answer (0, 0) if there is no text defined. Answer the height of the string if the width w is given. >>> w = h = 500 # Default to pt-units >>> x = y = 0 >>> context = FlatContext() >>> context.newDocument(w, h) >>> context.newPage(w, h) >>> style = dict(font='Roboto-Regular', fontSize=12) # Number defaults to pt-unit >>> bs = context.newString('ABC ' * 100, style=style) >>> t = context.page.place(bs.s) >>> t = t.frame(x, y, w, h) # Numbers default to pt-units >>> t.overflow() False >>> bs = context.newString('ABC ' * 100000, style=style) >>> t = context.page.place(bs.s) >>> t = t.frame(x, y, w, h) >>> t.overflow() True >>> lines = t.lines() >>> #len(lines) 35 """ # FIXME! This is a totally wrong boilerplate for now! #t = placedtext(bs.s) if not bs.s: return (pt(0), pt(0)) elif w is None: return (pt(100), pt(100)) else: return (w, w / len(bs))
def drawString(self, bs, p): """Draws the BabelString at position p. >>> from pagebot.contexts import getContext >>> from pagebot.toolbox.units import pt, em >>> from pagebot.document import Document >>> from pagebot.elements import * >>> context = getContext() >>> style = dict(font='PageBot-Regular', fontSize=pt(100), leading=em(1)) >>> bs = BabelString('Hkpx'+chr(10)+'Hkpx', style, context=context) >>> context.drawString(bs, pt(100, 100)) """ if not isinstance(bs, BabelString): try: bs = self.asBabelString(bs) except TypeError as e: print('TypeError: %s is not a string compatible type, %s' % (type(bs), e)) return if bs._w is None and bs._h is None: x, y = p p = (pt(x), pt(y)) self.text(bs, p) else: x, y = p x = pt(x) y = pt(y) # x, y = point2D(upt(p)) box = (x, y, bs.w or DEFAULT_WIDTH, bs.h or 1000) self.textBox(bs, box)
def run(): w, h = pt(1000, 400) # Make a list of Unit pt instances and unpack them. context.newPage(W, H) txt = "Hello World" x, y = pt(10, 100) # Position of the text. # draw the text. bs = context.newString(txt, style=dict(fontSize=pt(300), font="Verdana")) context.text(bs, (x, y)) # calculate the size of the text. textWidth, textHeight = bs.size # set a red stroke color strokeColor = color( 1, 0, 0) # Color instance can translate into any other color type. context.stroke(strokeColor) # loop over all font metrics for metric in (0, bs.fontDescender, bs.fontAscender, bs.fontXHeight, bs.fontCapHeight): # Draw a red line with the size of the drawn text # Context drawing functions expect measures to be Unit instances. p1 = pt(x, y + metric) # Make a list of 2 Pt instances. p2 = pt(W - 2 * x, y + metric) context.line(p1, p2)
def _SketchLayoutGrid2Element(self, sketchLayoutGrid, e): """ type GridLayout = { _class: 'layoutGrid', isEnabled: bool, + columnWidth: number, --> cw drawHorizontal: bool, drawHorizontalLinesL bool, drawVertical: bool, + gutterHeight: number, --> gh + gutterWidth: number, --> gw guttersOutside: bool, + horizontalOffset: number, --> e.ml + numberOfColumns: number, --> cols + rowHeightMultiplication: number, --> ch totalWidth: number resizesContent: bool, """ if sketchLayoutGrid is None: return [], [] e.ml = sketchLayoutGrid.get('horizontalOffset', pt(36)) gw = sketchLayoutGrid.get('gutterWidth', pt(12)) gh = sketchLayoutGrid.get('gutterHeight', pt(12)) cw = sketchLayoutGrid.get('columnWidth', pt(60)) ch = sketchLayoutGrid.get('rowHeightMultiplication', 4) * gh cols = sketchLayoutGrid.get('numberOfColumns', 3) gridX = [] x = 0 for n in range(int(e.w/(cw + gw))): gridX.append((cw, gw)) gridY = [] return gridX, gridY
def _get_size(self): u"""Answer the size tuple (w, h) of the string.""" if hasattr(self.context.b, 'textSize'): ts = self.context.b.textSize(self.s) return pt(ts) else: return pt(0, 0)
def __init__(self): """Constructor of SvgContext. >>> context = SvgContext() >>> context.newPage(1000, 1000) >>> context.saveDrawing('_export/SvgContext.%s' % FILETYPE_SVG) """ super().__init__() self.b = svgBuilder self.name = self.__class__.__name__ self._language = DEFAULT_LANGUAGE self._filePath = self.TMP_PATH % uniqueID() self.fill(noColor) # Sets self._svgFill self.stroke(noColor) # Sets self._svgStroke self._strokeWidth = pt(0) self._frameDuration = seconds(1) self._fontSize = DEFAULT_FONT_SIZE self._font = getDefaultFontPath() self._ox = pt(0) # Origin set by self.translate() self._oy = pt(0) self._rotate = 0 self._gState = [] # Stack of graphic states. self.save() # Save current set of values on gState stack. self._numberOfPages = 1 self._bezierpath = None # Hold current open SVG path self._w = None self._h = None self.drawing = []
def drawElementOrigin(self, e, origin): if not (self.showOrigin or e.showOrigin): return context = self.context px, py, _ = pointOffset(e.origin, origin) S = e.css('viewInfoOriginMarkerSize', pt(5)) # Draw origin of the element fill = e.css('viewInfoOriginMarkerFill', noColor) stroke = e.css('viewInfoOriginMarkerStroke', blackColor) width = e.css('viewInfoOriginMarkerStrokeWidth', pt(0.25)) context.fill( fill ) # Transparant fill, so we can see the marker on dark backgrounds. context.stroke(stroke, width) context.oval(px - S, py - S, 2 * S, 2 * S) context.line((px - S, py), (px + S, py)) context.line((px, py - S), (px, py + S)) if (self.showDimensions and e.isPage) or e.showDimensions: bs = context.newString(e.xy, style=dict( font=self.css('viewInfoFont'), fontSize=self.css('viewInfoFontSize'), leading=self.css('viewInfoLeading'), textFill=color(0.1))) w, h = bs.size context.text(bs, (px - w / 2, py + S * 1.5))
def outDocumentStyles(self, doc): """If there are @doc styles defined, then export them as paragraph styles JS such as pbDoc.paragraphStyles.add({name:"Title", appliedFont:"Upgrade", fontStyle:'Bold', justification:Justification.CENTER_ALIGN, pointSize:300, leading:300, fillColor: pbGetColor(pbDoc, [255, 255, 255])}); >>> from pagebot.toolbox.color import color >>> from pagebot.toolbox.units import pt >>> from pagebot.fonttoolbox.objects.font import findFont >>> from pagebot.document import Document >>> from indesigncontext.context import InDesignContext >>> context = InDesignContext() >>> font = findFont('Upgrade-Regular') >>> styles = dict(h1=dict(font=font, fontSize=pt(12), leading=pt(14), textFillColor=color(1, 0, 0))) >>> doc = Document(w=500, h=800, context=context) >>> doc.styles = styles # Overwrite all default styles. >>> context.b.outDocumentStyles(doc) >>> #context.b.getOut() """ self._out('/* Paragraph styles */') for name, style in doc.styles.items(): self._out('pbDoc.paragraphStyles.add({name:"%s",' % name) if 'font' in style: font = style['font'] if not isinstance( font, str): # For now, only with real Font objects. self._out('\tappliedFont:"%s",' % font.info.familyName) self._out('\tfontStyle:"%s",' % font.info.styleName) if 'fontSize' in style: fontSize = pt(style['fontSize']) self._out('\tpointSize:"%s",' % style['fontSize']) if 'leading' in style: leading = style['leading'] leading.base = style.get('fontSize', DEFAULT_FONT_SIZE) self._out('\tleading:"%s",' % pt(leading)) if 'textFill' in style: fillColor = style['textFill'] if fillColor.isCmyk: c, m, y, k = fillColor.cmyk self._out( '\tfillColor: pbGetColor(pbDoc, [%s, %s, %s, %s]),' % (c * 100, m * 100, y * 100, k**100)) else: # Round other colors to rgb output. r, g, b = fillColor.rgb self._out('\tfillColor: pbGetColor(pbDoc, [%s, %s, %s]),' % (r * 255, g * 255, b * 255)) if 'textStroke' in style: strokeColor = style['textStroke'] if fillColor.isCmyk: c, m, y, k = strokeColor.cmyk self._out( '\tstrokeColor: pbGetColor(pbDoc, [%s, %s, %s, %s]),' % (c * 100, m * 100, y * 100, k**100)) else: # Round other colors to rgb output. r, g, b = strokeColor.rgb self._out( '\tstrokeColor: pbGetColor(pbDoc, [%s, %s, %s]),' % (r * 255, g * 255, b * 255)) self._out('});')
def secondColumnWaterfall(b, fontStyle): s = c.newString('', style=dict(font=f)) CW2 = (PW - (G*2))/3 # Column width for n in range(3): s += c.newString( b + '\n', style=dict(font=fontStyle, fontSize=pt(16+n*2), leading=pt((12+n*2)+6) )) newTextBox(s ,parent=page, w=CW2, h=pt(700),font=f, pt=pt(160), conditions=[Right2Right(),Top2Top()]) doc.solve()
def firstColumnWaterfall(b, fontStyle): s = c.newString('', style=dict(font=f)) CW2 = (PW - (G*2))/3 # Column width for n in range(4): s += c.newString( b + '\n', style=dict(font=fontStyle, fontSize=pt(12+n*1), leading=pt((12+n*1)+3) )) newTextBox(s ,parent=page, w=CW2, h=pt(700),font=f, pt=pt(160), nextElementName='e2',conditions=[Left2Left(),Top2Top(), Overflow2Next()]) doc.solve()
def testContext(context): doc = Document(w=W, h=H, context=context, autoPages=1) sq = 100 x = 0 y = 0 context.frameDuration(1) context.newDrawing() context.newPage(w=W, h=H) context.fill(f) context.stroke(s) context.translate(3*sq, 2*sq) context.scale(0.1) #context.rect(x, y, pt(sq), pt(sq)) context.circle(x, y, sq) #context.oval(x, y, sq, sq) #context.oval(x, y, sq, 2*sq) #context.oval(x, y, 2*sq, sq) #p0 = (x, y) #p1 = (x + 2*sq, y + sq) #context.line(p0, p1) font = findFont('Roboto-Black') glyphName = 'Q' glyph = font[glyphName] context.drawGlyphPath(glyph) context.translate(-3*sq, -sq) context.scale(3) context.rotate(10) context.rect(x, y, pt(sq), pt(sq)) path = '_export/Transformations-%s.pdf' % context.name context.saveImage(path)
def ensure_page(self): """ Flat function? """ if not self.doc: self.newDocument(pt(100), pt(100)) # Standardize FlatContext document on pt. if not self.pages: self.newPage(self.doc.width, self.doc.height)
def _getValidSize(self, w, h): """Answer a valid size for FlatContext document and pages. Make default page size, similar to DrawBot.""" if w is None or w < 0: w = pt(1000) if h is None or h < 0: h = pt(1000) return units(w), units(h)
def __init__(self, font=None, path=None, w=None, h=None, **kwargs): """ """ assert font is not None or path is not None if w is None: w = pt(self.DEFAULT_W) if h is None: h = pt(self.DEFAULT_H) DesignSpace.__init__(self, w=w, h=h, **kwargs) self.font = font self.path = path
def threeColumnPage(fontStyle1, fontStyle2, fontStyle3, textString, PageDescription): page.padding = pagePaddings CW3 = (W-120)/3 # Column width cstring = context.newString(textString, style=dict(font=fontStyle1, xTextAlign=CENTER, fontSize=pt(144), leading=pt(163))) dstring = context.newString(textString, style=dict(font=fontStyle2, xTextAlign=CENTER, fontSize=pt(144), leading=pt(163), hyphenation=None)) spreads= dict(font=fontStyle3, fontSize=pt(144), leading=pt(163)) newTextBox(cstring, w=(CW3+10), parent=page, conditions=[Left2Left(), Middle2Middle()]) newTextBox(textString, style=spreads, w=CW3, xTextAlign=CENTER, parent=page, conditions=[Center2Center(), Middle2Middle()]) newTextBox(dstring, w=CW3, parent=page, conditions=[Right2Right(), Middle2Middle()]) newTextBox(PageDescription, style=subtitle, w=PW, h=PH, parent=page, columnAlignY = TOP, conditions=(Left2Left(), Top2Top())) doc.solve()
def __init__(self, f, name=None, label=None, title=None, eId=None, c='F', s=1, strokeWidth=None, stroke=noColor, earSize=None, earLeft=True, earFill=None, cFill=None, cStroke=None, cStrokeWidth=None, labelFont=None, labelFontSize=None, titleFont=None, titleFontSize=None, show=True, **kwargs): """ >>> from pagebot.fonttoolbox.objects.font import getFont >>> from pagebot.fonttoolbox.fontpaths import getTestFontsPath >>> from pagebot.contexts.drawbotcontext import DrawBotContext >>> from pagebot.elements import newRect >>> from pagebot.document import Document >>> from pagebot.toolbox.color import color >>> c = DrawBotContext() >>> w, h = 300, 400 >>> doc = Document(w=w, h=h, autoPages=1, padding=30, originTop=False, context=c) >>> page = doc[1] >>> path = getTestFontsPath() + '/google/roboto/Roboto-Regular.ttf' # We know this exists in the PageBot repository >>> font = getFont(path) >>> iw, ih = w/4, h/4 >>> x, y = w/8, h/8 >>> fi = FontIcon(font, x=x, y=y, w=iw, h=ih, name="40k", earSize=0.3, earLeft=True, parent=page, stroke=blackColor, strokeWidth=3) >>> bg = newRect(x=w/2, w=w/2, h=h/2, fill=blackColor,parent=page) >>> fi = FontIcon(font, x=x, y=y, w=iw, h=ih, name="40k", c="H", cFill=color(0.5), earSize=0.3, earLeft=True, earFill=None, fill=color(1,0,0,0.5), parent=bg, stroke=color(1), strokeWidth=3) >>> doc.export('_export/FontIconTest.pdf') >>> doc.export('_export/FontIconTest.jpg') """ Element.__init__(self, **kwargs) self.f = f # Font instance if title is not None: self.title = title or "%s %s" % (f.info.familyName, f.info.styleName) self.titleFont = titleFont, labelFont or f self.titleFontSize = pt(28) self.labelFont = labelFont or f self.labelFontSize = labelFontSize or pt(10) self.label = label # Optiona second label line self.c = c # Character(s) in the icon. if cFill is None: cFill = blackColor self.cFill = cFill if cStroke is None: cStroke = blackColor self.cStroke = cStroke self.cStrokeWidth = cStrokeWidth or pt(1) self.scale = s self.show = show if stroke is not None: self.style["stroke"] = stroke if strokeWidth is not None: self.style["strokeWidth"] = strokeWidth self.earSize = earSize or 0.25 # 1/4 of width self.earLeft = earLeft if earFill is None: earFill = self.css("fill") self.earFill = earFill
def imageSize(self, path): """Answers the (w, h) image size of the image file at path. >>> from pagebot import getResourcesPath >>> imagePath = getResourcesPath() + '/images/peppertom_lowres_398x530.png' >>> context = FlatContext() >>> context.imageSize(imagePath) (398pt, 530pt) """ img = self.b.image.open(path) # Answer units of the same time as the document.w was defined. return pt(img.width), pt(img.height)
def build(self, view, origin, drawElements=True, **kwargs): """Draw the text on position (x, y). Draw background rectangle and/or frame if fill and/or stroke are defined.""" context = view.context # Get current context b = context.b # Get the page position, depending on the floated origin of the element. p = pointOffset(self.origin, origin) p = self._applyScale(view, p) px, py, _ = p = self._applyAlignment(p) # Ignore z-axis for now. # Use the standard frame drawing of Element, using the border settings of self. self.buildFrame(view, p) # Draw optional frame or borders. # Calculate the scaled width for self.glyph, depending on the em-square # of fonts. width = self.glyph.width / f.info.unitsPerEm * SQSIZE # Draw the vertical width line. Not dashed for now. context.fill(None) context.stroke(color(1, 0, 0), w=0.5) context.line((px + width, py), (px + width, py + SQSIZE)) # Calculate the position of the baseline of the glyph in the square, # using font.info.descender from bottom of the square. baseline = py - f.info.descender / f.info.unitsPerEm * SQSIZE # Create the string in size SQSIZE showing the glyph. t = context.newString(chr(self.uCode), style=glyphStyle) # Set stroke color and stroke width for baseline and draw it. context.stroke(color(0, 0, 0.5), w=0.5) context.line((px, baseline), (px + SQSIZE, baseline)) # Draw the glyph. context.text(t, (px, baseline)) # Construct the label from the original glyph, unicode and glyph name # (if available) label = context.newString( '%s (%d) %s' % (chr(self.uCode), self.uCode, self.glyph.name), style=labelStyle) # Get the size of the generated formatted string to center it. # Draw the label. tw, th = label.size context.text(label, (px + SQSIZE / 2 - tw / 2, py - pt(7))) # Construct the rotated width string on left and right side. widthLabel = context.newString('Width: %d' % self.glyph.width, style=labelStyle) leftLabel = context.newString('Offset: %d' % self.glyph.leftMargin, style=labelStyle) context.save() # Save the graphics state # Translate the origin to the current position of self, so we can rotate. context.translate(px, py) context.rotate(90) # Rotate clockwise vertical context.text(widthLabel, (0, -SQSIZE - pt(7))) # Draw labels on these positions context.text(leftLabel, (0, pt(3))) context.restore() # Restore the graphics state self._restoreScale(view)
def run(): s = """글자가 일상이 된다 산돌커뮤니케이션 ABCD123 Latin すべての文化集団は,独自の言語,文字,書記システムを持つ.それゆえ,個々の書記システムをサイバースペースに移転することは. ABCD123 Latin included""" context.newPage(pt(W), pt(H)) fsr = context.newString(s, style=dict(font='Verdana', fontSize=FontSize)) fsb = context.newString(s, style=dict(font='Verdana', fontSize=FontSize)) fsbRed = context.newString(s, style=dict(font='Verdana', fill=color(1, 0, 0), fontSize=FontSize)) context.textBox(fsr, (100, 600, 820, 350)) context.textBox(fsb, (100, 300, 820, 350)) context.textBox(fsbRed, (100, 0, 820, 350)) context.textBox(fsr, (100, 0, 820, 350))
def makeDocument(): """Make a new document.""" W = H = PageSize doc = Document(w=W, h=H, originTop=False, title='Color Squares', autoPages=1) view = doc.getView() view.padding = pt(0) # Aboid showing of crop marks, etc. view.showOrigin = False view.showTextOverflowMarker = False # Get list of pages with equal y, then equal x. #page = doc[1][0] # Get the single page from te document. page = doc.getPage(1) # Get page on pageNumber, first in row (this is only one now). page.name = 'This is a demo page for floating child elements' page.padding = PagePadding # Show margin of page, can also be done by # view.showPadding = True newRect(fill=color(0.9), parent=page, margin=0, conditions=(Left2Left(), Fit2Right(), Bottom2Bottom(), Fit2Height())) redContainer = newRect(fill=color(1, 0, 0), pb=pt(10), w=RedSize, h=RedSize, padding=pt(10), conditions=(Left2Left(), Bottom2Bottom()), parent=page) # Yellow square yellowSquare = newRect(fill=color(1, 1, 0), z=pt(8), w=YellowSize, h=YellowSize, parent=redContainer, xAlign=CENTER, yAlign=TOP, conditions=(Center2Center(), Bottom2Bottom())) # Blue square in different z=layer. No interaction with Floating on other z-layers. blueSquare = newRect(fill=color(0, 1, 1), z=10, w=50, h=50, parent=redContainer, xAlign=CENTER, conditions=(Top2Top(), Center2Center())) # Centered string fs = doc.context.newString('Float on top of yellow', style=dict(font='Verdana', fontSize=7, xTextAlign=CENTER, textFill=blackColor)) # Text falls through the yr2 (with differnt z) and lands on yellowSquare by Float2SideBottom() newTextBox(fs, name='Caption', parent=redContainer, z=8, fill=color(0, 1, 0), strokeWidth=0.5, stroke=color(1, 1, 0), conditions=[Fit2Width(), Float2SideBottom()], padding=3) score = page.solve() if score.fails: print(score.fails) return doc # Answer the doc for further doing.
def getTextLines(self, bs, w=None, h=None, ascDesc=False): """Answer a list of BabeLineInfo instances. >>> from pagebot.toolbox.units import pt >>> context = FlatContext() >>> style = dict(font='PageBot-Regular', fontSize=pt(20)) >>> bs = context.newString('ABCD ' * 100, style, w=pt(200)) >>> lines = context.getTextLines(bs) >>> len(lines) 34 >>> line = lines[10] >>> #line #<BabelLineInfo y=246pt> """ placedText = bs.cs.pt lines = [] if placedText.width != w or placedText.height != h: # Make reflow on this new (w, h) placedText.frame(0, 0, w or bs.w or math.inf, h or bs.h or math.inf) x = pt(0) # Relative vertical position y = None # In Flat "run" is native data for line. flatRuns = placedText.layout.runs() for height, flatLine in flatRuns: height = round(height) if y is None: y = height else: y += height babelLineInfo = BabelLineInfo(x, y, context=self, cLine=flatLine) for fst, s in flatLine: font = findFont(fst.font.name.decode("utf-8")) style = dict(font=font, fontSize=pt(fst.size), leading=pt(fst.leading), textFill=color(fst.color), tracking=pt(fst.tracking * fst.size)) babelRunInfo = BabelRunInfo( s, style, self, cRun=fst) # Cache the flatStyle, just in case. babelLineInfo.runs.append(babelRunInfo) lines.append(babelLineInfo) return lines
def draw(self): for n in range(self.steps): c.newPage(pt(W), pt(H)) # Formattted string using append. print(' * Testing with append') bs = c.newString('') # Contains a DrawBot FormattedString. aa = bs.s aa.append("123", font="Helvetica", fontSize=100, fill=(1, 0, 1)) print(aa._font) print(aa._fontSize) print(aa._fill) c.text(bs, (pt(100), pt(100))) # Formatted string without append. print(' * Testing without append') bs = c.newString('bla', style=dict(font='Helvetica', fontSize=pt(100), fill=0)) print('style: %s' % bs.style) aa = bs.s print(aa._font) print(aa._fontSize) #c.setTextFillColor(aa, blackColor) print(aa._fill) c.b.text(aa, (100, 200)) c.text(bs, (100, 200)) """ self.drawBackground() if self.drawBackgroundHook is not None: self.drawBackgroundHook(self, n) """ for o in self.objects: offsetX = 0 offsetY = 0 if o.eId in self.positions: # Changed target, then calculate new offset tx, ty = self.positions[o.eId] offsetX = (tx-o.x)*1.0*n/self.steps offsetY = (ty-o.y)*1.0*n/self.steps o.draw(offsetX, offsetY) # Set the new target positions. for o in self.objects: if o.eId in self.positions: tx, ty = self.positions[o.eId] o.x = tx o.y = ty
def getText(s): style1 = dict(font=font, fontSize=36, leading=pt(40), textFill=whiteColor, xTextAlign=CENTER) style2 = dict(font=font, fontSize=10, leading=pt(12), textFill=blackColor, xTextAlign=CENTER) t = doc.context.newString('TEXT', style=style1) t += doc.context.newString('\n' + s, style=style2) return t
def __init__(self, **kwargs): BaseBusinessCard.__init__(self, **kwargs) context = self.doc.context mood = self.idData['theme'].mood bodyStyle = mood.getStyle('body') captionStyle = mood.getStyle('caption') logoStyle = mood.getStyle('logo') page = self.getDocument(name='BaseBusinessCard')[1] page.padding = self.padding = p(1) bs = context.newString(self.idData['logo'], style=logoStyle) bs += context.newString(' ' + self.idData['name'], style=bodyStyle) tw, th = bs.size e = newTextBox(bs, parent=page, w=tw, stroke=noColor, fill=0.7, conditions=[Left2Left(), Top2Top()]) print('===', e.x, tw, th, e.w, e.h) bs = context.newString(self.person['name'], style=bodyStyle) bs += context.newString('\n' + self.person['position'], style=captionStyle) bs += context.newString('\n\n' + self.person['addressStreet'], style=captionStyle) bs += context.newString('\n' + self.person['addressCity'], style=captionStyle) bs += context.newString('\n' + self.person['addressTelephone'], style=captionStyle) newTextBox(bs, parent=page, fill=noColor, stroke=noColor, conditions=[Left2Left(), Fit2Width(), Middle2Middle()]) self.showFrame = True self.showPadding = True self.showCropMarks = True self.showRegistrationMarks = True self.viewCropMarkSize = pt(16) self.viewCropMarkDistance = pt(8) page.solve() print('+++', e.x)
def text(self, bs, p): """Place the babelstring instance at position p. The position can be any 2D or 3D points tuple. Currently the z-axis is ignored """ #msg = 'InDesignString.text: bs not of type %s' % InDesignString.__name__ #assert isinstance(bs, InDesignString), msg # TODO: get text dimensions or element dimensions. self.addJs('var currentTextFrame = currentTextFrames.add();') p3 = self.w - self.margin p4 = self.h - self.margin self.addJs( 'currentTextFrame.geometricBounds = ["%s", "%s", "%s", "%s"];' % (p[0], p[1], pt(p3), pt(p4))) self.addJs('currentTextFrame.contents = "%s";' % bs)
def makePage2(page, font): border = dict(stroke=blackColor, strokeWidth=pt(0.5)) r = newRect(parent=page, conditions=[Fit()]) fullName = '%s %s' % (font.info.familyName, font.info.styleName) style = dict(font=font, fontSize=pt(24), xTextAlign=CENTER) bs = context.newString(fullName.upper(), style=style) newTextBox(bs, parent=r, borderTop=border, borderBottom=border, margin=0, padding=0, conditions=[Left2Left(), Top2Top(), Fit2Width()])
def getDocument(self): """Answer the document that fits the current UI settings.""" w, h = self.getPaperSize() name = self.getDocumentName() padding = self.getPadding() gridX, gridY = self.getGrid(w, h, padding) # Make a new Document instance for export doc = Document(w=w, h=h, autoPages=1, padding=padding, originTop=False, gridX=gridX, gridY=gridY, context=context) view = doc.view view.showCropMarks = showMarks = bool( self.uiDesign.showCropMarks.get()) view.showRegistrationMarks = showMarks view.showNameInfo = showMarks view.showColorBars = bool(self.uiDesign.showColorBars.get()) #view.showBaselineGrid = bool(self.window.group.showBaselineGrid.get()) if bool(self.uiDesign.showGrid.get()): view.showGrid = GRID_COL else: view.showGrid = False view.showPadding = bool(self.uiDesign.showPagePadding.get()) view.showFrame = bool(self.uiDesign.showPageFrame.get()) if showMarks: # Needs padding outside the page? view.padding = pt(48) else: view.padding = 0 return doc